diff --git a/.changes/unreleased/Added-20241129-164631.yaml b/.changes/unreleased/Added-20241129-164631.yaml new file mode 100644 index 000000000..cec797027 --- /dev/null +++ b/.changes/unreleased/Added-20241129-164631.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Tool use +time: 2024-11-29T16:46:31.677532-08:00 diff --git a/.changes/unreleased/Added-20241129-164644.yaml b/.changes/unreleased/Added-20241129-164644.yaml new file mode 100644 index 000000000..7dfa427dd --- /dev/null +++ b/.changes/unreleased/Added-20241129-164644.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Model Context Protocol +time: 2024-11-29T16:46:44.960691-08:00 diff --git a/.continueignore b/.continueignore index 7e0d0c115..79e924012 100644 --- a/.continueignore +++ b/.continueignore @@ -4,4 +4,5 @@ docs/docs/languages .idea/ .vscode/ .archive/ -**/*.scm \ No newline at end of file +**/*.scm +**/*.diff \ No newline at end of file diff --git a/binary/package-lock.json b/binary/package-lock.json index a27e6ee97..c855ad5d1 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -49,6 +49,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -59,7 +60,7 @@ "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", - "dbinfoz": "^0.11.0", + "dbinfoz": "^0.14.0", "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", @@ -82,6 +83,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index f77efae6e..a6e1e551b 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -3,6 +3,7 @@ import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { IDE, ILLM } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; +import { EXPERIMENTS, PosthogFeatureFlag, Telemetry } from "../util/posthog.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; @@ -66,7 +67,11 @@ export class CompletionProvider { // Set temperature (but don't override) if (llm.completionOptions.temperature === undefined) { - llm.completionOptions.temperature = 0.01; + const value = await Telemetry.getValueForFeatureFlag( + PosthogFeatureFlag.AutocompleteTemperature, + ); + + llm.completionOptions.temperature = value ?? 0.01; } if (llm instanceof OpenAI) { diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index a94e37e38..93648653f 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -10,13 +10,13 @@ import { IGNORE_PATH_PATTERNS, LanguageName, } from "../../../util/treeSitter"; -import { AstPath } from "../../util/ast"; -import { ImportDefinitionsService } from "../ImportDefinitionsService"; -import { AutocompleteSnippetDeprecated } from "../../types"; import { AutocompleteCodeSnippet, AutocompleteSnippetType, } from "../../snippets/types"; +import { AutocompleteSnippetDeprecated } from "../../types"; +import { AstPath } from "../../util/ast"; +import { ImportDefinitionsService } from "../ImportDefinitionsService"; function getSyntaxTreeString( node: Parser.SyntaxNode, @@ -112,7 +112,6 @@ export class RootPathContextService { ); snippets.push(...newSnippets); } catch (e) { - debugger; throw e; } } diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index da178cb66..55cde067a 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -6,7 +6,7 @@ import { stopAtStartOf, stopAtStopTokens } from "./charStream"; import { avoidEmptyComments, avoidPathLine, - noDoubleNewlineAfterClosingBracket, + noDoubleNewLine, showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, @@ -49,7 +49,7 @@ export class StreamTransformPipeline { ); lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); lineGenerator = skipPrefixes(lineGenerator); - lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator); + lineGenerator = noDoubleNewLine(lineGenerator); for (const lineFilter of helper.lang.lineFilters ?? []) { lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); diff --git a/core/autocomplete/filtering/streamTransforms/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts index d82d9dbac..4485b5a29 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.test.ts @@ -171,46 +171,45 @@ describe("stopAtStartOf", () => { controlPlaneEnv.CONTROL_PLANE_URL, ), `; + /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */ it("should stop if the start of the suffix is reached", async () => { - const removeLength = 10; - for (let i = 0; i < sampleCode.length - removeLength - 20; i++) { - const removed = sampleCode.slice(i, i + removeLength); - const suffix = sampleCode.slice(i + removeLength); - const response = removed + suffix; + const suffix = ` + const data = await response.json(); + return data.items; +}`; + const mockStream = createMockStream(sampleCode.split(/(?! )/g)); + const result = stopAtStartOf(mockStream, suffix); - // split the response but keep spaces - const mockStream = createMockStream(response.split(/(?! )/g)); - const result = stopAtStartOf(mockStream, suffix); - - const resultStr = await streamToString(result); - if (resultStr !== removed) { - throw new Error( - `i=${i} result:\n${resultStr}\n\nremoved:\n${removed}\n\nsuffix:\n${suffix}`, - ); - } - } + const resultStr = await streamToString(result); + expect(resultStr).toBe(` { + method: "GET", + headers: { + "Content-Type": "application/json", + Authorization: \`Bearer \${this.workOsAccessToken}\`, + }, + }, + ); + `); }); it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => { - const removeLength = 10; - for (let i = 0; i < sampleCode.length - removeLength - 20; i++) { - const removed = sampleCode.slice(i, i + removeLength); - let suffix = sampleCode.slice(i + removeLength); - const response = removed + suffix; - // add a prefix to the suffix - suffix = "strange words;\n which start the suffix#" + suffix; + const suffix = ` + xxxconst data = await response.json(); + return data.items; +}`; + const mockStream = createMockStream(sampleCode.split(/(?! )/g)); + const result = stopAtStartOf(mockStream, suffix); - // split the response but keep spaces - const mockStream = createMockStream(response.split(/(?! )/g)); - const result = stopAtStartOf(mockStream, suffix); - - const resultStr = await streamToString(result); - if (resultStr !== removed) { - throw new Error( - `i=${i} result:\n${resultStr}\n\nremoved:\n${removed}\n\nsuffix:\n${suffix}`, - ); - } - } + const resultStr = await streamToString(result); + expect(resultStr).toBe(` { + method: "GET", + headers: { + "Content-Type": "application/json", + Authorization: \`Bearer \${this.workOsAccessToken}\`, + }, + }, + ); + `); }); }); diff --git a/core/autocomplete/filtering/streamTransforms/charStream.ts b/core/autocomplete/filtering/streamTransforms/charStream.ts index f4b751ff9..9177a9716 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.ts @@ -119,8 +119,9 @@ export async function* stopAtStopTokens( } /** - * Asynchronously yields characters from the input stream, stopping if a sequence contained in the beginning of the suffix is encountered. - * */ + * Asynchronously yields characters from the input stream. + * Stops if the beginning of the suffix is detected in the stream. + */ export async function* stopAtStartOf( stream: AsyncGenerator, suffix: string, @@ -132,42 +133,31 @@ export async function* stopAtStartOf( } return; } + // We use sequenceLength * 1.5 as a heuristic to make sure we don't miss the sequence if the + // stream is not perfectly aligned with the sequence (small whitespace differences etc). + const targetPart = suffix + .trimStart() + .slice(0, Math.floor(sequenceLength * 1.5)); - const n = Math.min(suffix.length, 3 * sequenceLength); - let prev = new Array(n + 1).fill(0); - let res = 0; let buffer = ""; for await (const chunk of stream) { - const s1 = chunk; - const m = chunk.length; - for (let i = 1; i <= m; i++) { - // Create a temporary array to store the current row - let curr = new Array(n + 1).fill(0); - for (let j = 1; j <= n; j++) { - if (s1[i - 1] === suffix[j - 1]) { - curr[j] = prev[j - 1] + 1; - res = Math.max(res, curr[j]); - } else { - curr[j] = 0; - } - } + buffer += chunk; - // Move the current row's data to the previous row - prev = curr; + // Check if the targetPart contains contains the buffer at any point + if (buffer.length >= sequenceLength && targetPart.includes(buffer)) { + return; // Stop processing when the sequence is found + } - if (res > sequenceLength) { - return; - } - - buffer += s1[i - 1]; - - while (buffer.length > sequenceLength) { - yield buffer[0]; - buffer = buffer.slice(1); - } + // Yield chunk by chunk, ensuring not to exceed sequenceLength in the buffer + while (buffer.length > sequenceLength) { + yield buffer[0]; + buffer = buffer.slice(1); } } - yield buffer; + // Yield the remaining buffer if it is not contained in the `targetPart` + if (buffer.length > 0) { + yield buffer; + } } diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 9cbf190ec..aaeec1291 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -537,53 +537,32 @@ export async function* showWhateverWeHaveAtXMs( ms: number, ): LineStream { const startTime = Date.now(); + let firstNonWhitespaceLineYielded = false; + for await (const line of lines) { - // Always get at least one line yield line; - // But after that, soft break at X ms - if (Date.now() - startTime > ms) { + if (!firstNonWhitespaceLineYielded && line.trim() !== "") { + firstNonWhitespaceLineYielded = true; + } + + const isTakingTooLong = Date.now() - startTime > ms; + if (isTakingTooLong && firstNonWhitespaceLineYielded) { break; } } } -export async function* noDoubleNewlineAfterClosingBracket( - lines: LineStream, -): LineStream { - const bracketTypeCounts = new Map(); +export async function* noDoubleNewLine(lines: LineStream): LineStream { + let isFirstLine = true; for await (const line of lines) { - if (line.trim() === "") { - // Double newline detected - // Check if any bracket counts are negative - let hasNegativeCount = false; - for (const count of bracketTypeCounts.values()) { - if (count < 0) { - hasNegativeCount = true; - break; - } - } - if (hasNegativeCount) { - // Stop the generator if we've closed brackets we didn't open - return; - } + if (line.trim() === "" && !isFirstLine) { + return; } + isFirstLine = false; + yield line; - - // Update bracket counts - for (const char of line) { - if (BRACKETS[char]) { - // It's an opening bracket - const count = bracketTypeCounts.get(char) || 0; - bracketTypeCounts.set(char, count + 1); - } else if (BRACKETS_REVERSE[char]) { - // It's a closing bracket - const openingBracket = BRACKETS_REVERSE[char]; - const count = bracketTypeCounts.get(openingBracket) || 0; - bracketTypeCounts.set(openingBracket, count - 1); - } - } } } diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 33924b1b3..277c8cdc8 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -110,6 +110,7 @@ Here is a list of features: - Feature 2`, }, { + // options: { only: true }, description: "Should autocomplete a Java method within a class", filename: "Calculator.java", input: ` @@ -150,37 +151,7 @@ public class Calculator { POSTGRES_DB: mydb `, expectedCompletion: ` - POSTGRES_DB: mydb - `, - }, - { - description: - "Should filter out suffix generated by LLM (sample from Codestral)", - filename: "test.js", - input: ` - add(number) { - this.result += number; - return this; - } - // Add the subtract method - subtract(number) {<|fim|> - - subtract(number) { - this.result -= number; - return this; - } - - multiply(number) { - this.result *= number; - return this; - }`, - llmOutput: ` this.result -= number; - return this; - } - // Add the multiply method - multiply(number) { - `, - expectedCompletion: undefined, + POSTGRES_DB: mydb`, }, { description: "Should enforce bracket matching in JSON files", @@ -283,8 +254,7 @@ async getContextForPath( ): Promise { const snippets: AutocompleteCodeSnippet[] = []; `, - expectedCompletion: `console.log('TEST'); - `, + expectedCompletion: `console.log('TEST');`, }, { description: "Should autocomplete React effect hook", @@ -333,6 +303,82 @@ export const Timer = () => { llmOutput: ` this;`, expectedCompletion: `this;`, }, + { + description: "Should complete YAML list item and preserve structure", + filename: "test.yaml", + input: ` + services: + - name: web + image: nginx + - name: app<|fim|> + volumes: + - volume1 + - volume2 + `, + llmOutput: ` + image: node + `, + expectedCompletion: ` + image: node`, + }, + { + description: + "Should complete YAML key-value pair inside a nested structure", + filename: "test.yaml", + input: ` + version: '3' + services: + db: + image: postgres + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass + POSTGRES_DB: mydb<|fim|> + `, + llmOutput: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + expectedCompletion: ` + PGDATA: /var/lib/postgresql/data/pgdata`, + }, + { + description: "Should complete YAML block within an existing block", + filename: "test.yaml", + input: ` + pipelines: + branches: + master: + - step: + name: Build and Test + script: + - npm install + - npm run test + - step: + name: Deploy<|fim|> + `, + llmOutput: ` + script: + - npm run deploy + `, + expectedCompletion: ` + script: + - npm run deploy`, + }, + { + description: + "Should autocomplete SQL query with subquery and alias in SELECT clause", + filename: "complex_query.sql", + input: `SELECT u.id, + u.name, + (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count + FROM users u + WHERE u.active = 1 + <|fim|>`, + llmOutput: + " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", + expectedCompletion: + "AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", + }, ]; export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [ @@ -832,21 +878,6 @@ func main() { llmOutput: " DEFAULT", expectedCompletion: " DEFAULT", }, - { - description: - "Should autocomplete SQL query with subquery and alias in SELECT clause", - filename: "complex_query.sql", - input: `SELECT u.id, - u.name, - (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count - FROM users u - WHERE u.active = 1 - <|fim|>`, - llmOutput: - " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", - expectedCompletion: - " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)", - }, { description: "Should autocomplete multi-line SQL query with CASE statements", @@ -1030,70 +1061,6 @@ Smart<|fim|>`, llmOutput: "ob, 2023-02-10", expectedCompletion: "ob, 2023-02-10", }, - { - description: "Should complete YAML list item and preserve structure", - filename: "test.yaml", - input: ` - services: - - name: web - image: nginx - - name: app<|fim|> - volumes: - - volume1 - - volume2 - `, - llmOutput: ` - image: node - `, - expectedCompletion: ` - image: node - `, - }, - { - description: - "Should complete YAML key-value pair inside a nested structure", - filename: "test.yaml", - input: ` - version: '3' - services: - db: - image: postgres - environment: - POSTGRES_USER: user - POSTGRES_PASSWORD: pass - POSTGRES_DB: mydb<|fim|> - `, - llmOutput: ` - PGDATA: /var/lib/postgresql/data/pgdata - `, - expectedCompletion: ` - PGDATA: /var/lib/postgresql/data/pgdata - `, - }, - { - description: "Should complete YAML block within an existing block", - filename: "test.yaml", - input: ` - pipelines: - branches: - master: - - step: - name: Build and Test - script: - - npm install - - npm run test - - step: - name: Deploy<|fim|> - `, - llmOutput: ` - script: - - npm run deploy - `, - expectedCompletion: ` - script: - - npm run deploy - `, - }, { description: "Should autocomplete a Rust function implementation inside a struct", @@ -2168,4 +2135,70 @@ export default { llmOutput: "}", expectedCompletion: "}", }, + { + description: + "Should handle autocomplete in two similar TypeScript functions", + filename: "List.svelte", + input: ` +import { createClient, RedisClientType } from "redis"; +import { IKeyValueStore } from "./index.js"; + +export class RedisKeyValueStore implements IKeyValueStore { + private client: RedisClientType; + + constructor(redisUrl: string) { + this.client = createClient({ + url: redisUrl + .replace("https://", "redis://") + .replace("http://", "redis://"), + }); + this.client.on("connect", () => console.log("Redis Connected")); + this.client.on("error", (err) => console.log("Redis Client Error", err)); + this.client.connect(); + } + public async has(tableName: string, key: string): Promise { + return (await this.client.exists(this._getKey(tableName, key))) > 0; + } + + public async keys(tableName: string): Promise { + const keys = await this.client.keys(this._getTableKey(tableName)); + return keys.map((key) => key.split("::")[1]); + } + + public async put( + tableName: string, + key: string, + value: string, + ): Promise { + await this.client.set(this._getKey(tableName, key), value); + } + + public async get( + tableName: string, + key: string, + ): Promise { + const value = await this.client.get(this._getKey(tableName, key)); + return value ?? undefined; + } + + public async deleteAll(tableName: string): Promise { + await this.client.del(this._getTableKey(tableName)); + } + +<|fim|> + + + public async remove(tableName: string, key: string): Promise { + const result = await this.client.del(this._getKey(tableName, key)); + return result > 0; + } +} +`, + llmOutput: ` public async delete(tableName: string, key: string): Promise { + await this.client.del(this._getKey(tableName, key)); + }`, + expectedCompletion: ` public async delete(tableName: string, key: string): Promise { + await this.client.del(this._getKey(tableName, key)); + }`, + }, ]; diff --git a/core/autocomplete/generation/ListenableGenerator.test.ts b/core/autocomplete/generation/ListenableGenerator.test.ts index 9dc6cc893..916d8dbef 100644 --- a/core/autocomplete/generation/ListenableGenerator.test.ts +++ b/core/autocomplete/generation/ListenableGenerator.test.ts @@ -1,4 +1,5 @@ import { jest } from "@jest/globals"; + import { ListenableGenerator } from "./ListenableGenerator"; describe("ListenableGenerator", () => { diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index 1eb3b37da..ed7c41f05 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -43,11 +43,15 @@ function isExtremeRepetition(completion: string): boolean { } return false; } -export function isOnlyWhitespace(completion: string): boolean { +function isOnlyWhitespace(completion: string): boolean { const whitespaceRegex = /^[\s]+$/; return whitespaceRegex.test(completion); } +function isBlank(completion: string): boolean { + return completion.trim().length === 0; +} + export function postprocessCompletion({ completion, llm, @@ -60,6 +64,11 @@ export function postprocessCompletion({ suffix: string; }): string | undefined { // Don't return empty + if (isBlank(completion)) { + return undefined; + } + + // Don't return whitespace if (isOnlyWhitespace(completion)) { return undefined; } @@ -112,11 +121,8 @@ export function postprocessCompletion({ // } // If prefix ends with space and so does completion, then remove the space from completion - if ( - prefix.split("\n").pop()?.trim() !== "" && - prefix.endsWith(" ") && - completion.startsWith(" ") - ) { + + if (prefix.endsWith(" ") && completion.startsWith(" ")) { completion = completion.slice(1); } diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index bc85fb909..a6cdf0957 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -46,7 +46,7 @@ export const getSnippets = ( ...payload.clipboardSnippets, ...shuffleArray( filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets], + [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], helper.prunedCaretWindow, ), ), diff --git a/core/autocomplete/templating/formatting.ts b/core/autocomplete/templating/formatting.ts index be7fe7a15..bdbe56c50 100644 --- a/core/autocomplete/templating/formatting.ts +++ b/core/autocomplete/templating/formatting.ts @@ -13,12 +13,14 @@ const getCommentMark = (helper: HelperVars) => { }; const addCommentMarks = (text: string, helper: HelperVars) => { + const commentMark = getCommentMark(helper); const lines = [ ...text .trim() .split("\n") - .map((line) => `${getCommentMark(helper)} ${line}`), + .map((line) => `${commentMark} ${line}`), ]; + return lines.join("\n"); }; @@ -61,11 +63,6 @@ const commentifySnippet = ( }; }; -const SNIPPET_TYPES_TO_COMMENT = [ - AutocompleteSnippetType.Code, - AutocompleteSnippetType.Clipboard, -]; - export const formatSnippets = ( helper: HelperVars, snippets: AutocompleteSnippet[], @@ -88,19 +85,7 @@ export const formatSnippets = ( } }) .map((item) => { - if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) { - return commentifySnippet(helper, item); - } - - return item; - }) - .map((item) => { - if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) { - const commentMark = getCommentMark(helper); - return item.content + `\n${commentMark}\n${commentMark}`; - } - - return item.content; + return commentifySnippet(helper, item).content; }) .join("\n") + `\n${currentFilepathComment}` ); diff --git a/core/autocomplete/templating/getStopTokens.ts b/core/autocomplete/templating/getStopTokens.ts index 85131953b..ece0a73b4 100644 --- a/core/autocomplete/templating/getStopTokens.ts +++ b/core/autocomplete/templating/getStopTokens.ts @@ -10,7 +10,7 @@ const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; const PYTHON_ENCODING = "#- coding: utf-8"; const CODE_BLOCK_END = "```"; -const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; +// const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; export function getStopTokens( diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 8a2cfaae4..8aaa98248 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -10,7 +10,6 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; -import { AutocompleteCodeSnippet } from "../snippets/types"; import { SnippetPayload } from "../snippets"; import { formatSnippets } from "./formatting"; import { getSnippets } from "./filtering"; diff --git a/core/commands/index.ts b/core/commands/index.ts index cb5e162f7..492b7f90a 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,6 +1,6 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; -import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; +import { renderChatMessage } from "../util/messageContent"; import SlashCommands from "./slash"; @@ -29,7 +29,8 @@ export function slashFromCustomCommand( const messages = [...history]; // Find the last chat message with this slash command and replace it with the user input for (let i = messages.length - 1; i >= 0; i--) { - const { role, content } = messages[i]; + const message = messages[i]; + const { role, content } = message; if (role !== "user") { continue; } @@ -41,7 +42,7 @@ export function slashFromCustomCommand( ) ) { messages[i] = { - ...messages[i], + ...message, content: content.map((part) => { return part.text?.startsWith(`/${customCommand.name}`) ? { ...part, text: promptUserInput } @@ -53,13 +54,16 @@ export function slashFromCustomCommand( typeof content === "string" && content.startsWith(`/${customCommand.name}`) ) { - messages[i] = { ...messages[i], content: promptUserInput }; + messages[i] = { ...message, content: promptUserInput }; break; } } - for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/comment.ts b/core/commands/slash/comment.ts deleted file mode 100644 index adadb026c..000000000 --- a/core/commands/slash/comment.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { SlashCommand } from "../../"; - -import EditSlashCommand from "./edit"; - -const CommentSlashCommand: SlashCommand = { - name: "comment", - description: "Write comments for highlighted code", - run: async function* (sdk) { - for await (const update of EditSlashCommand.run({ - ...sdk, - input: - "Write comments for this code. Do not change anything about the code itself.", - })) { - yield update; - } - }, -}; - -export default CommentSlashCommand; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index f6521a73d..8fc1ae27b 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -1,5 +1,5 @@ import { SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const CommitMessageCommand: SlashCommand = { name: "commit", @@ -18,7 +18,7 @@ const CommitMessageCommand: SlashCommand = { [{ role: "user", content: prompt }], new AbortController().signal, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 268c68384..a640dbd25 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -1,6 +1,6 @@ import { ChatMessage, SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; import { removeQuotesAndEscapes } from "../../util/index.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const PROMPT = ( input: string, @@ -30,7 +30,8 @@ const DraftIssueCommand: SlashCommand = { return; } let title = await llm.complete( - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, + new AbortController().signal, { maxTokens: 20 }, ); @@ -43,9 +44,12 @@ const DraftIssueCommand: SlashCommand = { { role: "user", content: PROMPT(input, title) }, ]; - for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { + for await (const chunk of llm.streamChat( + messages, + new AbortController().signal, + )) { body += chunk.content; - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent( diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts deleted file mode 100644 index a8f8db944..000000000 --- a/core/commands/slash/edit.ts +++ /dev/null @@ -1,637 +0,0 @@ -import { - ContextItemWithId, - ILLM, - RangeInFileWithContents, - SlashCommand, -} from "../../"; -import { - filterCodeBlockLines, - filterEnglishLinesAtEnd, - filterEnglishLinesAtStart, - fixCodeLlamaFirstLineIndentation, - stopAtLines, - streamWithNewLines, -} from "../../autocomplete/filtering/streamTransforms/lineStream"; -import { streamLines } from "../../diff/util"; -import { stripImages } from "../../llm/images"; -import { - dedentAndGetCommonWhitespace, - getMarkdownLanguageTagForFile, -} from "../../util/"; -import { ctxItemToRifWithContents } from "../util"; - -const PROMPT = `Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The tag should be written to indicate the end of the modified code section. Do not ever use nested tags. - -Example: - - -class Database: - def __init__(self): - self._data = {{}} - - def get(self, key): - return self._data[key] - - - - def set(self, key, value): - self._data[key] = value - - - - def clear_all(): - self._data = {{}} - - -Raise an error if the key already exists. - - - def set(self, key, value): - if key in self._data: - raise KeyError(f"Key {{key}} already exists") - self._data[key] = value - - -Main task: -`; - -export async function getPromptParts( - rif: RangeInFileWithContents, - fullFileContents: string, - model: ILLM, - input: string, - tokenLimit: number | undefined, -) { - const maxTokens = Math.floor(model.contextLength / 2); - - const BUFFER_FOR_FUNCTIONS = 400; - let totalTokens = - model.countTokens(fullFileContents + PROMPT + input) + - BUFFER_FOR_FUNCTIONS + - maxTokens; - - const fullFileContentsList = fullFileContents.split("\n"); - const maxStartLine = rif.range.start.line; - const minEndLine = rif.range.end.line; - let curStartLine = 0; - let curEndLine = fullFileContentsList.length - 1; - - if (totalTokens > model.contextLength) { - while (curEndLine > minEndLine) { - totalTokens -= model.countTokens(fullFileContentsList[curEndLine]); - curEndLine--; - if (totalTokens < model.contextLength) { - break; - } - } - } - - if (totalTokens > model.contextLength) { - while (curStartLine < maxStartLine) { - curStartLine++; - totalTokens -= model.countTokens(fullFileContentsList[curStartLine]); - if (totalTokens < model.contextLength) { - break; - } - } - } - - let filePrefix = fullFileContentsList - .slice(curStartLine, maxStartLine - 1) - .join("\n"); - let fileSuffix = fullFileContentsList - .slice(minEndLine, curEndLine + 1) - .join("\n"); - - if (rif.contents.length > 0) { - let lines = rif.contents.split(/\r?\n/); - let firstLine = lines[0] || null; - while (firstLine && firstLine.trim() === "") { - filePrefix += firstLine; - rif.contents = rif.contents.substring(firstLine.length); - lines = rif.contents.split(/\r?\n/); - firstLine = lines[0] || null; - } - - let lastLine = lines[lines.length - 1] || null; - while (lastLine && lastLine.trim() === "") { - fileSuffix = lastLine + fileSuffix; - rif.contents = rif.contents.substring( - 0, - rif.contents.length - lastLine.length, - ); - lines = rif.contents.split(/\r?\n/); - lastLine = lines[lines.length - 1] || null; - } - - while (rif.contents.startsWith("\n")) { - filePrefix += "\n"; - rif.contents = rif.contents.substring(1); - } - while (rif.contents.endsWith("\n")) { - fileSuffix = `\n${fileSuffix}`; - rif.contents = rif.contents.substring(0, rif.contents.length - 1); - } - } - return { filePrefix, fileSuffix, contents: rif.contents, maxTokens }; -} - -function compilePrompt( - filePrefix: string, - contents: string, - fileSuffix: string, - input: string, -): string { - if (contents.trim() === "") { - // Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file - return `\ - -${filePrefix} - - - -${fileSuffix} - - -${input} - - -Please output the code to be inserted at the cursor in order to fulfill the user_request. Do NOT preface your answer or write anything other than code. You should not write any tags, just the code. Make sure to correctly indent the code:`; - } - - let prompt = PROMPT; - if (filePrefix.trim() !== "") { - prompt += ` - -${filePrefix} -`; - } - prompt += ` - -${contents} -`; - - if (fileSuffix.trim() !== "") { - prompt += ` - -${fileSuffix} -`; - } - prompt += ` - -${input} - - -`; - - return prompt; -} - -function isEndLine(line: string) { - return ( - line.includes("") || - line.includes("") || - line.includes("[/CODE]") - ); -} - -function lineToBeIgnored(line: string, isFirstLine = false): boolean { - return ( - line.includes("```") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") || - line.includes("") - ); -} - -const EditSlashCommand: SlashCommand = { - name: "edit", - description: "Edit selected code", - run: async function* ({ ide, llm, input, history, contextItems, params }) { - let contextItemToEdit = contextItems.find( - (item: ContextItemWithId) => - item.editing && item.id.providerTitle === "code", - ); - if (!contextItemToEdit) { - contextItemToEdit = contextItems.find( - (item: ContextItemWithId) => item.id.providerTitle === "code", - ); - } - - if (!contextItemToEdit) { - yield "Please highlight the code you want to edit, then press `cmd/ctrl+shift+L` to add it to chat"; - return; - } - - // Strip unecessary parts of the input (the fact that you have to do this is suboptimal, should be refactored away) - let content = history[history.length - 1].content; - if (typeof content !== "string") { - content.forEach((part) => { - if (part.text?.startsWith("/edit")) { - part.text = part.text.replace("/edit", "").trimStart(); - } - }); - } else if (input?.startsWith("/edit")) { - content = input.replace("/edit", "").trimStart(); - } else if (input?.startsWith("/comment")) { - content = input.replace("/comment", "").trimStart(); - } - let userInput = stripImages(content).replace( - `\`\`\`${contextItemToEdit.name}\n${contextItemToEdit.content}\n\`\`\`\n`, - "", - ); - // if the above replace fails to find a match, the code will still be present - // in the userInput. Replace it with input if available. - if (userInput.includes("```") && (input !== "" || !input)) { - userInput = input; - } - - const rif: RangeInFileWithContents = - ctxItemToRifWithContents(contextItemToEdit); - - await ide.saveFile(rif.filepath); - const fullFileContents = await ide.readFile(rif.filepath); - - let { filePrefix, contents, fileSuffix, maxTokens } = await getPromptParts( - rif, - fullFileContents, - llm, - userInput, - params?.tokenLimit, - ); - const [dedentedContents, commonWhitespace] = - dedentAndGetCommonWhitespace(contents); - contents = dedentedContents; - - const prompt = compilePrompt(filePrefix, contents, fileSuffix, userInput); - const fullFileContentsLines = fullFileContents.split("\n"); - const fullPrefixLines = fullFileContentsLines.slice( - 0, - Math.max(0, rif.range.start.line - 1), - ); - const fullSuffixLines = fullFileContentsLines.slice(rif.range.end.line); - - let linesToDisplay: string[] = []; - - async function sendDiffUpdate(lines: string[], final = false) { - const completion = lines.join("\n"); - - // Don't do this at the very end, just show the inserted code - if (final) { - linesToDisplay = []; - } - - // Only recalculate at every new-line, because this is sort of expensive - else if (completion.endsWith("\n")) { - const contentsLines = rif.contents.split("\n"); - let rewrittenLines = 0; - for (const line of lines) { - for (let i = rewrittenLines; i < contentsLines.length; i++) { - if ( - // difflib.SequenceMatcher( - // null, line, contentsLines[i] - // ).ratio() - // > 0.7 - line.trim() === contentsLines[i].trim() && // Temp replacement for difflib (TODO) - contentsLines[i].trim() !== "" - ) { - rewrittenLines = i + 1; - break; - } - } - } - linesToDisplay = contentsLines.slice(rewrittenLines); - } - - const newFileContents = `${fullPrefixLines.join("\n")}\n${completion}\n${ - linesToDisplay.length > 0 ? `${linesToDisplay.join("\n")}\n` : "" - }${fullSuffixLines.join("\n")}`; - - const stepIndex = history.length - 1; - - await ide.showDiff(rif.filepath, newFileContents, stepIndex); - } - - // Important state variables - // ------------------------- - const originalLines = rif.contents === "" ? [] : rif.contents.split("\n"); - // In the actual file, taking into account block offset - let currentLineInFile = rif.range.start.line; - let currentBlockLines: string[] = []; - let originalLinesBelowPreviousBlocks = originalLines; - // The start of the current block in file, taking into account block offset - let currentBlockStart = -1; - let offsetFromBlocks = 0; - - // Don't end the block until you've matched N simultaneous lines - // This helps avoid many tiny blocks - const LINES_TO_MATCH_BEFORE_ENDING_BLOCK = 2; - // If a line has been matched at the end of the block, this is its index within originalLinesBelowPreviousBlocks - // Except we are keeping track of multiple potentialities, so it's a list - // We always check the lines following each of these leads, but if multiple make it out at the end, we use the first one - // This is a tuple of (index_of_last_matched_line, number_of_lines_matched) - let indicesOfLastMatchedLines: [number, number][] = []; - - async function handleGeneratedLine(line: string) { - if (currentBlockLines.length === 0) { - // Set this as the start of the next block - currentBlockStart = - rif.range.start.line + - originalLines.length - - originalLinesBelowPreviousBlocks.length + - offsetFromBlocks; - if ( - originalLinesBelowPreviousBlocks.length > 0 && - line === originalLinesBelowPreviousBlocks[0] - ) { - // Line is equal to the next line in file, move past this line - originalLinesBelowPreviousBlocks = - originalLinesBelowPreviousBlocks.slice(1); - return; - } - } - - // In a block, and have already matched at least one line - // Check if the next line matches, for each of the candidates - const matchesFound: any[] = []; - let firstValidMatch: any = null; - for (const [ - index_of_last_matched_line, - num_lines_matched, - ] of indicesOfLastMatchedLines) { - if ( - index_of_last_matched_line + 1 < - originalLinesBelowPreviousBlocks.length && - line === - originalLinesBelowPreviousBlocks[index_of_last_matched_line + 1] - ) { - matchesFound.push([ - index_of_last_matched_line + 1, - num_lines_matched + 1, - ]); - if ( - firstValidMatch === null && - num_lines_matched + 1 >= LINES_TO_MATCH_BEFORE_ENDING_BLOCK - ) { - firstValidMatch = [ - index_of_last_matched_line + 1, - num_lines_matched + 1, - ]; - } - } - } - indicesOfLastMatchedLines = matchesFound; - - if (firstValidMatch !== null) { - // We've matched the required number of lines, insert suggestion! - - // We added some lines to the block that were matched (including maybe some blank lines) - // So here we will strip all matching lines from the end of currentBlockLines - const linesStripped: string[] = []; - let indexOfLastLineInBlock: number = firstValidMatch[0]; - while ( - currentBlockLines.length > 0 && - currentBlockLines[currentBlockLines.length - 1] === - originalLinesBelowPreviousBlocks[indexOfLastLineInBlock - 1] - ) { - linesStripped.push(currentBlockLines.pop() as string); - indexOfLastLineInBlock -= 1; - } - - // Reset current block / update variables - currentLineInFile += 1; - offsetFromBlocks += currentBlockLines.length; - originalLinesBelowPreviousBlocks = - originalLinesBelowPreviousBlocks.slice(indexOfLastLineInBlock + 1); - currentBlockLines = []; - currentBlockStart = -1; - indicesOfLastMatchedLines = []; - - return; - } - - // Always look for new matching candidates - const newMatches: any[] = []; - for (let i = 0; i < originalLinesBelowPreviousBlocks.length; i++) { - const ogLine = originalLinesBelowPreviousBlocks[i]; - // TODO: It's a bit sus to be disqualifying empty lines. - // What you ideally do is find ALL matches, and then throw them out as you check the following lines - if (ogLine === line) { - // and og_line.trim() !== "": - newMatches.push([i, 1]); - } - } - indicesOfLastMatchedLines = indicesOfLastMatchedLines.concat(newMatches); - - // Make sure they are sorted by index - indicesOfLastMatchedLines = indicesOfLastMatchedLines.sort( - (a, b) => a[0] - b[0], - ); - - currentBlockLines.push(line); - } - - let messages = history; - messages[messages.length - 1] = { role: "user", content: prompt }; - - let linesOfPrefixCopied = 0; - const lines = []; - let unfinishedLine = ""; - let completionLinesCovered = 0; - let repeatingFileSuffix = false; - const lineBelowHighlightedRange = fileSuffix.trim().split("\n")[0]; - - // Use custom templates defined by the model - const template = llm.promptTemplates?.edit; - let generator: AsyncGenerator; - if (template) { - const rendered = llm.renderPromptTemplate( - template, - // typeof template === 'string' ? template : template.prompt, - messages.slice(0, messages.length - 1), - { - codeToEdit: rif.contents, - userInput, - filePrefix: filePrefix, - fileSuffix: fileSuffix, - - // Some built-in templates use these instead of the above - prefix: filePrefix, - suffix: fileSuffix, - - language: getMarkdownLanguageTagForFile(rif.filepath), - systemMessage: llm.systemMessage ?? "", - // "contextItems": (await sdk.getContextItemChatMessages()).map(x => x.content || "").join("\n\n"), - }, - ); - if (typeof rendered === "string") { - messages = [ - { - role: "user", - content: rendered, - }, - ]; - } else { - messages = rendered; - } - - const completion = llm.streamComplete( - rendered as string, - new AbortController().signal, - { - maxTokens: Math.min( - maxTokens, - Math.floor(llm.contextLength / 2), - 4096, - ), - raw: true, - }, - ); - let lineStream = streamLines(completion); - - lineStream = filterEnglishLinesAtStart(lineStream); - - lineStream = filterEnglishLinesAtEnd(filterCodeBlockLines(lineStream)); - lineStream = stopAtLines(lineStream, () => {}); - - generator = streamWithNewLines( - fixCodeLlamaFirstLineIndentation(lineStream), - ); - } else { - async function* gen() { - for await (const chunk of llm.streamChat( - messages, - new AbortController().signal, - { - temperature: 0.5, // TODO - maxTokens: Math.min( - maxTokens, - Math.floor(llm.contextLength / 2), - 4096, - ), - }, - )) { - yield stripImages(chunk.content); - } - } - - generator = gen(); - } - - for await (const chunk of generator) { - // Stop early if it is repeating the fileSuffix or the step was deleted - if (repeatingFileSuffix) { - break; - } - - // Allow stopping breakpoints - yield undefined; - - // Accumulate lines - const chunkLines = chunk.split("\n"); - chunkLines[0] = unfinishedLine + chunkLines[0]; - if (chunk.endsWith("\n")) { - unfinishedLine = ""; - chunkLines.pop(); // because this will be an empty string - } else { - unfinishedLine = chunkLines.pop() ?? ""; - } - - // Deal with newly accumulated lines - for (let i = 0; i < chunkLines.length; i++) { - // Trailing whitespace doesn't matter - chunkLines[i] = chunkLines[i].trimEnd(); - chunkLines[i] = commonWhitespace + chunkLines[i]; - - // Lines that should signify the end of generation - if (isEndLine(chunkLines[i])) { - break; - } - // Lines that should be ignored, like the <> tags - if (lineToBeIgnored(chunkLines[i], completionLinesCovered === 0)) { - continue; // noice - } - // Check if we are currently just copying the prefix - if ( - (linesOfPrefixCopied > 0 || completionLinesCovered === 0) && - linesOfPrefixCopied < filePrefix.split("\n").length && - chunkLines[i] === fullPrefixLines[linesOfPrefixCopied] - ) { - // This is a sketchy way of stopping it from repeating the filePrefix. Is a bug if output happens to have a matching line - linesOfPrefixCopied += 1; - continue; // also nice - } - // Because really short lines might be expected to be repeated, this is only a !heuristic! - // Stop when it starts copying the fileSuffix - if ( - chunkLines[i].trim() === lineBelowHighlightedRange.trim() && - chunkLines[i].trim().length > 4 && - !( - originalLinesBelowPreviousBlocks.length > 0 && - chunkLines[i].trim() === originalLinesBelowPreviousBlocks[0].trim() - ) - ) { - repeatingFileSuffix = true; - break; - } - - lines.push(chunkLines[i]); - completionLinesCovered += 1; - currentLineInFile += 1; - } - - await sendDiffUpdate( - lines.concat([ - unfinishedLine?.startsWith("<") - ? commonWhitespace - : commonWhitespace + unfinishedLine, - ]), - ); - } - - // Add the unfinished line - if ( - unfinishedLine !== "" && - !lineToBeIgnored(unfinishedLine, completionLinesCovered === 0) && - !isEndLine(unfinishedLine) - ) { - unfinishedLine = commonWhitespace + unfinishedLine; - lines.push(unfinishedLine); - await handleGeneratedLine(unfinishedLine); - completionLinesCovered += 1; - currentLineInFile += 1; - } - - await sendDiffUpdate(lines, true); - - if (params?.recap) { - const prompt = `This is the code before editing: -\`\`\` -${contents} -\`\`\` - -This is the code after editing: - -\`\`\` -${lines.join("\n")} -\`\`\` - -Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`; - - for await (const update of llm.streamComplete( - prompt, - new AbortController().signal, - )) { - yield update; - } - } - yield `Edited ${contextItemToEdit.name}`; - }, -}; - -export default EditSlashCommand; diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts new file mode 100644 index 000000000..a9fa332bb --- /dev/null +++ b/core/commands/slash/mcp.ts @@ -0,0 +1,46 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; + +import { ChatMessage, SlashCommand } from "../../index.js"; +import { renderChatMessage } from "../../util/messageContent.js"; +export function constructMcpSlashCommand( + client: Client, + name: string, + description?: string, + args?: string[], +): SlashCommand { + return { + name, + description: description ?? "MCP Prompt", + params: {}, + run: async function* (context) { + const argsObject: { [key: string]: string } = {}; + const userInput = context.input.split(" ").slice(1).join(" "); + if (args) { + args.forEach((arg, i) => { + argsObject[arg] = userInput; + }); + } + + const result = await client.getPrompt({ name, arguments: argsObject }); + + const messages: ChatMessage[] = result.messages.map((msg) => { + if (msg.content.type !== "text") { + throw new Error( + "Continue currently only supports text prompts through MCP", + ); + } + return { + content: msg.content.text, + role: msg.role, + }; + }); + + for await (const chunk of context.llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); + } + }, + }; +} diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index 4d8aa3a38..b9a39aa0b 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -9,7 +9,7 @@ import { defaultIgnoreFile, gitIgArrayFromFile, } from "../../indexing/ignore"; -import { stripImages } from "../../llm/images"; +import { renderChatMessage } from "../../util/messageContent"; const LANGUAGE_DEP_MGMT_FILENAMES = [ "package.json", // JavaScript (Node.js) @@ -45,10 +45,11 @@ const OnboardSlashCommand: SlashCommand = { const context = await gatherProjectContext(workspaceDir, ide); const prompt = createOnboardingPrompt(context); - for await (const chunk of llm.streamChat([ - { role: "user", content: prompt }, - ], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content: prompt }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index 77357647a..a3a2be6a7 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -1,5 +1,5 @@ import { ChatMessage, SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; const prompt = ` Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines: @@ -43,10 +43,11 @@ const ReviewMessageCommand: SlashCommand = { const content = `${prompt} \r\n ${reviewText}`; - for await (const chunk of llm.streamChat([ - { role: "user", content: content }, - ], new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of llm.streamChat( + [{ role: "user", content: content }], + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index 5ee1fd938..4b69f4c62 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -4,7 +4,7 @@ import path from "path"; import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../index.js"; -import { stripImages } from "../../llm/images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; // If useful elsewhere, helper funcs should move to core/util/index.ts or similar function getOffsetDatetime(date: Date): Date { @@ -48,7 +48,7 @@ const ShareSlashCommand: SlashCommand = { // message in the chat history, this will omit it for (const msg of history.slice(0, history.length - 1)) { let msgText = msg.content; - msgText = stripImages(msg.content); + msgText = renderChatMessage(msg); if (msg.role === "user" && msgText.search("```") > -1) { msgText = reformatCodeBlocks(msgText); diff --git a/core/config/load.ts b/core/config/load.ts index 9911c840f..1e16913e5 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -1,10 +1,11 @@ import { execSync } from "child_process"; -import * as JSONC from "comment-json"; import * as fs from "fs"; import os from "os"; import path from "path"; +import * as JSONC from "comment-json"; import * as tar from "tar"; + import { BrowserSerializedContinueConfig, Config, @@ -28,6 +29,7 @@ import { slashCommandFromDescription, slashFromCustomCommand, } from "../commands/index.js"; +import MCPConnectionSingleton from "../context/mcp"; import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; @@ -42,6 +44,7 @@ import { BaseLLM } from "../llm"; import { llmFromDescription } from "../llm/llms"; import CustomLLMClass from "../llm/llms/CustomLLM"; import FreeTrial from "../llm/llms/FreeTrial"; +import { allTools } from "../tools"; import { copyOf } from "../util"; import { fetchwithRequestOptions } from "../util/fetchWithOptions"; import { GlobalContext } from "../util/GlobalContext"; @@ -57,7 +60,6 @@ import { getEsbuildBinaryPath, readAllGlobalPromptFiles, } from "../util/paths"; - import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -484,14 +486,36 @@ async function intermediateToFinalConfig( } } - return { + let continueConfig: ContinueConfig = { ...config, contextProviders, models, embeddingsProvider: config.embeddingsProvider as any, tabAutocompleteModels, reranker: config.reranker as any, + tools: allTools, }; + + // Apply MCP if specified + if (config.experimental?.modelContextProtocolServer) { + const mcpConnection = await MCPConnectionSingleton.getInstance( + config.experimental.modelContextProtocolServer, + ); + continueConfig = await Promise.race([ + mcpConnection.modifyConfig(continueConfig), + new Promise((_, reject) => + setTimeout( + () => reject(new Error("MCP connection timed out after 2000ms")), + 2000, + ), + ), + ]).catch((error) => { + console.warn("MCP connection error:", error); + return continueConfig; // Return original config if timeout occurs + }); + } + + return continueConfig; } function finalToBrowserConfig( @@ -528,6 +552,7 @@ function finalToBrowserConfig( ui: final.ui, experimental: final.experimental, docs: final.docs, + tools: final.tools, }; } diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index a630e41d6..5020fc112 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,9 +4,9 @@ import Handlebars from "handlebars"; import * as YAML from "yaml"; import { walkDir } from "../indexing/walkDir"; -import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; import { getBasename } from "../util/index"; +import { renderChatMessage } from "../util/messageContent"; import type { ChatMessage, @@ -129,7 +129,7 @@ export function slashCommandFromPromptFile( messages, new AbortController().signal, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } context.llm.systemMessage = originalSystemMessage; @@ -236,7 +236,8 @@ function updateChatHistory( const messages = [...history]; for (let i = messages.length - 1; i >= 0; i--) { - const { role, content } = messages[i]; + const message = messages[i]; + const { role, content } = message; if (role !== "user") { continue; } @@ -254,7 +255,7 @@ function updateChatHistory( typeof content === "string" && content.startsWith(`/${commandName}`) ) { - messages[i] = { ...messages[i], content: renderedPrompt }; + messages[i] = { ...message, content: renderedPrompt }; break; } } diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts new file mode 100644 index 000000000..984ba8f7b --- /dev/null +++ b/core/context/mcp/index.ts @@ -0,0 +1,157 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; + +import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../.."; +import { constructMcpSlashCommand } from "../../commands/slash/mcp"; +import MCPContextProvider from "../providers/MCPContextProvider"; + +class MCPConnectionSingleton { + private static instance: MCPConnectionSingleton; + public client: Client; + private transport: Transport; + + private constructor(private readonly options: MCPOptions) { + this.transport = this.constructTransport(options); + + this.client = new Client( + { + name: "continue-client", + version: "1.0.0", + }, + { + capabilities: {}, + }, + ); + } + + public static getInstance(options: MCPOptions): MCPConnectionSingleton { + if (!MCPConnectionSingleton.instance) { + MCPConnectionSingleton.instance = new MCPConnectionSingleton(options); + } + return MCPConnectionSingleton.instance; + } + + public static getExistingInstance(): MCPConnectionSingleton | null { + return MCPConnectionSingleton.instance; + } + + private constructTransport(options: MCPOptions): Transport { + switch (options.transport.type) { + case "stdio": + return new StdioClientTransport({ + command: options.transport.command, + args: options.transport.args, + }); + case "websocket": + return new WebSocketClientTransport(new URL(options.transport.url)); + case "sse": + return new SSEClientTransport(new URL(options.transport.url)); + default: + throw new Error( + `Unsupported transport type: ${(options.transport as any).type}`, + ); + } + } + + private isConnected: boolean = false; + private connectPromise: Promise | null = null; + + private async connectClient() { + if (this.isConnected) { + // Already connected + return; + } + + if (this.connectPromise) { + // Connection is already in progress; wait for it to complete + await this.connectPromise; + return; + } + + this.connectPromise = (async () => { + await this.client.connect(this.transport); + this.isConnected = true; + })(); + + try { + await this.connectPromise; + } catch (error) { + // Handle connection error if needed + throw error; + } finally { + // Reset the promise so future attempts can try again if necessary + this.connectPromise = null; + } + } + + async modifyConfig(config: ContinueConfig): Promise { + try { + await this.connectClient(); + } catch (error: any) { + if (!error.message.startsWith("StdioClientTransport already started")) { + console.error("Failed to connect client:", error); + return config; + } + } + + // Resources <—> Context Provider + const { resources } = await this.client.listResources(); + + const submenuItems = resources.map((resource: any) => ({ + title: resource.name, + description: resource.description, + id: resource.uri, + })); + + if (!config.contextProviders) { + config.contextProviders = []; + } + + config.contextProviders!.push( + new MCPContextProvider({ + submenuItems, + client: this.client, + }), + ); + + // Tools <—> Tools + const { tools } = await this.client.listTools(); + const continueTools: Tool[] = tools.map((tool) => ({ + displayTitle: tool.name, + function: { + description: tool.description, + name: tool.name, + parameters: tool.inputSchema, + }, + readonly: false, + type: "function", + wouldLikeTo: `use the ${tool.name} tool`, + uri: `mcp://${tool.name}`, + })); + + config.tools = [...config.tools, ...continueTools]; + + // Prompts <—> Slash commands + const { prompts } = await this.client.listPrompts(); + if (!config.slashCommands) { + config.slashCommands = []; + } + + const slashCommands: SlashCommand[] = prompts.map((prompt) => { + return constructMcpSlashCommand( + this.client, + prompt.name, + prompt.description, + prompt.arguments?.map((a) => a.name), + ); + }); + config.slashCommands!.push(...slashCommands); + + return config; + } +} + +export default MCPConnectionSingleton; diff --git a/core/context/providers/MCPContextProvider.ts b/core/context/providers/MCPContextProvider.ts new file mode 100644 index 000000000..0c0a6939d --- /dev/null +++ b/core/context/providers/MCPContextProvider.ts @@ -0,0 +1,66 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; + +import { BaseContextProvider } from "../"; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../../"; + +interface MCPContextProviderOptions { + submenuItems: ContextSubmenuItem[]; + client: Client; +} + +class MCPContextProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "mcp", + displayTitle: "MCP", + description: "Model Context Protocol", + type: "submenu", + }; + + constructor(options: MCPContextProviderOptions) { + super(options); + } + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + const { contents } = await ( + this.options as MCPContextProviderOptions + ).client.readResource({ uri: query }); + + return await Promise.all( + contents.map(async (resource) => { + const content = resource.text; + if (typeof content !== "string") { + throw new Error( + "Continue currently only supports text resources from MCP", + ); + } + + return { + name: resource.uri, + description: resource.uri, + content, + uri: { + type: "url", + value: resource.uri, + }, + }; + }), + ); + } + + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + return (this.options as MCPContextProviderOptions).submenuItems; + } +} + +export default MCPContextProvider; diff --git a/core/context/providers/WebContextProvider.ts b/core/context/providers/WebContextProvider.ts index 2c8cb8928..9ea4bac41 100644 --- a/core/context/providers/WebContextProvider.ts +++ b/core/context/providers/WebContextProvider.ts @@ -3,12 +3,37 @@ import { ContextItem, ContextProviderDescription, ContextProviderExtras, + FetchFunction, } from "../.."; import { getHeaders } from "../../continueServer/stubs/headers"; import { TRIAL_PROXY_URL } from "../../control-plane/client"; +export const fetchSearchResults = async ( + query: string, + n: number, + fetchFn: FetchFunction, +): Promise => { + const resp = await fetchFn(WebContextProvider.ENDPOINT, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(await getHeaders()), + }, + body: JSON.stringify({ + query, + n, + }), + }); + + if (!resp.ok) { + const text = await resp.text(); + throw new Error(`Failed to fetch web context: ${text}`); + } + return await resp.json(); +}; + export default class WebContextProvider extends BaseContextProvider { - private static ENDPOINT = new URL("web", TRIAL_PROXY_URL); + public static ENDPOINT = new URL("web", TRIAL_PROXY_URL); private static DEFAULT_N = 6; static description: ContextProviderDescription = { @@ -23,22 +48,10 @@ export default class WebContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const resp = await extras.fetch(WebContextProvider.ENDPOINT, { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(await getHeaders()), - }, - body: JSON.stringify({ - query: extras.fullInput, - n: this.options.n ?? WebContextProvider.DEFAULT_N, - }), - }); - if (!resp.ok) { - const text = await resp.text(); - throw new Error(`Failed to fetch web context: ${text}`); - } - const json = await resp.json(); - return json; + return await fetchSearchResults( + extras.fullInput, + this.options.n ?? WebContextProvider.DEFAULT_N, + extras.fetch, + ); } } diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 316e4936b..f5656832c 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -17,6 +17,7 @@ import GoogleContextProvider from "./GoogleContextProvider"; import GreptileContextProvider from "./GreptileContextProvider"; import HttpContextProvider from "./HttpContextProvider"; import JiraIssuesContextProvider from "./JiraIssuesContextProvider/"; +import MCPContextProvider from "./MCPContextProvider"; import OpenFilesContextProvider from "./OpenFilesContextProvider"; import OSContextProvider from "./OSContextProvider"; import PostgresContextProvider from "./PostgresContextProvider"; @@ -60,6 +61,7 @@ export const Providers: (typeof BaseContextProvider)[] = [ DiscordContextProvider, GreptileContextProvider, WebContextProvider, + MCPContextProvider, ]; export function contextProviderClassFromName( diff --git a/core/context/providers/utils.ts b/core/context/providers/utils.ts index 7bc20e491..fd73a9bec 100644 --- a/core/context/providers/utils.ts +++ b/core/context/providers/utils.ts @@ -4,4 +4,5 @@ export const INSTRUCTIONS_BASE_ITEM: ContextItem = { name: "Instructions", description: "Instructions", content: "", + hidden: true, }; diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 8dc55df9d..57f2b339e 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,7 +1,7 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; -import { stripImages } from "../../llm/images"; import generateRepoMap from "../../util/generateRepoMap"; +import { renderChatMessage } from "../../util/messageContent"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -58,11 +58,14 @@ After this, your response should begin with a tag, followed by a list This is the question that you should select relevant files for: "${input}"`; - const response = await llm.chat([ - { role: "user", content: prompt }, - { role: "assistant", content: "" }, - ], new AbortController().signal); - const content = stripImages(response.content); + const response = await llm.chat( + [ + { role: "user", content: prompt }, + { role: "assistant", content: "" }, + ], + new AbortController().signal, + ); + const content = renderChatMessage(response); console.debug("Repo map retrieval response: ", content); if (!content.includes("\n")) { diff --git a/core/core.ts b/core/core.ts index a1d74f281..a426a337d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -36,6 +36,7 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; +import { callTool } from "./tools/callTool"; import type { IMessenger, Message } from "./util/messenger"; export class Core { @@ -154,10 +155,10 @@ export class Core { // Index on initialization void this.ide.getWorkspaceDirs().then(async (dirs) => { // Respect pauseCodebaseIndexOnStart user settings - this.indexingPauseToken.paused = true; if (ideSettings.pauseCodebaseIndexOnStart) { + this.indexingPauseToken.paused = true; void this.messenger.request("indexProgress", { - progress: 1, + progress: 0, desc: "Initial Indexing Skipped", status: "paused", }); @@ -382,6 +383,7 @@ export class Core { } const model = await configHandler.llmFromTitle(msg.data.title); + const gen = model.streamChat( msg.data.messages, new AbortController().signal, @@ -402,8 +404,11 @@ export class Core { }); break; } + + const chunk = next.value; + // @ts-ignore - yield { content: next.value.content }; + yield { content: chunk }; next = await gen.next(); } @@ -770,10 +775,44 @@ export class Core { const ignoreInstance = ignore().add(defaultIgnoreFile); let rootDirectory = await this.ide.getWorkspaceDirs(); const relativeFilePath = path.relative(rootDirectory[0], filepath); - if (!ignoreInstance.ignores(relativeFilePath)) { - recentlyEditedFilesCache.set(filepath, filepath); + try { + if (!ignoreInstance.ignores(relativeFilePath)) { + recentlyEditedFilesCache.set(filepath, filepath); + } + } catch (e) { + if (e instanceof RangeError) { + // do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json` + } else { + console.debug("unhandled ignores error", relativeFilePath, e); + } } }); + + on("tools/call", async ({ data: { toolCall } }) => { + const config = await this.configHandler.loadConfig(); + const tool = config.tools.find( + (t) => t.function.name === toolCall.function.name, + ); + + if (!tool) { + throw new Error(`Tool ${toolCall.function.name} not found`); + } + + const llm = await this.getSelectedModel(); + + const contextItems = await callTool( + tool.uri ?? tool.function.name, + JSON.parse(toolCall.function.arguments || "{}"), + { + ide: this.ide, + llm, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + }, + ); + + return { contextItems }; + }); } private indexingCancellationController: AbortController | undefined; @@ -803,6 +842,8 @@ export class Core { this.indexingCancellationController.signal, )) { let updateToSend = { ...update }; + // TODO reconsider this status overwrite? + // original goal was to not concern users with edge noncritical errors if (update.status === "failed") { updateToSend.status = "done"; updateToSend.desc = "Indexing complete"; diff --git a/core/diff/util.ts b/core/diff/util.ts index 839ab15b1..c56e88504 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -1,7 +1,7 @@ import { distance } from "fastest-levenshtein"; import { ChatMessage } from "../index.js"; -import { stripImages } from "../llm/images.js"; +import { renderChatMessage } from "../util/messageContent.js"; export type LineStream = AsyncGenerator; @@ -103,7 +103,7 @@ export async function* streamLines( try { for await (const update of streamCompletion) { const chunk = - typeof update === "string" ? update : stripImages(update.content); + typeof update === "string" ? update : renderChatMessage(update); buffer += chunk; const lines = buffer.split("\n"); buffer = lines.pop() ?? ""; diff --git a/core/index.d.ts b/core/index.d.ts index efb7a18e9..81ddd2039 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -42,11 +42,18 @@ export interface IndexingProgressUpdate { progress: number; desc: string; shouldClearIndexes?: boolean; - status: "loading" | "indexing" | "done" | "failed" | "paused" | "disabled"; + status: + | "loading" + | "indexing" + | "done" + | "failed" + | "paused" + | "disabled" + | "cancelled"; debugInfo?: string; } -// This is more or less a V2 of IndexingProgressUpdate +// This is more or less a V2 of IndexingProgressUpdate for docs etc. export interface IndexingStatus { id: string; type: "docs"; @@ -240,7 +247,6 @@ export interface Session { title: string; workspaceDirectory: string; history: ChatHistoryItem[]; - checkpoints?: Checkpoint[]; } export interface SessionMetadata { @@ -288,7 +294,7 @@ export interface CompletionOptions extends BaseCompletionOptions { model: string; } -export type ChatMessageRole = "user" | "assistant" | "system"; +export type ChatMessageRole = "user" | "assistant" | "system" | "tool"; export interface MessagePart { type: "text" | "imageUrl"; @@ -298,11 +304,52 @@ export interface MessagePart { export type MessageContent = string | MessagePart[]; -export interface ChatMessage { - role: ChatMessageRole; +export interface ToolCall { + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; +} + +export interface ToolCallDelta { + id?: string; + type?: "function"; + function?: { + name?: string; + arguments?: string; + }; +} + +export interface ToolResultChatMessage { + role: "tool"; + content: string; + toolCallId: string; +} + +export interface UserChatMessage { + role: "user"; content: MessageContent; } +export interface AssistantChatMessage { + role: "assistant"; + content: MessageContent; + toolCalls?: ToolCallDelta[]; +} + +export interface SystemChatMessage { + role: "system"; + content: string; +} + +export type ChatMessage = + | UserChatMessage + | AssistantChatMessage + | SystemChatMessage + | ToolResultChatMessage; + export interface ContextItemId { providerTitle: string; itemId: string; @@ -323,6 +370,7 @@ export interface ContextItem { editable?: boolean; icon?: string; uri?: ContextItemUri; + hidden?: boolean; } export interface ContextItemWithId extends ContextItem { @@ -347,19 +395,39 @@ export interface PromptLog { prompt: string; completion: string; } -export interface ChatHistoryItem { - message: ChatMessage; - editorState?: any; - modifiers?: InputModifiers; - contextItems: ContextItemWithId[]; - promptLogs?: PromptLog[]; + +type MessageModes = "chat" | "edit"; + +export type ToolStatus = + | "generating" + | "generated" + | "calling" + | "done" + | "canceled"; + +// Will exist only on "assistant" messages with tool calls +interface ToolCallState { + toolCallId: string; + toolCall: ToolCall; + status: ToolStatus; + parsedArgs: any; + output?: ContextItem[]; } -// LLM +export interface ChatHistoryItem { + message: ChatMessage; + contextItems: ContextItemWithId[]; + editorState?: any; + modifiers?: InputModifiers; + promptLogs?: PromptLog[]; + toolCallState?: ToolCallState; + isGatheringContext?: boolean; + checkpoint?: Checkpoint; + isBeforeCheckpoint?: boolean; +} export interface LLMFullCompletionOptions extends BaseCompletionOptions { log?: boolean; - model?: string; } @@ -700,7 +768,8 @@ type ModelProvider = | "nebius" | "xAI" | "moonshot" - | "siliconflow"; + | "siliconflow" + | "function-network"; export type ModelName = | "AUTODETECT" @@ -855,6 +924,27 @@ interface Prediction { }[]; } +export interface ToolExtras { + ide: IDE; + llm: ILLM; + fetch: FetchFunction; +} + +export interface Tool { + type: "function"; + function: { + name: string; + description?: string; + parameters?: Record; + strict?: boolean | null; + }; + + displayTitle: string; + wouldLikeTo: string; + readonly: boolean; + uri?: string; +} + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -871,6 +961,7 @@ interface BaseCompletionOptions { raw?: boolean; stream?: boolean; prediction?: Prediction; + tools?: Tool[]; } export interface ModelCapability { @@ -913,6 +1004,7 @@ export type EmbeddingsProviderName = | "nebius" | "vertexai" | "watsonx" + | "function-network" | "siliconflow"; export interface EmbedOptions { @@ -984,6 +1076,28 @@ export interface TabAutocompleteOptions { showWhateverWeHaveAtXMs?: number; } +interface StdioOptions { + type: "stdio"; + command: string; + args: string[]; +} + +interface WebSocketOptions { + type: "websocket"; + url: string; +} + +interface SSEOptions { + type: "sse"; + url: string; +} + +type TransportOptions = StdioOptions | WebSocketOptions | SSEOptions; + +export interface MCPOptions { + transport: TransportOptions; +} + export interface ContinueUIConfig { codeBlockToolbarPosition?: "top" | "bottom"; fontSize?: number; @@ -1089,6 +1203,8 @@ interface ExperimentalConfig { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; + useTools?: boolean; + modelContextProtocolServer?: MCPOptions; } interface AnalyticsConfig { @@ -1193,6 +1309,7 @@ export interface ContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; + tools: Tool[]; } export interface BrowserSerializedContinueConfig { @@ -1212,6 +1329,7 @@ export interface BrowserSerializedContinueConfig { experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; + tools: Tool[]; } // DOCS SUGGESTIONS AND PACKAGE INFO diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 5c70f8bad..af204a723 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -145,9 +145,7 @@ export class CodebaseIndexer { } } - async *refreshFiles( - files: string[], - ): AsyncGenerator { + async *refreshFiles(files: string[]): AsyncGenerator { let progress = 0; if (files.length === 0) { yield { @@ -192,9 +190,9 @@ export class CodebaseIndexer { if (dirs.length === 0) { yield { - progress, + progress: 1, desc: "Nothing to index", - status: "disabled", + status: "done", }; return; } @@ -238,9 +236,9 @@ export class CodebaseIndexer { directoryFiles.push(p); if (abortSignal.aborted) { yield { - progress: 1, + progress: 0, desc: "Indexing cancelled", - status: "disabled", + status: "cancelled", }; return; } @@ -263,9 +261,9 @@ export class CodebaseIndexer { // Handle pausing in this loop because it's the only one really taking time if (abortSignal.aborted) { yield { - progress: 1, + progress: 0, desc: "Indexing cancelled", - status: "disabled", + status: "cancelled", }; return; } diff --git a/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts b/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts new file mode 100644 index 000000000..fe16dbc51 --- /dev/null +++ b/core/indexing/embeddings/FunctionNetworkEmbeddingsProvider.ts @@ -0,0 +1,69 @@ +import { Response } from "node-fetch"; + +import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; +import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + +import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; + +class FunctionNetworkEmbeddingsProvider extends BaseEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "function-network"; + static maxBatchSize = 128; + + static defaultOptions: Partial | undefined = { + apiBase: "https://api.function.network/v1/", + model: "baai/bge-base-en-v1.5", + }; + + private _getEndpoint() { + if (!this.options.apiBase) { + throw new Error( + "No API base URL provided. Please set the 'apiBase' option in config.json", + ); + } + + this.options.apiBase = this.options.apiBase.endsWith("/") + ? this.options.apiBase + : `${this.options.apiBase}/`; + return new URL("embeddings", this.options.apiBase); + } + + async embed(chunks: string[]) { + const batchedChunks = this.getBatchedChunks(chunks); + return ( + await Promise.all( + batchedChunks.map(async (batch) => { + if (batch.length === 0) { + return []; + } + + const fetchWithBackoff = () => + withExponentialBackoff(() => + this.fetch(this._getEndpoint(), { + method: "POST", + body: JSON.stringify({ + input: batch, + model: this.options.model, + }), + headers: { + Authorization: `Bearer ${this.options.apiKey}`, + "Content-Type": "application/json", + }, + }), + ); + const resp = await fetchWithBackoff(); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + return data.data.map( + (result: { embedding: number[] }) => result.embedding, + ); + }), + ) + ).flat(); + } +} + +export default FunctionNetworkEmbeddingsProvider; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index 3e895a39e..5adc241ba 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -6,6 +6,7 @@ import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js"; import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js"; import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js"; import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js"; +import FunctionNetworkEmbeddingsProvider from "./FunctionNetworkEmbeddingsProvider.js"; import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js"; import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider.js"; import LMStudioEmbeddingsProvider from "./LMStudio.js"; @@ -36,6 +37,7 @@ export const allEmbeddingsProviders: Record< openai: OpenAIEmbeddingsProvider, cohere: CohereEmbeddingsProvider, "free-trial": FreeTrialEmbeddingsProvider, + "function-network": FunctionNetworkEmbeddingsProvider, "huggingface-tei": HuggingFaceTEIEmbeddingsProvider, gemini: GeminiEmbeddingsProvider, "continue-proxy": ContinueProxyEmbeddingsProvider, diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 8e475d01e..363e7c28a 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -84,6 +84,13 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "llama3.2", ]; +function modelSupportsTools(modelName: string) { + return ( + modelName.includes("claude") && + (modelName.includes("3-5") || modelName.includes("3.5")) + ); +} + function modelSupportsImages( provider: ModelProvider, model: string, @@ -124,6 +131,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [ "sambanova", "nebius", "vertexai", + "function-network", ]; function llmCanGenerateInParallel( @@ -150,13 +158,12 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("chat-bison") || lower.includes("pplx") || lower.includes("gemini") || - lower.includes("grok")|| + lower.includes("grok") || lower.includes("moonshot") ) { - return undefined; + return undefined; } - - if (lower.includes("llama3")) { + if (lower.includes("llama3") || lower.includes("llama-3")) { return "llama3"; } @@ -354,4 +361,5 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, + modelSupportsTools, }; diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 5191765cd..b1cb0da93 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,4 +1,6 @@ import { ChatHistoryItem, ChatMessage, MessagePart } from "../index.js"; +import { normalizeToMessageParts } from "../util/messageContent.js"; +import { modelSupportsTools } from "./autodetect.js"; const SYSTEM_MESSAGE = `When generating new code: @@ -58,52 +60,67 @@ function helloWorld() { Always follow these guidelines when generating code responses.`; -function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean { - const contentStr = typeof content === "string" ? content : content[0].text; +const TOOL_USE_RULES = `When using tools, follow the following guidelines: +- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`; - if (!contentStr) { - return false; +function constructSystemPrompt(model: string): string | null { + if (model.includes("sonnet")) { + return SYSTEM_MESSAGE + "\n\n" + TOOL_USE_RULES; + } + if (modelSupportsTools(model)) { + return TOOL_USE_RULES; } - const codeBlockRegex = /```[\w\W]*?\.[\w\W]*/; - return codeBlockRegex.test(contentStr); + return null; } +const CANCELED_TOOL_CALL_MESSAGE = + "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; + export function constructMessages( history: ChatHistoryItem[], model: string, ): ChatMessage[] { - const msgs = []; + const msgs: ChatMessage[] = []; - // Only using this system message with Sonnet right now - if ( - // hasCodeBlockWithFilename(history[0].message.content) && - model.includes("sonnet") - ) { + const systemMessage = constructSystemPrompt(model); + if (systemMessage) { msgs.push({ role: "system" as const, - content: SYSTEM_MESSAGE, + content: systemMessage, }); } for (let i = 0; i < history.length; i++) { const historyItem = history[i]; - let content = Array.isArray(historyItem.message.content) - ? historyItem.message.content - : [{ type: "text", text: historyItem.message.content } as MessagePart]; + if (historyItem.message.role === "user") { + // Gather context items for user messages + let content = normalizeToMessageParts(historyItem.message); - const ctxItems = historyItem.contextItems.map((ctxItem) => { - return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; - }); + const ctxItems = historyItem.contextItems.map((ctxItem) => { + return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; + }); - content = [...ctxItems, ...content]; - - msgs.push({ - role: historyItem.message.role, - content, - }); + content = [...ctxItems, ...content]; + msgs.push({ + ...historyItem.message, + content, + }); + } else if (historyItem.toolCallState?.status === "canceled") { + // Canceled tool call + msgs.push({ + ...historyItem.message, + content: CANCELED_TOOL_CALL_MESSAGE, + }); + } else { + msgs.push(historyItem.message); + } } - return msgs; + // Remove the "id" from all of the messages + return msgs.map((msg) => { + const { id, ...rest } = msg as any; + return rest; + }); } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 9b30ad4bc..49aed0e8d 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -2,6 +2,7 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; import { ChatMessage, MessageContent, MessagePart } from "../index.js"; +import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, GPTAsyncEncoder, @@ -9,7 +10,6 @@ import { } from "./asyncEncoder.js"; import { autodetectTemplateType } from "./autodetect.js"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; -import { stripImages } from "./images.js"; import llamaTokenizer from "./llamaTokenizer.js"; interface Encoding { encode: Tiktoken["encode"]; @@ -115,19 +115,28 @@ function countTokens( } } -function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { +function messageHasToolCalls(msg: ChatMessage): boolean { + return msg.role === "assistant" && !!msg.toolCalls; +} + +export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { const flattened: ChatMessage[] = []; + for (let i = 0; i < msgs.length; i++) { const msg = msgs[i]; + if ( flattened.length > 0 && - flattened[flattened.length - 1].role === msg.role + flattened[flattened.length - 1].role === msg.role && + !messageHasToolCalls(msg) && + !messageHasToolCalls(flattened[flattened.length - 1]) ) { flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; } else { flattened.push(msg); } } + return flattened; } @@ -222,11 +231,8 @@ function pruneRawPromptFromBottom( return pruneStringFromBottom(modelName, maxTokens, prompt); } -function summarize(message: MessageContent): string { - if (Array.isArray(message)) { - return `${stripImages(message).substring(0, 100)}...`; - } - return `${message.substring(0, 100)}...`; +function summarize(message: ChatMessage): string { + return `${renderChatMessage(message).substring(0, 100)}...`; } function pruneChatHistory( @@ -257,7 +263,7 @@ function pruneChatHistory( for (let i = 0; i < longerThanOneThird.length; i++) { // Prune line-by-line from the top const message = longerThanOneThird[i]; - const content = stripImages(message.content); + const content = renderChatMessage(message); const deltaNeeded = totalTokens - contextLength; const delta = Math.min(deltaNeeded, distanceFromThird[i]); message.content = pruneStringFromTop( @@ -273,8 +279,8 @@ function pruneChatHistory( while (totalTokens > contextLength && i < chatHistory.length - 5) { const message = chatHistory[0]; totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message.content), modelName); - message.content = summarize(message.content); + totalTokens += countTokens(summarize(message), modelName); + message.content = summarize(message); i++; } @@ -297,8 +303,8 @@ function pruneChatHistory( ) { const message = chatHistory[i]; totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message.content), modelName); - message.content = summarize(message.content); + totalTokens += countTokens(summarize(message), modelName); + message.content = summarize(message); i++; } @@ -314,7 +320,7 @@ function pruneChatHistory( message.content = pruneRawPromptFromTop( modelName, contextLength, - stripImages(message.content), + renderChatMessage(message), tokensForCompletion, ); totalTokens = contextLength; @@ -344,6 +350,24 @@ function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] { }); } +function chatMessageIsEmpty(message: ChatMessage): boolean { + switch (message.role) { + case "system": + case "user": + return ( + typeof message.content === "string" && message.content.trim() === "" + ); + case "assistant": + return ( + typeof message.content === "string" && + message.content.trim() === "" && + !message.toolCalls + ); + case "tool": + return false; + } +} + function compileChatMessages( modelName: string, msgs: ChatMessage[] | undefined, @@ -357,7 +381,7 @@ function compileChatMessages( let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) - .filter((msg) => msg.content !== "" && msg.role !== "system") + .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") : []; msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); @@ -376,7 +400,7 @@ function compileChatMessages( ) { let content = ""; if (msgs?.[0].role === "system") { - content = stripImages(msgs?.[0].content); + content = renderChatMessage(msgs?.[0]); } if (systemMessage && systemMessage.trim() !== "") { const shouldAddNewLines = content !== ""; @@ -411,7 +435,7 @@ function compileChatMessages( if (!supportsImages) { for (const msg of msgsCopy) { if ("content" in msg && Array.isArray(msg.content)) { - const content = stripImages(msg.content); + const content = renderChatMessage(msg); msg.content = content; } } diff --git a/core/llm/flattenMessages.test.ts b/core/llm/flattenMessages.test.ts new file mode 100644 index 000000000..6f5ba0a4c --- /dev/null +++ b/core/llm/flattenMessages.test.ts @@ -0,0 +1,104 @@ +import { ChatMessage } from ".."; +import { flattenMessages } from "./countTokens"; + +describe("flattenMessages", () => { + it("should return an empty array when given an empty array", () => { + expect(flattenMessages([])).toEqual([]); + }); + + it("should return the same array when there is only one message", () => { + const messages: ChatMessage[] = [{ role: "user", content: "Hello" }]; + expect(flattenMessages(messages)).toEqual(messages); + }); + + it("should return the same array when messages have different roles", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" }, + { role: "assistant", content: "Hi there!" }, + { role: "user", content: "How are you?" }, + ]; + expect(flattenMessages(messages)).toEqual(messages); + }); + + it("should combine consecutive messages with the same role", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" }, + { role: "user", content: "How are you?" }, + { role: "assistant", content: "I am an AI assistant." }, + { role: "assistant", content: "How can I help you?" }, + ]; + const expected: ChatMessage[] = [ + { role: "user", content: "Hello\n\nHow are you?" }, + { + role: "assistant", + content: "I am an AI assistant.\n\nHow can I help you?", + }, + ]; + expect(flattenMessages(messages)).toEqual(expected); + }); + + it("should handle messages with undefined or empty content", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" }, + { role: "user", content: "" }, + { role: "assistant", content: "" }, + { role: "assistant", content: "Sure, I can help with that." }, + ]; + const expected: ChatMessage[] = [ + { role: "user", content: "Hello\n\n" }, + { role: "assistant", content: "\n\nSure, I can help with that." }, + ]; + expect(flattenMessages(messages)).toEqual(expected); + }); + + it("should not combine non-consecutive messages with the same role", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "First message" }, + { role: "assistant", content: "Reply to first message" }, + { role: "user", content: "Second message" }, + ]; + expect(flattenMessages(messages)).toEqual(messages); + }); + + it("should handle a mix of message roles and contents correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Message one" }, + { role: "user", content: "Message two" }, + { role: "assistant", content: "Reply one" }, + { role: "user", content: "Message three" }, + { role: "user", content: "Message four" }, + { role: "assistant", content: "Reply two" }, + ]; + const expected: ChatMessage[] = [ + { role: "user", content: "Message one\n\nMessage two" }, + { role: "assistant", content: "Reply one" }, + { role: "user", content: "Message three\n\nMessage four" }, + { role: "assistant", content: "Reply two" }, + ]; + expect(flattenMessages(messages)).toEqual(expected); + }); + + it("should not combine adjacent assistant messages when one of them is a tool call", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "What's the capital of France?" }, + { role: "assistant", content: "Paris" }, + { + role: "assistant", + content: " ", + toolCalls: [ + { + id: "test", + type: "function", + function: { + name: "getCapital", + arguments: JSON.stringify({ + country: "France", + }), + }, + }, + ], + }, + ]; + expect(flattenMessages(messages).length).toBe(3); + }); +}); diff --git a/core/llm/images.ts b/core/llm/images.ts deleted file mode 100644 index 912ae48ca..000000000 --- a/core/llm/images.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { MessageContent } from "../index.js"; - -export function stripImages(content: MessageContent): string { - if (Array.isArray(content)) { - return content - .filter((part) => part.type === "text") - .map((part) => part.text) - .join("\n"); - } - return content; - } \ No newline at end of file diff --git a/core/llm/index.ts b/core/llm/index.ts index 8759af8a5..144df72d2 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -4,7 +4,6 @@ import Handlebars from "handlebars"; import { CacheBehavior, ChatMessage, - ChatMessageRole, CompletionOptions, ILLM, LLMFullCompletionOptions, @@ -24,6 +23,7 @@ import mergeJson from "../util/merge.js"; import { Telemetry } from "../util/posthog.js"; import { withExponentialBackoff } from "../util/withExponentialBackoff.js"; +import { renderChatMessage } from "../util/messageContent.js"; import { autodetectPromptTemplates, autodetectTemplateFunction, @@ -41,7 +41,6 @@ import { countTokens, pruneRawPromptFromTop, } from "./countTokens.js"; -import { stripImages } from "./images.js"; import CompletionOptionsForModels from "./templates/options.js"; export abstract class BaseLLM implements ILLM { @@ -372,7 +371,8 @@ export abstract class BaseLLM implements ILLM { `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`, ); } else { - if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here + if (e.name !== "AbortError") { + // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here console.debug( `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, ); @@ -414,7 +414,7 @@ export abstract class BaseLLM implements ILLM { let formatted = ""; for (const msg of msgsCopy) { if ("content" in msg && Array.isArray(msg.content)) { - const content = stripImages(msg.content); + const content = renderChatMessage(msg); msg.content = content; } formatted += `<${msg.role}>\n${msg.content || ""}\n\n`; @@ -533,7 +533,11 @@ export abstract class BaseLLM implements ILLM { }; } - async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) { + async complete( + _prompt: string, + signal: AbortSignal, + options: LLMFullCompletionOptions = {}, + ) { const { completionOptions, log, raw } = this._parseCompletionOptions(options); @@ -568,12 +572,16 @@ export abstract class BaseLLM implements ILLM { return completion; } - async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) { + async chat( + messages: ChatMessage[], + signal: AbortSignal, + options: LLMFullCompletionOptions = {}, + ) { let completion = ""; for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; } - return { role: "assistant" as ChatMessageRole, content: completion }; + return { role: "assistant" as const, content: completion }; } async *streamChat( @@ -668,7 +676,11 @@ export abstract class BaseLLM implements ILLM { } } - protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) { + protected async _complete( + prompt: string, + signal: AbortSignal, + options: CompletionOptions, + ) { let completion = ""; for await (const chunk of this._streamComplete(prompt, signal, options)) { completion += chunk; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 5033658c7..a10d2c4a4 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -30,11 +30,79 @@ class Anthropic extends BaseLLM { model: options.model === "claude-2" ? "claude-2.1" : options.model, stop_sequences: options.stop?.filter((x) => x.trim() !== ""), stream: options.stream ?? true, + tools: options.tools?.map((tool) => ({ + name: tool.function.name, + description: tool.function.description, + input_schema: tool.function.parameters, + })), }; return finalOptions; } + private convertMessage(message: ChatMessage, addCaching: boolean): any { + if (message.role === "tool") { + return { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: message.toolCallId, + content: renderChatMessage(message) || undefined, + }, + ], + }; + } else if (message.role === "assistant" && message.toolCalls) { + return { + role: "assistant", + content: message.toolCalls.map((toolCall) => ({ + type: "tool_use", + id: toolCall.id, + name: toolCall.function?.name, + input: JSON.parse(toolCall.function?.arguments || "{}"), + })), + }; + } + + if (typeof message.content === "string") { + var chatMessage = { + role: message.role, + content: [ + { + type: "text", + text: message.content, + ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), + }, + ], + }; + return chatMessage; + } + + return { + role: message.role, + content: message.content.map((part, contentIdx) => { + if (part.type === "text") { + const newpart = { + ...part, + // If multiple text parts, only add cache_control to the last one + ...(addCaching && contentIdx == message.content.length - 1 + ? { cache_control: { type: "ephemeral" } } + : {}), + }; + return newpart; + } + return { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: part.imageUrl?.url.split(",")[1], + }, + }; + }), + }; + } + public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI const filteredmessages = msgs.filter( @@ -54,43 +122,8 @@ class Anthropic extends BaseLLM { this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); - if (typeof message.content === "string") { - var chatMessage = { - ...message, - content: [ - { - type: "text", - text: message.content, - ...(addCaching ? { cache_control: { type: "ephemeral" } } : {}), - }, - ], - }; - return chatMessage; - } - - return { - ...message, - content: message.content.map((part, contentIdx) => { - if (part.type === "text") { - const newpart = { - ...part, - // If multiple text parts, only add cache_control to the last one - ...(addCaching && contentIdx == message.content.length - 1 - ? { cache_control: { type: "ephemeral" } } - : {}), - }; - return newpart; - } - return { - type: "image", - source: { - type: "base64", - media_type: "image/jpeg", - data: part.imageUrl?.url.split(",")[1], - }, - }; - }), - }; + const chatMessage = this.convertMessage(message, !!addCaching); + return chatMessage; }); return messages; } @@ -102,7 +135,7 @@ class Anthropic extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -114,9 +147,10 @@ class Anthropic extends BaseLLM { const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; const systemMessage: string = stripImages( - messages.filter((m) => m.role === "system")[0]?.content, + messages.filter((m) => m.role === "system")[0]?.content ?? "", ); + const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", headers: { @@ -130,7 +164,7 @@ class Anthropic extends BaseLLM { }, body: JSON.stringify({ ...this.convertArgs(options), - messages: this.convertMessages(messages), + messages: msgs, system: shouldCacheSystemMessage ? [ { @@ -141,21 +175,74 @@ class Anthropic extends BaseLLM { ] : systemMessage, }), - signal + signal, }); + if (!response.ok) { + const json = await response.json(); + if (json.type === "error") { + if (json.error?.type === "overloaded_error") { + throw new Error( + "The Anthropic API is currently overloaded. Please check their status page: https://status.anthropic.com/#past-incidents", + ); + } + throw new Error(json.message); + } + throw new Error( + `Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`, + ); + } + if (options.stream === false) { const data = await response.json(); yield { role: "assistant", content: data.content[0].text }; return; } + let lastToolUseId: string | undefined; + let lastToolUseName: string | undefined; for await (const value of streamSse(response)) { - if (value.type == "message_start") { - console.log(value); - } - if (value.delta?.text) { - yield { role: "assistant", content: value.delta.text }; + // https://docs.anthropic.com/en/api/messages-streaming#event-types + switch (value.type) { + case "content_block_start": + if (value.content_block.type === "tool_use") { + lastToolUseId = value.content_block.id; + lastToolUseName = value.content_block.name; + } + break; + case "content_block_delta": + // https://docs.anthropic.com/en/api/messages-streaming#delta-types + switch (value.delta.type) { + case "text_delta": + yield { role: "assistant", content: value.delta.text }; + break; + case "input_json_delta": + if (!lastToolUseId || !lastToolUseName) { + throw new Error("No tool use found"); + } + yield { + role: "assistant", + content: "", + toolCalls: [ + { + id: lastToolUseId, + type: "function", + function: { + name: lastToolUseName, + arguments: value.delta.partial_json, + }, + }, + ], + }; + break; + } + break; + case "content_block_stop": + lastToolUseId = undefined; + lastToolUseName = undefined; + break; + default: + break; } } } diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index c2f76d0a8..31445c84a 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -11,7 +11,7 @@ import { MessageContent, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; /** @@ -47,7 +47,7 @@ class Bedrock extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -91,7 +91,7 @@ class Bedrock extends BaseLLM { const input = this._generateConverseInput(messages, options); const command = new ConverseStreamCommand(input); - const response = await client.send(command, { abortSignal: signal}); + const response = await client.send(command, { abortSignal: signal }); if (response.stream) { for await (const chunk of response.stream) { diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 07e2e427c..3c4766365 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -1,5 +1,5 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -36,12 +36,15 @@ export default class Cloudflare extends BaseLLM { model: this.model, ...this._convertArgs(options), }), - signal + signal, }); for await (const value of streamSse(resp)) { if (value.choices?.[0]?.delta?.content) { - yield value.choices[0].delta; + yield { + role: "assistant", + content: value.choices[0].delta, + }; } } } @@ -56,7 +59,7 @@ export default class Cloudflare extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } } diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 98135c7cc..a43df7a62 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -4,7 +4,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamJSON } from "../stream.js"; @@ -51,7 +51,7 @@ class Cohere extends BaseLLM { ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; for await (const update of this._streamChat(messages, signal, options)) { - yield stripImages(update.content); + yield renderChatMessage(update); } } @@ -75,7 +75,7 @@ class Cohere extends BaseLLM { chat_history: this._convertMessages(messages), preamble: this.systemMessage, }), - signal + signal, }); if (options.stream === false) { diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index ecca89d16..8c5b0f459 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -6,7 +6,7 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; interface IFlowiseApiOptions { @@ -126,7 +126,7 @@ class Flowise extends BaseLLM { ): AsyncGenerator { const message: ChatMessage = { role: "user", content: prompt }; for await (const chunk of this._streamChat([message], signal, options)) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -141,7 +141,7 @@ class Flowise extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), - signal + signal, }).then((res) => res.json()); while (await socketInfo.hasNextToken()) { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 8f80c7418..895d6c42f 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -74,7 +74,7 @@ class FreeTrial extends BaseLLM { prompt, ...args, }), - signal + signal, }); let completion = ""; @@ -82,10 +82,18 @@ class FreeTrial extends BaseLLM { yield value; completion += value; } - this._countTokens(completion, args.model, false); + void this._countTokens(completion, args.model, false); } protected _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return { + role: "tool", + content: message.content, + tool_call_id: message.toolCallId, + }; + } + if (typeof message.content === "string") { return message; } @@ -123,7 +131,7 @@ class FreeTrial extends BaseLLM { messages: messages.map(this._convertMessage), ...args, }), - signal + signal, }); let completion = ""; @@ -158,7 +166,7 @@ class FreeTrial extends BaseLLM { suffix, ...args, }), - signal + signal, }); let completion = ""; diff --git a/core/llm/llms/FunctionNetwork.ts b/core/llm/llms/FunctionNetwork.ts new file mode 100644 index 000000000..1010e47ed --- /dev/null +++ b/core/llm/llms/FunctionNetwork.ts @@ -0,0 +1,41 @@ +import { LLMOptions, ModelProvider } from "../../index.js"; + +import OpenAI from "./OpenAI.js"; + +class FunctionNetwork extends OpenAI { + static providerName: ModelProvider = "function-network"; + static defaultOptions: Partial = { + apiBase: "https://api.function.network/v1/", + model: "meta/llama-3.1-70b-instruct", + }; + + private static modelConversion: { [key: string]: string } = { + "mistral-7b": "mistral/mistral-7b-instruct-v0.1", + "llama3-8b": "meta/llama-3-8b-instruct", + "llama3.1-8b": "meta/llama-3.1-8b-instruct", + "llama3.1-70b": "meta/llama-3.1-70b-instruct", + "deepseek-7b": "thebloke/deepseek-coder-6.7b-instruct-awq", + }; + + constructor(options: LLMOptions) { + super(options); + } + + protected _convertModelName(model: string): string { + return FunctionNetwork.modelConversion[model] ?? model; + } + + public supportsFim(): boolean { + return false; + } + + public supportsCompletions(): boolean { + return false; + } + + public supportsPrefill(): boolean { + return false; + } +} + +export default FunctionNetwork; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index ada603240..e9cc484c8 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -5,7 +5,7 @@ import { MessagePart, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -19,7 +19,8 @@ class Gemini extends BaseLLM { }; // Function to convert completion options to Gemini format - public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI + public convertArgs(options: CompletionOptions) { + // should be public for use within VertexAI const finalOptions: any = {}; // Initialize an empty object // Map known options @@ -54,17 +55,19 @@ class Gemini extends BaseLLM { signal, options, )) { - yield stripImages(message.content); + yield renderChatMessage(message); } } - public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI + public removeSystemMessage(messages: ChatMessage[]) { + // should be public for use within VertexAI const msgs = [...messages]; if (msgs[0]?.role === "system") { const sysMsg = msgs.shift()?.content; // @ts-ignore if (msgs[0]?.role === "user") { + // @ts-ignore msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`; } } @@ -143,6 +146,9 @@ class Gemini extends BaseLLM { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + if (msg.role === "tool") { + return null; + } return { role: msg.role === "assistant" ? "model" : "user", parts: @@ -165,7 +171,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); let buffer = ""; @@ -234,7 +240,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 642f8bcc5..c56884e4b 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -4,13 +4,11 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; -interface OllamaChatMessage extends ChatMessage { - images?: string[]; -} +type OllamaChatMessage = ChatMessage & { images?: string[] }; // See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter interface ModelFileParams { @@ -195,6 +193,10 @@ class Ollama extends BaseLLM { } private _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return null; + } + if (typeof message.content === "string") { return message; } @@ -210,7 +212,7 @@ class Ollama extends BaseLLM { return { role: message.role, - content: stripImages(message.content), + content: renderChatMessage(message), images, }; } @@ -221,7 +223,7 @@ class Ollama extends BaseLLM { ): ChatOptions { return { model: this._getModel(), - messages: messages.map(this._convertMessage), + messages: messages.map(this._convertMessage).filter(Boolean) as any, options: this._getModelFileParams(options), keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes stream: options.stream, diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 4f929b506..ed9810932 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -3,8 +3,9 @@ import { CompletionOptions, LLMOptions, ModelProvider, + Tool, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; @@ -56,6 +57,14 @@ class OpenAI extends BaseLLM { }; protected _convertMessage(message: ChatMessage) { + if (message.role === "tool") { + return { + role: "tool", + content: message.content, + tool_call_id: message.toolCallId, + }; + } + if (typeof message.content === "string") { return message; } else if (!message.content.some((item) => item.type !== "text")) { @@ -99,8 +108,22 @@ class OpenAI extends BaseLLM { return ["gpt-4o-mini", "gpt-4o"].includes(model); } + private convertTool(tool: Tool): any { + return { + type: tool.type, + function: { + name: tool.function.name, + description: tool.function.description, + parameters: tool.function.parameters, + strict: tool.function.strict, + }, + }; + } + protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { const url = new URL(this.apiBase!); + const tools = options.tools?.map(this.convertTool); + const finalOptions: any = { messages: messages.map(this._convertMessage), model: this._convertModelName(options.model), @@ -122,6 +145,7 @@ class OpenAI extends BaseLLM { this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, + tools, }; // OpenAI o1-preview and o1-mini: @@ -206,7 +230,7 @@ class OpenAI extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -249,7 +273,7 @@ class OpenAI extends BaseLLM { options.raw) ) { for await (const content of this._legacystreamComplete( - stripImages(messages[messages.length - 1]?.content || ""), + renderChatMessage(messages[messages.length - 1]), signal, options, )) { @@ -266,6 +290,9 @@ class OpenAI extends BaseLLM { body.messages = body.messages.map((m: any) => ({ ...m, content: m.content === "" ? " " : m.content, + // We call it toolCalls, they call it tool_calls + tool_calls: m.toolCalls, + tool_call_id: m.toolCallId, })) as any; const response = await this.fetch(this._getEndpoint("chat/completions"), { method: "POST", @@ -283,7 +310,25 @@ class OpenAI extends BaseLLM { for await (const value of streamSse(response)) { if (value.choices?.[0]?.delta?.content) { - yield value.choices[0].delta; + yield { + role: "assistant", + content: value.choices[0].delta.content, + }; + } else if (value.choices?.[0]?.delta?.tool_calls) { + yield { + role: "assistant", + content: "", + toolCalls: value.choices?.[0]?.delta?.tool_calls.map( + (tool_call: any) => ({ + id: tool_call.id, + type: tool_call.type, + function: { + name: tool_call.function.name, + arguments: tool_call.function.arguments, + }, + }), + ), + }; } } } @@ -333,4 +378,4 @@ class OpenAI extends BaseLLM { } } -export default OpenAI; \ No newline at end of file +export default OpenAI; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index c17aac90d..c9254eacc 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -4,13 +4,11 @@ import { ChatMessage, CompletionOptions, LLMOptions, - MessagePart, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; -import { streamSse } from "../stream.js"; -import { streamResponse } from "../stream.js"; +import { streamResponse, streamSse } from "../stream.js"; import Anthropic from "./Anthropic.js"; import Gemini from "./Gemini.js"; @@ -40,16 +38,17 @@ class VertexAI extends BaseLLM { super(_options); this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options); this.vertexProvider = - _options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral") + _options.model.includes("mistral") || + _options.model.includes("codestral") || + _options.model.includes("mixtral") ? "mistral" : _options.model.includes("claude") ? "anthropic" : _options.model.includes("gemini") - ? "gemini" : - "unknown"; + ? "gemini" + : "unknown"; this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); - } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -82,18 +81,18 @@ class VertexAI extends BaseLLM { }; } - protected async *StreamChatAnthropic( messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( - messages.filter((m) => m.role === "system")[0]?.content, + const shouldCacheSystemMessage = + !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const systemMessage: string = renderChatMessage( + messages.filter((m) => m.role === "system")[0], ); const apiURL = new URL( `publishers/anthropic/models/${options.model}:streamRawPredict`, - this.apiBase + this.apiBase, ); const response = await this.fetch(apiURL, { @@ -108,12 +107,12 @@ class VertexAI extends BaseLLM { messages: this.anthropicInstance.convertMessages(messages), system: shouldCacheSystemMessage ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] + { + type: "text", + text: this.systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] : systemMessage, }), }); @@ -125,14 +124,15 @@ class VertexAI extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.type == "message_start") {console.log(value);} + if (value.type == "message_start") { + console.log(value); + } if (value.delta?.text) { yield { role: "assistant", content: value.delta.text }; } } } - //Gemini private async *streamChatGemini( @@ -152,6 +152,10 @@ class VertexAI extends BaseLLM { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + if (msg.role === "tool") { + return null; + } + return { role: msg.role === "assistant" ? "model" : "user", parts: @@ -168,8 +172,8 @@ class VertexAI extends BaseLLM { // if this.systemMessage is defined, reformat it for Gemini API ...(this.systemMessage && !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, - }), + systemInstruction: { parts: [{ text: this.systemMessage }] }, + }), }; const response = await this.fetch(apiURL, { method: "POST", @@ -265,7 +269,6 @@ class VertexAI extends BaseLLM { //Mistral - protected async *StreamChatMistral( messages: ChatMessage[], options: CompletionOptions, @@ -330,7 +333,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), - signal + signal, }); for await (const chunk of streamSse(response)) { @@ -338,8 +341,6 @@ class VertexAI extends BaseLLM { } } - - //gecko protected async *streamFimGecko( prefix: string, @@ -347,15 +348,18 @@ class VertexAI extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); + const endpoint = new URL( + "publishers/google/models/code-gecko:predict", + this.apiBase, + ); const resp = await this.fetch(endpoint, { method: "POST", body: JSON.stringify({ instances: [ { prefix: prefix, - suffix: suffix - } + suffix: suffix, + }, ], parameters: { temperature: options.temperature, @@ -363,10 +367,9 @@ class VertexAI extends BaseLLM { stopSequences: options.stop?.splice(0, 5), frequencyPenalty: options.frequencyPenalty, presencePenalty: options.frequencyPenalty, - } - + }, }), - signal + signal, }); // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. @@ -409,7 +412,7 @@ class VertexAI extends BaseLLM { signal, options, )) { - yield stripImages(message.content); + yield renderChatMessage(message); } } @@ -419,9 +422,6 @@ class VertexAI extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - - - if (this.model === "code-gecko") { yield* this.streamFimGecko(prefix, suffix, signal, options); } else if (this.model.includes("codestral")) { @@ -429,21 +429,15 @@ class VertexAI extends BaseLLM { } else { throw new Error(`Unsupported model: ${this.model}`); } - - } supportsFim(): boolean { return ["code-gecko", "codestral-latest"].includes(this.model); } - - } async function delay(seconds: number) { return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } - - export default VertexAI; diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 808557692..fb82dacf9 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -4,25 +4,22 @@ import { LLMOptions, ModelProvider, } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; let watsonxToken = { - expiration: 0, - token: "" + expiration: 0, + token: "", }; class WatsonX extends BaseLLM { - constructor(options: LLMOptions) { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { - if ( - this.apiBase?.includes("cloud.ibm.com") - ) { + if (this.apiBase?.includes("cloud.ibm.com")) { // watsonx SaaS const wxToken = await ( await fetch( @@ -82,11 +79,9 @@ class WatsonX extends BaseLLM { } getWatsonxEndpoint(): string { - return ( - this.deploymentId ? - `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`: - `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}` - ); + return this.deploymentId + ? `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}` + : `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`; } static providerName: ModelProvider = "watsonx"; @@ -96,6 +91,10 @@ class WatsonX extends BaseLLM { return message; } + if (message.role === "tool") { + return null; + } + const parts = message.content.map((part) => { const msg: any = { type: part.type, @@ -119,7 +118,7 @@ class WatsonX extends BaseLLM { protected _convertArgs(options: any, messages: ChatMessage[]) { const finalOptions = { - messages: messages.map(this._convertMessage), + messages: messages.map(this._convertMessage).filter(Boolean), model: this._convertModelName(options.model), max_tokens: options.maxTokens, temperature: options.temperature, @@ -133,8 +132,9 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxToken.token}`, + Authorization: `${ + watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, }; } @@ -165,7 +165,7 @@ class WatsonX extends BaseLLM { signal, options, )) { - yield stripImages(chunk.content); + yield renderChatMessage(chunk); } } @@ -183,7 +183,8 @@ class WatsonX extends BaseLLM { watsonxToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${(watsonxToken.expiration - now) / 60 + `Reusing token (expires in ${ + (watsonxToken.expiration - now) / 60 } mins)`, ); } @@ -191,7 +192,8 @@ class WatsonX extends BaseLLM { throw new Error("Something went wrong. Check your credentials, please."); } const stopSequences = - options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []); + options.stop?.slice(0, 6) ?? + (options.model?.includes("granite") ? ["Question:"] : []); const url = this.getWatsonxEndpoint(); const headers = this._getHeaders(); @@ -224,7 +226,7 @@ class WatsonX extends BaseLLM { method: "POST", headers: headers, body: JSON.stringify(payload), - signal + signal, }); if (!response.ok || response.body === null) { diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 0297b7868..632607ed1 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -21,6 +21,7 @@ import Deepseek from "./Deepseek"; import Fireworks from "./Fireworks"; import Flowise from "./Flowise"; import FreeTrial from "./FreeTrial"; +import FunctionNetwork from "./FunctionNetwork"; import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; @@ -54,6 +55,7 @@ const LLMs = [ Anthropic, Cohere, FreeTrial, + FunctionNetwork, Gemini, Llamafile, Moonshot, diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index 9d26620f4..a4b999b05 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -1,5 +1,5 @@ import { ChatMessage } from "../../index.js"; -import { stripImages } from "../images.js"; +import { renderChatMessage } from "../../util/messageContent.js"; function templateFactory( systemMessage: (msg: ChatMessage) => string, @@ -64,7 +64,7 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; let hasSystem = msgs[0].role === "system"; - if (hasSystem && stripImages(msgs[0].content).trim() === "") { + if (hasSystem && renderChatMessage(msgs[0]).trim() === "") { hasSystem = false; msgs = msgs.slice(1); } @@ -158,7 +158,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string { prompt += "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n"; if (msgs[0].role === "system") { - system = stripImages(msgs.shift()!.content); + system = renderChatMessage(msgs.shift()!); } for (let i = 0; i < msgs.length; i++) { @@ -245,7 +245,7 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; for (const msg of msgs) { - prompt += `Source: ${msg.role}\n\n ${stripImages(msg.content).trim()}`; + prompt += `Source: ${msg.role}\n\n ${renderChatMessage(msg).trim()}`; prompt += " "; } diff --git a/core/package-lock.json b/core/package-lock.json index a53a1a49c..58762590f 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -14,6 +14,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -47,6 +48,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", @@ -3381,6 +3383,70 @@ "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.2.tgz", "integrity": "sha512-B5VFcZlwlwQg6htbIjCjj3z/pj3I929BzgWowiLzxYC40ag+v3e/hM9EDGWCEdNIT+PDMchAwS67iNB+WhE7qg==" }, + "node_modules/@esbuild/android-arm": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", + "integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz", + "integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz", + "integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz", + "integrity": "sha512-80wEoCfF/hFKM6WE1FyBHc9SfUblloAWx6FJkFWTWiCoht9Mc0ARGEM47e67W9rI09YoUxJL68WHfDRYEAvOhg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, "node_modules/@esbuild/darwin-x64": { "version": "0.17.19", "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz", @@ -3397,6 +3463,278 @@ "node": ">=12" } }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz", + "integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz", + "integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz", + "integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz", + "integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz", + "integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz", + "integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz", + "integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz", + "integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz", + "integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz", + "integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz", + "integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz", + "integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz", + "integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz", + "integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz", + "integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz", + "integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.17.19", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", + "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz", @@ -4155,6 +4493,16 @@ "win32" ] }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.0.0.tgz", + "integrity": "sha512-mbe0otw8vTtZoL5pVucXAmx6oEC7YjdXBgVeFkJXASu4OAnLkrIeNw9zwzU5CwEp19M54bjOUGcna90Dl/H5Bw==", + "dependencies": { + "content-type": "^1.0.5", + "raw-body": "^3.0.0", + "zod": "^3.23.8" + } + }, "node_modules/@mozilla/readability": { "version": "0.5.0", "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.5.0.tgz", @@ -6557,6 +6905,14 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "dev": true }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/cacache": { "version": "15.3.0", "resolved": "https://registry.npmjs.org/cacache/-/cacache-15.3.0.tgz", @@ -6996,6 +7352,14 @@ "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -7379,6 +7743,14 @@ "node": ">=0.10" } }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/deprecation": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", @@ -9343,6 +9715,21 @@ "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==", "optional": true }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/http-proxy-agent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", @@ -12497,6 +12884,11 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/partial-json": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz", + "integrity": "sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==" + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -13262,6 +13654,20 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/raw-body": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz", + "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.6.3", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/rc": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", @@ -13740,6 +14146,11 @@ "node": ">= 0.4" } }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, "node_modules/sharp": { "version": "0.32.6", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz", @@ -14134,6 +14545,14 @@ "node": ">=8" } }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/stoppable": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/stoppable/-/stoppable-1.1.0.tgz", @@ -14626,6 +15045,14 @@ "node": ">=8.0" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, "node_modules/tough-cookie": { "version": "4.1.4", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", @@ -15042,6 +15469,14 @@ "node": ">= 4.0.0" } }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/update-browserslist-db": { "version": "1.0.16", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.16.tgz", diff --git a/core/package.json b/core/package.json index 91652280a..78d7ecf65 100644 --- a/core/package.json +++ b/core/package.json @@ -45,6 +45,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -78,6 +79,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 9e4f0c194..7d3750ad4 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -1,8 +1,8 @@ import * as YAML from "yaml"; import { ContinueSDK, SlashCommand } from "../.."; -import { stripImages } from "../../llm/images"; import { getBasename } from "../../util/index"; +import { renderChatMessage } from "../../util/messageContent"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; @@ -90,8 +90,11 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { - yield stripImages(chunk.content); + for await (const chunk of context.llm.streamChat( + messages, + new AbortController().signal, + )) { + yield renderChatMessage(chunk); } }, }; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 9202d08b4..35785d359 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -4,21 +4,21 @@ import { ProfileDescription } from "../config/ConfigHandler"; import type { BrowserSerializedContinueConfig, ChatMessage, + ContextItem, ContextItemWithId, ContextSubmenuItem, DiffLine, FileSymbolMap, IdeSettings, - IndexingStatus, LLMFullCompletionOptions, - MessageContent, ModelDescription, ModelRoles, - Session, RangeInFile, SerializedContinueConfig, + Session, SessionMetadata, SiteIndexingConfig, + ToolCall, } from "../"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -123,7 +123,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; }, - ProtocolGeneratorType, + ProtocolGeneratorType, ]; streamDiffLines: [ { @@ -174,4 +174,5 @@ export type ToCoreFromIdeOrWebviewProtocol = { "profiles/switch": [{ id: string }, undefined]; "auth/getAuthUrl": [undefined, { url: string }]; + "tools/call": [{ toolCall: ToolCall }, { contextItems: ContextItem[] }]; }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 91fa40395..cd79bcd21 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -56,7 +56,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { { accept: boolean; onlyFirst: boolean; filepath: string }, void, ]; - "edit/escape": [undefined, void]; + "edit/exit": [{ shouldFocusEditor: boolean }, void]; }; export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 720a6f66e..bbcfbf3f2 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -58,6 +58,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "addAutocompleteModel", "profiles/switch", "didChangeSelectedProfile", + "tools/call", ]; // Message types to pass through from core to webview diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts new file mode 100644 index 000000000..55e2c5214 --- /dev/null +++ b/core/tools/builtIn.ts @@ -0,0 +1,11 @@ +export enum BuiltInToolNames { + ReadFile = "read_file", + ReadCurrentlyOpenFile = "read_currently_open_file", + CreateNewFile = "create_new_file", + RunTerminalCommand = "run_terminal_command", + ViewSubdirectory = "view_subdirectory", + ViewRepoMap = "view_repo_map", + ExactSearch = "exact_search", + SearchWeb = "search_web", + ViewDiff = "view_diff", +} diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts new file mode 100644 index 000000000..69307100e --- /dev/null +++ b/core/tools/callTool.ts @@ -0,0 +1,109 @@ +import { ContextItem, ToolExtras } from ".."; +import MCPConnectionSingleton from "../context/mcp"; +import { BuiltInToolNames } from "./builtIn"; + +import { createNewFileImpl } from "./implementations/createNewFile"; +import { exactSearchImpl } from "./implementations/exactSearch"; +import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; +import { readFileImpl } from "./implementations/readFile"; +import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; +import { searchWebImpl } from "./implementations/searchWeb"; +import { viewDiffImpl } from "./implementations/viewDiff"; +import { viewRepoMapImpl } from "./implementations/viewRepoMap"; +import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory"; + +async function callHttpTool( + url: string, + args: any, + extras: ToolExtras, +): Promise { + const response = await extras.fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + arguments: args, + }), + }); + + if (!response.ok) { + throw new Error(`Failed to call tool: ${url}`); + } + + const data = await response.json(); + return data.output; +} + +async function callToolFromUri( + uri: string, + args: any, + extras: ToolExtras, +): Promise { + const canParse = URL.canParse(uri); + if (!canParse) { + throw new Error(`Invalid URI: ${uri}`); + } + const parsedUri = new URL(uri); + + switch (parsedUri?.protocol) { + case "http:": + case "https:": + return callHttpTool(uri, args, extras); + case "mcp:": + const client = await MCPConnectionSingleton.getExistingInstance(); + if (!client) { + throw new Error("MCP connection not found"); + } + const toolName = parsedUri!.hostname; + const response = await client.client.callTool({ + name: toolName, + arguments: args, + }); + + if (response.isError === true) { + throw new Error(`Failed to call tool: ${toolName}`); + } + + return (response.content as any).map((item: any) => { + if (item.type !== "text") { + throw new Error( + `Continue received item of type "${item.type}" from MCP tool, but currently only supports "text".`, + ); + } + return { name: toolName, description: toolName, content: item.text }; + }); + + default: + throw new Error(`Unsupported protocol: ${parsedUri?.protocol}`); + } +} + +export async function callTool( + uri: string, + args: any, + extras: ToolExtras, +): Promise { + switch (uri) { + case BuiltInToolNames.ReadFile: + return await readFileImpl(args, extras); + case BuiltInToolNames.CreateNewFile: + return await createNewFileImpl(args, extras); + case BuiltInToolNames.ExactSearch: + return await exactSearchImpl(args, extras); + case BuiltInToolNames.RunTerminalCommand: + return await runTerminalCommandImpl(args, extras); + case BuiltInToolNames.SearchWeb: + return await searchWebImpl(args, extras); + case BuiltInToolNames.ViewDiff: + return await viewDiffImpl(args, extras); + case BuiltInToolNames.ViewRepoMap: + return await viewRepoMapImpl(args, extras); + case BuiltInToolNames.ViewSubdirectory: + return await viewSubdirectoryImpl(args, extras); + case BuiltInToolNames.ReadCurrentlyOpenFile: + return await readCurrentlyOpenFileImpl(args, extras); + default: + return await callToolFromUri(uri, args, extras); + } +} diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts new file mode 100644 index 000000000..f0082891c --- /dev/null +++ b/core/tools/definitions/createNewFile.ts @@ -0,0 +1,27 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const createNewFileTool: Tool = { + type: "function", + displayTitle: "Create New File", + wouldLikeTo: "create a new file", + readonly: false, + function: { + name: BuiltInToolNames.CreateNewFile, + description: "Create a new file", + parameters: { + type: "object", + required: ["filepath", "contents"], + properties: { + filepath: { + type: "string", + description: "The path where the new file should be created", + }, + contents: { + type: "string", + description: "The contents to write to the new file", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts new file mode 100644 index 000000000..8358b55da --- /dev/null +++ b/core/tools/definitions/exactSearch.ts @@ -0,0 +1,24 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const exactSearchTool: Tool = { + type: "function", + displayTitle: "Exact Search", + wouldLikeTo: 'search for "{{{ query }}}" in the repository', + readonly: true, + function: { + name: BuiltInToolNames.ExactSearch, + description: "Perform an exact search over the repository using ripgrep.", + parameters: { + type: "object", + required: ["query"], + properties: { + query: { + type: "string", + description: + "The search query to use. Must be a valid ripgrep regex expression, escaped where needed", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts new file mode 100644 index 000000000..79497a158 --- /dev/null +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -0,0 +1,18 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const readCurrentlyOpenFileTool: Tool = { + type: "function", + displayTitle: "Read Currently Open File", + wouldLikeTo: "read the current file", + readonly: true, + function: { + name: BuiltInToolNames.ReadCurrentlyOpenFile, + description: + "Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, this is probably it.", + parameters: { + type: "object", + properties: {}, + }, + }, +}; diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts new file mode 100644 index 000000000..00e16ba32 --- /dev/null +++ b/core/tools/definitions/readFile.ts @@ -0,0 +1,25 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const readFileTool: Tool = { + type: "function", + displayTitle: "Read File", + wouldLikeTo: "read {{{ filepath }}}", + readonly: true, + function: { + name: BuiltInToolNames.ReadFile, + description: + "Use this tool whenever you need to view the contents of a file.", + parameters: { + type: "object", + required: ["filepath"], + properties: { + filepath: { + type: "string", + description: + "The path of the file to read, relative to the root of the workspace.", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts new file mode 100644 index 000000000..82b2d342c --- /dev/null +++ b/core/tools/definitions/runTerminalCommand.ts @@ -0,0 +1,25 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const runTerminalCommandTool: Tool = { + type: "function", + displayTitle: "Run Terminal Command", + wouldLikeTo: "run a terminal command", + readonly: false, + function: { + name: BuiltInToolNames.RunTerminalCommand, + description: + "Run a terminal command in the current directory. The shell is not stateful and will not remember any previous commands.", + parameters: { + type: "object", + required: ["command"], + properties: { + command: { + type: "string", + description: + "The command to run. This will be passed directly into the shell.", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts new file mode 100644 index 000000000..eb8e58c99 --- /dev/null +++ b/core/tools/definitions/searchWeb.ts @@ -0,0 +1,25 @@ +import { Tool } from "../.."; + +import { BuiltInToolNames } from "../builtIn"; + +export const searchWebTool: Tool = { + type: "function", + displayTitle: "Search Web", + wouldLikeTo: 'search the web for "{{{ query }}}"', + readonly: true, + function: { + name: BuiltInToolNames.SearchWeb, + description: + "Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.", + parameters: { + type: "object", + required: ["query"], + properties: { + repo_url: { + type: "string", + description: "The natural language search query", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts new file mode 100644 index 000000000..e54086d05 --- /dev/null +++ b/core/tools/definitions/viewDiff.ts @@ -0,0 +1,18 @@ +import { Tool } from "../.."; + +import { BuiltInToolNames } from "../builtIn"; + +export const viewDiffTool: Tool = { + type: "function", + displayTitle: "View Diff", + wouldLikeTo: "view a diff", + readonly: true, + function: { + name: BuiltInToolNames.ViewDiff, + description: "View the current diff of working changes", + parameters: { + type: "object", + properties: {}, + }, + }, +}; diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts new file mode 100644 index 000000000..9cf3d319d --- /dev/null +++ b/core/tools/definitions/viewRepoMap.ts @@ -0,0 +1,18 @@ +import { Tool } from "../.."; + +import { BuiltInToolNames } from "../builtIn"; + +export const viewRepoMapTool: Tool = { + type: "function", + displayTitle: "View Repo Map", + wouldLikeTo: "view the repository map", + readonly: true, + function: { + name: BuiltInToolNames.ViewRepoMap, + description: "View the repository map", + parameters: { + type: "object", + properties: {}, + }, + }, +}; diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts new file mode 100644 index 000000000..70b7524bd --- /dev/null +++ b/core/tools/definitions/viewSubdirectory.ts @@ -0,0 +1,24 @@ +import { Tool } from "../.."; +import { BuiltInToolNames } from "../builtIn"; + +export const viewSubdirectoryTool: Tool = { + type: "function", + displayTitle: "View Subdirectory", + wouldLikeTo: 'view the contents of "{{{ directory_path }}}"', + readonly: true, + function: { + name: BuiltInToolNames.ViewSubdirectory, + description: "View the contents of a subdirectory", + parameters: { + type: "object", + required: ["directory_path"], + properties: { + directory_path: { + type: "string", + description: + "The path of the subdirectory to view, relative to the root of the workspace", + }, + }, + }, + }, +}; diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts new file mode 100644 index 000000000..0be187b19 --- /dev/null +++ b/core/tools/implementations/createNewFile.ts @@ -0,0 +1,17 @@ +import { getPathModuleForIde } from "../../util/pathModule"; + +import { ToolImpl } from "."; + +export const createNewFileImpl: ToolImpl = async (args, extras) => { + const pathSep = await extras.ide.pathSep(); + let filepath = args.filepath; + if (!args.filepath.startsWith(pathSep)) { + const pathModule = await getPathModuleForIde(extras.ide); + const workspaceDirs = await extras.ide.getWorkspaceDirs(); + const cwd = workspaceDirs[0]; + filepath = pathModule.join(cwd, filepath); + } + await extras.ide.writeFile(filepath, args.contents); + await extras.ide.openFile(filepath); + return []; +}; diff --git a/core/tools/implementations/exactSearch.ts b/core/tools/implementations/exactSearch.ts new file mode 100644 index 000000000..ae8f6fd02 --- /dev/null +++ b/core/tools/implementations/exactSearch.ts @@ -0,0 +1,12 @@ +import { ToolImpl } from "."; + +export const exactSearchImpl: ToolImpl = async (args, extras) => { + const content = await extras.ide.getSearchResults(args.query); + return [ + { + name: "Search results", + description: "Results from exact search", + content, + }, + ]; +}; diff --git a/core/tools/implementations/index.ts b/core/tools/implementations/index.ts new file mode 100644 index 000000000..c0ef15be9 --- /dev/null +++ b/core/tools/implementations/index.ts @@ -0,0 +1,6 @@ +import { ContextItem, ToolExtras } from "../.."; + +export type ToolImpl = ( + parameters: any, + extras: ToolExtras, +) => Promise; diff --git a/core/tools/implementations/readCurrentlyOpenFile.ts b/core/tools/implementations/readCurrentlyOpenFile.ts new file mode 100644 index 000000000..7fff3b621 --- /dev/null +++ b/core/tools/implementations/readCurrentlyOpenFile.ts @@ -0,0 +1,20 @@ +import { ToolImpl } from "."; +import { getBasename } from "../../util"; + +export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => { + const result = await extras.ide.getCurrentFile(); + + if (!result) { + return []; + } + + const basename = getBasename(result.path); + + return [ + { + name: "Current file", + description: basename, + content: `\`\`\`${basename}\n${result.contents}\n\`\`\``, + }, + ]; +}; diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts new file mode 100644 index 000000000..032db3dce --- /dev/null +++ b/core/tools/implementations/readFile.ts @@ -0,0 +1,14 @@ +import { getBasename } from "../../util"; + +import { ToolImpl } from "."; + +export const readFileImpl: ToolImpl = async (args, extras) => { + const content = await extras.ide.readFile(args.filepath); + return [ + { + name: getBasename(args.filepath), + description: args.filepath, + content, + }, + ]; +}; diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts new file mode 100644 index 000000000..ddc8575c4 --- /dev/null +++ b/core/tools/implementations/runTerminalCommand.ts @@ -0,0 +1,40 @@ +import { ToolImpl } from "."; +const util = require("node:util"); +const asyncExec = util.promisify(require("node:child_process").exec); + +export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { + const ideInfo = await extras.ide.getIdeInfo(); + + if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { + try { + const output = await asyncExec(args.command, { + cwd: (await extras.ide.getWorkspaceDirs())[0], + }); + return [ + { + name: "Terminal", + description: "Terminal command output", + content: output.stdout ?? "", + }, + ]; + } catch (error: any) { + return [ + { + name: "Terminal", + description: "Terminal command output", + content: error.stderr ?? error.toString(), + }, + ]; + } + } + + await extras.ide.runCommand(args.command); + return [ + { + name: "Terminal", + description: "Terminal command output", + content: + "[Terminal output not available. This is only available in local development environments and not in SSH environments for example.]", + }, + ]; +}; diff --git a/core/tools/implementations/searchWeb.ts b/core/tools/implementations/searchWeb.ts new file mode 100644 index 000000000..a01212659 --- /dev/null +++ b/core/tools/implementations/searchWeb.ts @@ -0,0 +1,8 @@ +import { fetchSearchResults } from "../../context/providers/WebContextProvider"; + +import { ToolImpl } from "."; + +export const searchWebImpl: ToolImpl = async (args, extras) => { + const webResults = await fetchSearchResults(args.query, 5, extras.fetch); + return webResults; +}; diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts new file mode 100644 index 000000000..11003b61a --- /dev/null +++ b/core/tools/implementations/viewDiff.ts @@ -0,0 +1,12 @@ +import { ToolImpl } from "."; + +export const viewDiffImpl: ToolImpl = async (args, extras) => { + const diff = await extras.ide.getDiff(true); + return [ + { + name: "Diff", + description: "The current git diff", + content: diff.join("\n"), + }, + ]; +}; diff --git a/core/tools/implementations/viewRepoMap.ts b/core/tools/implementations/viewRepoMap.ts new file mode 100644 index 000000000..56c265416 --- /dev/null +++ b/core/tools/implementations/viewRepoMap.ts @@ -0,0 +1,14 @@ +import generateRepoMap from "../../util/generateRepoMap"; + +import { ToolImpl } from "."; + +export const viewRepoMapImpl: ToolImpl = async (args, extras) => { + const repoMap = await generateRepoMap(extras.llm, extras.ide, {}); + return [ + { + name: "Repo map", + description: "Overview of the repository structure", + content: repoMap, + }, + ]; +}; diff --git a/core/tools/implementations/viewSubdirectory.ts b/core/tools/implementations/viewSubdirectory.ts new file mode 100644 index 000000000..a8204ca6a --- /dev/null +++ b/core/tools/implementations/viewSubdirectory.ts @@ -0,0 +1,27 @@ +import generateRepoMap from "../../util/generateRepoMap"; +import { resolveRelativePathInWorkspace } from "../../util/ideUtils"; + +import { ToolImpl } from "."; + +export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { + const { directory_path } = args; + const absolutePath = await resolveRelativePathInWorkspace( + directory_path, + extras.ide, + ); + + if (!absolutePath) { + throw new Error(`Directory path "${directory_path}" does not exist.`); + } + + const repoMap = await generateRepoMap(extras.llm, extras.ide, { + dirs: [absolutePath], + }); + return [ + { + name: "Repo map", + description: `Map of ${directory_path}`, + content: repoMap, + }, + ]; +}; diff --git a/core/tools/index.ts b/core/tools/index.ts new file mode 100644 index 000000000..c27860a6f --- /dev/null +++ b/core/tools/index.ts @@ -0,0 +1,21 @@ +import { createNewFileTool } from "./definitions/createNewFile"; +import { exactSearchTool } from "./definitions/exactSearch"; +import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile"; +import { readFileTool } from "./definitions/readFile"; +import { runTerminalCommandTool } from "./definitions/runTerminalCommand"; +import { searchWebTool } from "./definitions/searchWeb"; +import { viewDiffTool } from "./definitions/viewDiff"; +import { viewRepoMapTool } from "./definitions/viewRepoMap"; +import { viewSubdirectoryTool } from "./definitions/viewSubdirectory"; + +export const allTools = [ + readFileTool, + createNewFileTool, + runTerminalCommandTool, + viewSubdirectoryTool, + viewRepoMapTool, + exactSearchTool, + searchWebTool, + viewDiffTool, + readCurrentlyOpenFileTool, +]; diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index b8ca609a2..b52fd7696 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -1,5 +1,4 @@ import { ILLM, LLMFullCompletionOptions } from ".."; -import { stripImages } from "../llm/images"; import { removeQuotesAndEscapes } from "."; @@ -35,7 +34,6 @@ export class ChatDescriber { } // Clean up and distill the message we want to send to the LLM - message = stripImages(message); message = removeCodeBlocksAndTrim(message); if (!message) { diff --git a/core/util/history.ts b/core/util/history.ts index e68556762..053c23455 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -96,7 +96,6 @@ class HistoryManager { title: session.title, workspaceDirectory: session.workspaceDirectory, history: session.history, - checkpoints: session.checkpoints, }; fs.writeFileSync( getSessionFilePath(session.sessionId), diff --git a/core/util/incrementalParseJson.ts b/core/util/incrementalParseJson.ts new file mode 100644 index 000000000..21385ad6a --- /dev/null +++ b/core/util/incrementalParseJson.ts @@ -0,0 +1,13 @@ +import { parse } from "partial-json"; + +export function incrementalParseJson(raw: string): [boolean, any] { + try { + return [true, JSON.parse(raw)]; + } catch (e) { + try { + return [false, parse(raw)]; + } catch (e2) { + return [false, {}]; + } + } +} diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts new file mode 100644 index 000000000..b42bb082a --- /dev/null +++ b/core/util/messageContent.ts @@ -0,0 +1,45 @@ +import { + ChatMessage, + ContextItem, + MessageContent, + MessagePart, +} from "../index.js"; + +export function stripImages(messageContent: MessageContent): string { + if (typeof messageContent === "string") { + return messageContent; + } + + return messageContent + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); +} + +export function renderChatMessage(message: ChatMessage): string { + switch (message.role) { + case "user": + case "assistant": + case "system": + return stripImages(message.content); + case "tool": + return message.content; + } +} + +export function renderContextItems(contextItems: ContextItem[]): string { + return contextItems.map((item) => item.content).join("\n\n"); +} + +export function normalizeToMessageParts(message: ChatMessage): MessagePart[] { + switch (message.role) { + case "user": + case "assistant": + case "system": + return Array.isArray(message.content) + ? message.content + : [{ type: "text", text: message.content }]; + case "tool": + return [{ type: "text", text: message.content }]; + } +} diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 24e94781c..a7a11b503 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -4,11 +4,13 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disable: false, useFileSuffix: true, maxPromptTokens: 1024, - prefixPercentage: 0.85, - maxSuffixPercentage: 0.25, + prefixPercentage: 0.3, + maxSuffixPercentage: 0.2, debounceDelay: 350, multilineCompletions: "auto", + // @deprecated TO BE REMOVED slidingWindowPrefixPercentage: 0.75, + // @deprecated TO BE REMOVED slidingWindowSize: 500, useCache: true, onlyMyCode: true, diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 615f77b82..dea92ec85 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -2,10 +2,28 @@ import os from "node:os"; import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; import { IdeInfo } from "../index.js"; +import type { PostHog as PostHogType } from "posthog-node"; + +export enum PosthogFeatureFlag { + AutocompleteTemperature = "autocomplete-temperature", +} + +export const EXPERIMENTS: { + [key in PosthogFeatureFlag]: { + [key: string]: { value: number }; + }; +} = { + [PosthogFeatureFlag.AutocompleteTemperature]: { + control: { value: 0.01 }, + "0_33": { value: 0.33 }, + "0_66": { value: 0.66 }, + "0_99": { value: 0.99 }, + }, +}; export class Telemetry { // Set to undefined whenever telemetry is disabled - static client: any = undefined; + static client: PostHogType | undefined = undefined; static uniqueId = "NOT_UNIQUE"; static os: string | undefined = undefined; static ideInfo: IdeInfo | undefined = undefined; @@ -28,6 +46,7 @@ export class Telemetry { distinctId: Telemetry.uniqueId, event, properties: augmentedProperties, + sendFeatureFlags: true, }; // In cases where an extremely early fatal error occurs, we may not have initialized yet @@ -55,7 +74,7 @@ export class Telemetry { Telemetry.client?.shutdown(); } - static async getTelemetryClient() { + static async getTelemetryClient(): Promise { try { const { PostHog } = await import("posthog-node"); return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", { @@ -77,4 +96,21 @@ export class Telemetry { Telemetry.client = await Telemetry.getTelemetryClient(); } } + + static async getFeatureFlag(flag: PosthogFeatureFlag) { + return Telemetry.client?.getFeatureFlag(flag, Telemetry.uniqueId); + } + + static async getValueForFeatureFlag(flag: PosthogFeatureFlag) { + try { + const userGroup = await Telemetry.getFeatureFlag(flag); + if (typeof userGroup === "string") { + return EXPERIMENTS[flag][userGroup].value; + } + + return undefined; + } catch { + return undefined; + } + } } diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 22a59e85c..8029c0609 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -290,7 +290,12 @@ export async function getSymbolsForManyFiles( const filesAndSymbols = await Promise.all( uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => { const contents = await ide.readFile(uri); - const symbols = await getSymbolsForFile(uri, contents); + let symbols = undefined; + try { + symbols = await getSymbolsForFile(uri, contents); + } catch (e) { + console.error(`Failed to get symbols for ${uri}:`, e); + } return [uri, symbols ?? []]; }), ); diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index a423ff4dc..2c7708cac 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -495,6 +495,26 @@ Reference the architecture and platform of your current operating system. } ``` +### Model Context Protocol + +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: + +```json +{ + "experimental": { + "modelContextProtocolServer": { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } + } + } +} +``` + +You'll then be able to type "@" and see "MCP" in the context providers dropdown. + ### `@HTTP` The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems. diff --git a/docs/docs/customize/model-providers/top-level/function-network.md b/docs/docs/customize/model-providers/top-level/function-network.md new file mode 100644 index 000000000..c48e899d8 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/function-network.md @@ -0,0 +1,67 @@ +--- +title: Function Network +slug: ../function-network +--- +# Function Network + +> Private, Affordable User-Owned AI + +:::info + +To get an API key, login to the Function Network Developer Platform. If you don't have an account, you can create one [here](https://www.function.network/join-waitlist). + +::: + +## Chat model + +Function Network supports a number of models for chat. We recommend using LLama 3.1 70b or Qwen2.5-Coder-32B-Instruct. + +```json title="config.json" +{ + "models": [ + { + "title": "Llama 3.1 70b", + "provider": "function-network", + "model": "meta/llama-3.1-70b-instruct", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +[Click here](https://docs.function.network/models-supported/chat-and-code-completion) to see a list of chat model providers. + +## Autocomplete model + +Function Network supports a number of models for autocomplete. We recommend using Llama 3.1 8b or Qwen2.5-Coder-1.5B. + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Deepseek Coder 6.7b", + "provider": "function-network", + "model": "thebloke/deepseek-coder-6.7b-base-awq", + "apiKey": "YOUR_API_KEY" + } +} +``` + +## Embeddings model + +Function Network supports a number of models for embeddings. We recommend using baai/bge-base-en-v1.5. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "function-network", + "model": "baai/bge-base-en-v1.5", + "apiKey": "YOUR_API_KEY" + } +} +``` + +[Click here](https://docs.function.network/models-supported/embeddings) to see a list of embeddings model providers. + +## Reranking model + +Function Network currently does not offer any reranking models. diff --git a/docs/docs/customize/slash-commands.md b/docs/docs/customize/slash-commands.md index 96988e858..20283ae89 100644 --- a/docs/docs/customize/slash-commands.md +++ b/docs/docs/customize/slash-commands.md @@ -106,3 +106,21 @@ The onboard slash command helps to familiarize yourself with a new project by an ] } ``` + +### Model Context Protocol + +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports MCP "prompts" by creating slash commands. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: + +```json +{ + "experimental": { + "modelContextProtocolServer": { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } + } + } +} +``` diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index c48c8e58b..6dccf7f08 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -435,8 +435,10 @@ class IdeProtocolClient( "getRepoName" -> { // Get the current repository name val dir = (data as Map)["dir"] as String + val directory = File(dir) + val targetDir = if (directory.isFile) directory.parentFile else directory val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url") - builder.directory(File(dir)) + builder.directory(targetDir) var output = "NONE" try { val process = builder.start() @@ -453,9 +455,10 @@ class IdeProtocolClient( "getDiff" -> { val workspaceDirs = workspaceDirectories() - val output = StringBuilder() + val diffs = mutableListOf() for (workspaceDir in workspaceDirs) { + val output = StringBuilder() val builder = ProcessBuilder("git", "diff") builder.directory(File(workspaceDir)) val process = builder.start() @@ -469,9 +472,10 @@ class IdeProtocolClient( } process.waitFor() + diffs.add(output.toString()) } - respond(output.toString()) + respond(diffs) } "getProblems" -> { @@ -1091,4 +1095,4 @@ class IdeProtocolClient( return matchingModel } -} \ No newline at end of file +} 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..7651ecc8f 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 @@ -66,6 +66,7 @@ class ContinueBrowser(val project: Project, url: String) { "config/listProfiles", "profiles/switch", "didChangeSelectedProfile", + "context/getSymbolsForFiles", ) private fun registerAppSchemeHandler() { diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index d33482747..8f6a1cd01 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -5,6 +5,11 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html), and is generated by [Changie](https://github.com/miniscruff/changie). +Pre-release Changes +### Added +* Tool use +* Support for Model Context Protocol + ## 0.8.59 - 2024-11-25 ### Fixed * Hotfix for Ollama onboarding diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 682925838..86a9d54a2 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -207,7 +207,8 @@ "xAI", "kindo", "moonshot", - "siliconflow" + "siliconflow", + "function-network" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -246,7 +247,8 @@ "### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)", "### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)", "### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)", - "### SiliconFlow\nTo get started with SiliconFlow, obtain your API key from [SiliconCloud](https://cloud.siliconflow.cn/account/ak). SiliconCloud provides cost-effective GenAI services based on excellent open source basic models.\n> [Models](https://siliconflow.cn/zh-cn/models)" + "### SiliconFlow\nTo get started with SiliconFlow, obtain your API key from [SiliconCloud](https://cloud.siliconflow.cn/account/ak). SiliconCloud provides cost-effective GenAI services based on excellent open source basic models.\n> [Models](https://siliconflow.cn/zh-cn/models)", + "### Function Network offers private, affordable user-owned AI\nTo get started with Function Network, obtain your API key from [Function Network](https://www.function.network/join-waitlist). Function Network provides a variety of models for chat, completion, and embeddings." ], "type": "string" }, @@ -2524,7 +2526,8 @@ "mistral", "watsonx", "lmstudio", - "siliconflow" + "siliconflow", + "function-network" ] }, "model": { @@ -2572,7 +2575,13 @@ "if": { "properties": { "provider": { - "enum": ["cohere", "voyage", "nvidia", "gemini", "siliconflow"] + "enum": [ + "cohere", + "voyage", + "nvidia", + "gemini", + "siliconflow" + ] } }, "required": ["provider"] @@ -3039,6 +3048,68 @@ "type": "boolean", "description": "Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.", "default": false + }, + "useTools": { + "type": "boolean", + "description": "Allow tool use. Currently only supported with Claude 3.5 Sonnet", + "default": true + }, + "modelContextProtocolServer": { + "type": "object", + "properties": { + "transport": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["stdio"] + }, + "command": { + "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["type", "command", "args"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["websocket"] + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": ["type", "url"] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["sse"] + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": ["type", "url"] + } + ] + } + }, + "required": ["transport"] } } } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 49cc1fb6c..9ac0c6f53 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.237", + "version": "0.9.242", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.237", + "version": "0.9.242", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -99,6 +99,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -132,6 +133,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index f3bb0896f..67d4e5020 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.237", + "version": "0.9.242", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -57,6 +57,12 @@ ], "main": "./out/extension.js", "contributes": { + "authentication": [ + { + "id": "continue", + "label": "Continue" + } + ], "languages": [ { "filenames": [ diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index cc0d8c343..5138ba490 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -531,8 +531,14 @@ class VsCodeIde implements IDE { "bin", "rg", ), - ["-i", "-C", "2", "--", `${query}`, "."], //no regex - //["-i", "-C", "2", "-e", `${query}`, "."], //use regex + [ + "-i", // Case-insensitive search + "-C", + "2", // Show 2 lines of context + "-e", + query, // Pattern to search for + ".", // Directory to search in + ], { cwd: dir }, ); let output = ""; @@ -546,6 +552,9 @@ class VsCodeIde implements IDE { p.on("close", (code) => { if (code === 0) { resolve(output); + } else if (code === 1) { + // No matches + resolve("No matches found"); } else { reject(new Error(`Process exited with code ${code}`)); } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index ffe69a2c4..5d6faef3f 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -19,8 +19,8 @@ import { stopStatusBarLoading, } from "./statusBar"; -import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import type { IDE } from "core"; +import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; interface VsCodeCompletionInput { document: vscode.TextDocument; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 96426b88a..c6acc5e14 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -581,7 +581,8 @@ const getCommandsMap: ( }, "continue.exitEditMode": async () => { captureCommandTelemetry("exitEditMode"); - await sidebar.webviewProtocol?.request("exitEditMode", undefined); + editDecorationManager.clear(); + void sidebar.webviewProtocol?.request("exitEditMode", undefined); }, // "continue.quickEdit": async (args: QuickEditShowParams) => { // let linesOfCode = undefined; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 8a70038a3..5133788ce 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -4,7 +4,6 @@ import * as path from "node:path"; import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; -import { stripImages } from "core/llm/images"; import { FromCoreProtocol, FromWebviewProtocol, @@ -21,6 +20,7 @@ import { getBasename } from "core/util"; import { InProcessMessenger, Message } from "core/util/messenger"; import * as vscode from "vscode"; +import { stripImages } from "core/util/messageContent"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -400,8 +400,16 @@ export class VsCodeMessenger { vscode.commands.executeCommand("continue.rejectDiff", filepath); } }); - this.onWebview("edit/escape", async (msg) => { - this.editDecorationManager.clear(); + this.onWebview("edit/exit", async (msg) => { + if (msg.data.shouldFocusEditor) { + const activeEditor = vscode.window.activeTextEditor; + + if (activeEditor) { + vscode.window.showTextDocument(activeEditor.document); + } + } + + editDecorationManager.clear(); }); /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/ diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 4e9eb3054..28f3f6032 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -169,7 +169,11 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { } get redirectUri() { - if (env.uriScheme === "vscode-insiders" || env.uriScheme === "vscode") { + if ( + env.uriScheme === "vscode-insiders" || + env.uriScheme === "vscode" || + env.uriScheme === "code-oss" + ) { // We redirect to a page that says "you can close this page", and that page finishes the redirect const url = new URL(controlPlaneEnv.APP_URL); url.pathname = `/auth/${env.uriScheme}-redirect`; diff --git a/gui/package-lock.json b/gui/package-lock.json index 52a14384e..7546cc341 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -10,7 +10,7 @@ "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@monaco-editor/react": "^4.6.0", - "@reduxjs/toolkit": "^1.9.3", + "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", "@tiptap/extension-document": "^2.3.2", "@tiptap/extension-dropcursor": "^2.1.16", @@ -30,6 +30,7 @@ "downshift": "^7.6.0", "lodash": "^4.17.21", "minisearch": "^7.0.2", + "mustache": "^4.2.0", "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", @@ -47,6 +48,7 @@ "react-tooltip": "^5.18.0", "redux-persist": "^6.0.0", "redux-persist-transform-filter": "^0.0.22", + "redux-thunk": "^3.1.0", "rehype-highlight": "^7.0.0", "rehype-katex": "^7.0.0", "rehype-wrap-all": "^1.1.0", @@ -70,6 +72,7 @@ "@testing-library/react": "^16.0.1", "@testing-library/user-event": "^14.5.2", "@types/lodash": "^4.17.6", + "@types/mustache": "^4.2.5", "@types/node": "^20.5.6", "@types/node-fetch": "^2.6.4", "@types/react": "^18.3.11", @@ -81,7 +84,7 @@ "@vitest/coverage-v8": "^2.1.3", "@vitest/ui": "^2.1.3", "autoprefixer": "^10.4.13", - "eslint": "^9.15.0", + "eslint": "^8", "eslint-plugin-react": "^7.37.2", "eslint-plugin-strict-null-checks": "^0.1.3", "jsdom": "^25.0.1", @@ -106,6 +109,7 @@ "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", "@continuedev/llm-info": "^1.0.2", + "@modelcontextprotocol/sdk": "^1.0.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -139,6 +143,7 @@ "onnxruntime-node": "1.14.0", "openai": "^4.20.1", "p-limit": "^6.1.0", + "partial-json": "^0.1.7", "pg": "^8.11.3", "posthog-node": "^3.6.3", "puppeteer": "^22.4.0", @@ -968,61 +973,16 @@ "node": "^12.0.0 || ^14.0.0 || >=16.0.0" } }, - "node_modules/@eslint/config-array": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.19.0.tgz", - "integrity": "sha512-zdHg2FPIFNKPdcHWtiNT+jEFCHYVplAXRDlQDyqy0zGx/q2parwh7brGJSiTxRk/TSMkbM//zt/f5CHgyTyaSQ==", - "dev": true, - "dependencies": { - "@eslint/object-schema": "^2.1.4", - "debug": "^4.3.1", - "minimatch": "^3.1.2" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/config-array/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/@eslint/config-array/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/@eslint/core": { - "version": "0.9.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.9.0.tgz", - "integrity": "sha512-7ATR9F0e4W85D/0w7cU0SNj7qkAexMG+bAHEZOjo9akvGuhHE2m7umzWzfnpa0XAg5Kxc1BWmtPMV67jJ+9VUg==", - "dev": true, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, "node_modules/@eslint/eslintrc": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.2.0.tgz", - "integrity": "sha512-grOjVNN8P3hjJn/eIETF1wwd12DdnwFDoyceUJLYYdkpbwq3nLi+4fqrTAONx7XDALqlL220wC/RHSC/QTI/0w==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", + "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", "dev": true, "dependencies": { "ajv": "^6.12.4", "debug": "^4.3.2", - "espree": "^10.0.1", - "globals": "^14.0.0", + "espree": "^9.6.0", + "globals": "^13.19.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.1.0", @@ -1030,7 +990,7 @@ "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -1063,12 +1023,15 @@ } }, "node_modules/@eslint/eslintrc/node_modules/globals": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", - "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", "dev": true, + "dependencies": { + "type-fest": "^0.20.2" + }, "engines": { - "node": ">=18" + "node": ">=8" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -1093,33 +1056,12 @@ } }, "node_modules/@eslint/js": { - "version": "9.15.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.15.0.tgz", - "integrity": "sha512-tMTqrY+EzbXmKJR5ToI8lxu7jaN5EdmrBFJpQk5JmSlyLsx6o4t27r883K5xsLuCYCpfKBCGswMSWXsM+jB7lg==", + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", + "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", "dev": true, "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/object-schema": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.4.tgz", - "integrity": "sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==", - "dev": true, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, - "node_modules/@eslint/plugin-kit": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.2.3.tgz", - "integrity": "sha512-2b/g5hRmpbb1o4GnTZax9N9m0FXzz9OV42ZzI4rDDMDuHUqigAiQCEWChBWCY4ztAGVRjoWT19v0yMmc5/L5kA==", - "dev": true, - "dependencies": { - "levn": "^0.4.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/@floating-ui/core": { @@ -1168,48 +1110,12 @@ "react": ">= 16" } }, - "node_modules/@humanfs/core": { - "version": "0.19.1", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", - "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", - "dev": true, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/node": { - "version": "0.16.6", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.6.tgz", - "integrity": "sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==", - "dev": true, - "dependencies": { - "@humanfs/core": "^0.19.1", - "@humanwhocodes/retry": "^0.3.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/node/node_modules/@humanwhocodes/retry": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.1.tgz", - "integrity": "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==", - "dev": true, - "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, "node_modules/@humanwhocodes/config-array": { "version": "0.13.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", "deprecated": "Use @eslint/config-array instead", "dev": true, - "peer": true, "dependencies": { "@humanwhocodes/object-schema": "^2.0.3", "debug": "^4.3.1", @@ -1224,7 +1130,6 @@ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, - "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -1235,7 +1140,6 @@ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, - "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -1261,21 +1165,7 @@ "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", "deprecated": "Use @eslint/object-schema instead", - "dev": true, - "peer": true - }, - "node_modules/@humanwhocodes/retry": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.1.tgz", - "integrity": "sha512-c7hNEllBlenFTHBky65mhq8WD2kbN9Q6gk0bTk8lSBvc554jpXSkST1iePudpt7+A/AQvuHs9EMqjHDXMY1lrA==", - "dev": true, - "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } + "dev": true }, "node_modules/@isaacs/cliui": { "version": "8.0.2", @@ -1820,18 +1710,18 @@ } }, "node_modules/@reduxjs/toolkit": { - "version": "1.9.7", - "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-1.9.7.tgz", - "integrity": "sha512-t7v8ZPxhhKgOKtU+uyJT13lu4vL7az5aFi4IdoDs/eS548edn2M8Ik9h8fxgvMjGoAUVFSt6ZC1P5cWmQ014QQ==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.3.0.tgz", + "integrity": "sha512-WC7Yd6cNGfHx8zf+iu+Q1UPTfEcXhQ+ATi7CV1hlrSAaQBdlPzg7Ww/wJHNQem7qG9rxmWoFCDCPubSvFObGzA==", "dependencies": { - "immer": "^9.0.21", - "redux": "^4.2.1", - "redux-thunk": "^2.4.2", - "reselect": "^4.1.8" + "immer": "^10.0.3", + "redux": "^5.0.1", + "redux-thunk": "^3.1.0", + "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18", - "react-redux": "^7.2.1 || ^8.0.2" + "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "peerDependenciesMeta": { "react": { @@ -1842,11 +1732,6 @@ } } }, - "node_modules/@reduxjs/toolkit/node_modules/reselect": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/reselect/-/reselect-4.1.8.tgz", - "integrity": "sha512-ab9EmR80F/zQTMNeneUr4cv+jSwPJgIlvEmVwLerwrWVbpLlBuls9XHzIeTFy4cegU2NHBp3va0LKOzU5qFEYQ==" - }, "node_modules/@remirror/core-constants": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/@remirror/core-constants/-/core-constants-3.0.0.tgz", @@ -3103,6 +2988,12 @@ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.34.tgz", "integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==" }, + "node_modules/@types/mustache": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@types/mustache/-/mustache-4.2.5.tgz", + "integrity": "sha512-PLwiVvTBg59tGFL/8VpcGvqOu3L4OuveNvPi0EYbWchRdEVP++yRUXJPFl+CApKEq13017/4Nf7aQ5lTtHUNsA==", + "dev": true + }, "node_modules/@types/node": { "version": "20.16.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.16.5.tgz", @@ -5138,62 +5029,59 @@ } }, "node_modules/eslint": { - "version": "9.15.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.15.0.tgz", - "integrity": "sha512-7CrWySmIibCgT1Os28lUU6upBshZ+GxybLOrmRzi08kS8MBuO8QA7pXEgYgY5W8vK3e74xv0lpjo9DbaGU9Rkw==", + "version": "8.57.1", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", + "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", + "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.12.1", - "@eslint/config-array": "^0.19.0", - "@eslint/core": "^0.9.0", - "@eslint/eslintrc": "^3.2.0", - "@eslint/js": "9.15.0", - "@eslint/plugin-kit": "^0.2.3", - "@humanfs/node": "^0.16.6", + "@eslint-community/regexpp": "^4.6.1", + "@eslint/eslintrc": "^2.1.4", + "@eslint/js": "8.57.1", + "@humanwhocodes/config-array": "^0.13.0", "@humanwhocodes/module-importer": "^1.0.1", - "@humanwhocodes/retry": "^0.4.1", - "@types/estree": "^1.0.6", - "@types/json-schema": "^7.0.15", + "@nodelib/fs.walk": "^1.2.8", + "@ungap/structured-clone": "^1.2.0", "ajv": "^6.12.4", "chalk": "^4.0.0", - "cross-spawn": "^7.0.5", + "cross-spawn": "^7.0.2", "debug": "^4.3.2", + "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.2.0", - "eslint-visitor-keys": "^4.2.0", - "espree": "^10.3.0", - "esquery": "^1.5.0", + "eslint-scope": "^7.2.2", + "eslint-visitor-keys": "^3.4.3", + "espree": "^9.6.1", + "esquery": "^1.4.2", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^8.0.0", + "file-entry-cache": "^6.0.1", "find-up": "^5.0.0", "glob-parent": "^6.0.2", + "globals": "^13.19.0", + "graphemer": "^1.4.0", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", + "is-path-inside": "^3.0.3", + "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.4.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", - "optionator": "^0.9.3" + "optionator": "^0.9.3", + "strip-ansi": "^6.0.1", + "text-table": "^0.2.0" }, "bin": { "eslint": "bin/eslint.js" }, "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "jiti": "*" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - } + "url": "https://opencollective.com/eslint" } }, "node_modules/eslint-plugin-react": { @@ -5291,40 +5179,6 @@ "typescript": ">=3.9.4" } }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", - "dev": true, - "peer": true, - "dependencies": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/@eslint/js": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", - "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", - "dev": true, - "peer": true, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, "node_modules/eslint-plugin-strict-null-checks/node_modules/@typescript-eslint/eslint-plugin": { "version": "5.62.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz", @@ -5532,172 +5386,6 @@ "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "dev": true, - "peer": true, - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "peer": true, - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, - "peer": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "peer": true, - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "peer": true, - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "peer": true - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "peer": true, - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "peer": true, - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/eslint": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", - "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", - "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", - "dev": true, - "peer": true, - "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.1", - "@humanwhocodes/config-array": "^0.13.0", - "@humanwhocodes/module-importer": "^1.0.1", - "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", - "ajv": "^6.12.4", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.3.2", - "doctrine": "^3.0.0", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "strip-ansi": "^6.0.1", - "text-table": "^0.2.0" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, "node_modules/eslint-plugin-strict-null-checks/node_modules/eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", @@ -5732,12 +5420,11 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/eslint/node_modules/eslint-scope": { + "node_modules/eslint-scope": { "version": "7.2.2", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", "dev": true, - "peer": true, "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" @@ -5749,189 +5436,6 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", - "dev": true, - "peer": true, - "dependencies": { - "acorn": "^8.9.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", - "dev": true, - "peer": true, - "dependencies": { - "flat-cache": "^3.0.4" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", - "dev": true, - "peer": true, - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "peer": true, - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", - "dev": true, - "peer": true, - "dependencies": { - "type-fest": "^0.20.2" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "peer": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "peer": true - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "peer": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "peer": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "peer": true, - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "peer": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "peer": true, - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/eslint-plugin-strict-null-checks/node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "peer": true, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/eslint-scope": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.2.0.tgz", - "integrity": "sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A==", - "dev": true, - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, "node_modules/eslint-visitor-keys": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", @@ -6033,6 +5537,30 @@ "node": ">= 8" } }, + "node_modules/eslint/node_modules/doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/eslint/node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -6045,6 +5573,21 @@ "node": ">=10.13.0" } }, + "node_modules/eslint/node_modules/globals": { + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "dev": true, + "dependencies": { + "type-fest": "^0.20.2" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/eslint/node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -6130,17 +5673,29 @@ } }, "node_modules/espree": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.3.0.tgz", - "integrity": "sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg==", + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", + "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", "dev": true, "dependencies": { - "acorn": "^8.14.0", + "acorn": "^8.9.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^4.2.0" + "eslint-visitor-keys": "^3.4.1" }, "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -6331,15 +5886,15 @@ "integrity": "sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==" }, "node_modules/file-entry-cache": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", - "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", + "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", "dev": true, "dependencies": { - "flat-cache": "^4.0.0" + "flat-cache": "^3.0.4" }, "engines": { - "node": ">=16.0.0" + "node": "^10.12.0 || >=12.0.0" } }, "node_modules/file-type": { @@ -6432,16 +5987,17 @@ } }, "node_modules/flat-cache": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", - "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", + "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", "dev": true, "dependencies": { "flatted": "^3.2.9", - "keyv": "^4.5.4" + "keyv": "^4.5.3", + "rimraf": "^3.0.2" }, "engines": { - "node": ">=16" + "node": "^10.12.0 || >=12.0.0" } }, "node_modules/flatted": { @@ -6598,8 +6154,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "peer": true + "dev": true }, "node_modules/fsevents": { "version": "2.3.3", @@ -7532,9 +7087,9 @@ } }, "node_modules/immer": { - "version": "9.0.21", - "resolved": "https://registry.npmjs.org/immer/-/immer-9.0.21.tgz", - "integrity": "sha512-bc4NBHqOqSfRW7POMkHd51LvClaeMXpm8dx0e8oE2GORbq5aRK7Bxl4FyzVLdGtLmvLKL7BTDBG5ACQm4HWjTA==", + "version": "10.1.1", + "resolved": "https://registry.npmjs.org/immer/-/immer-10.1.1.tgz", + "integrity": "sha512-s2MPrmjovJcoMaHtx6K11Ra7oD05NT97w1IC5zpMkT6Atjr7H8LjaDd81iIxUYpMKSRRNMJE703M1Fhr/TctHw==", "funding": { "type": "opencollective", "url": "https://opencollective.com/immer" @@ -7580,7 +7135,6 @@ "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", "dev": true, - "peer": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -7913,7 +7467,6 @@ "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", "dev": true, - "peer": true, "engines": { "node": ">=8" } @@ -9583,6 +9136,14 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "bin": { + "mustache": "bin/mustache" + } + }, "node_modules/mz": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", @@ -9992,7 +9553,6 @@ "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", "dev": true, - "peer": true, "engines": { "node": ">=0.10.0" } @@ -11219,12 +10779,9 @@ } }, "node_modules/redux": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz", - "integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==", - "dependencies": { - "@babel/runtime": "^7.9.2" - } + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", + "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==" }, "node_modules/redux-persist": { "version": "6.0.0", @@ -11247,11 +10804,11 @@ } }, "node_modules/redux-thunk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-2.4.2.tgz", - "integrity": "sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz", + "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==", "peerDependencies": { - "redux": "^4" + "redux": "^5.0.0" } }, "node_modules/reflect.getprototypeof": { @@ -11686,7 +11243,6 @@ "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, - "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -11702,7 +11258,6 @@ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", "dev": true, - "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -11714,7 +11269,6 @@ "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, - "peer": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -11735,7 +11289,6 @@ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, - "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -12578,8 +12131,7 @@ "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true, - "peer": true + "dev": true }, "node_modules/thenify": { "version": "3.3.1", @@ -12879,7 +12431,6 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true, - "peer": true, "engines": { "node": ">=10" }, diff --git a/gui/package.json b/gui/package.json index e13e00be6..3d8faabed 100644 --- a/gui/package.json +++ b/gui/package.json @@ -18,7 +18,7 @@ "@headlessui/react": "^1.7.17", "@heroicons/react": "^2.0.18", "@monaco-editor/react": "^4.6.0", - "@reduxjs/toolkit": "^1.9.3", + "@reduxjs/toolkit": "^2.3.0", "@tiptap/core": "^2.3.2", "@tiptap/extension-document": "^2.3.2", "@tiptap/extension-dropcursor": "^2.1.16", @@ -38,6 +38,7 @@ "downshift": "^7.6.0", "lodash": "^4.17.21", "minisearch": "^7.0.2", + "mustache": "^4.2.0", "onigasm": "^2.2.5", "posthog-js": "^1.130.1", "prismjs": "^1.29.0", @@ -55,6 +56,7 @@ "react-tooltip": "^5.18.0", "redux-persist": "^6.0.0", "redux-persist-transform-filter": "^0.0.22", + "redux-thunk": "^3.1.0", "rehype-highlight": "^7.0.0", "rehype-katex": "^7.0.0", "rehype-wrap-all": "^1.1.0", @@ -78,6 +80,7 @@ "@testing-library/react": "^16.0.1", "@testing-library/user-event": "^14.5.2", "@types/lodash": "^4.17.6", + "@types/mustache": "^4.2.5", "@types/node": "^20.5.6", "@types/node-fetch": "^2.6.4", "@types/react": "^18.3.11", @@ -89,7 +92,7 @@ "@vitest/coverage-v8": "^2.1.3", "@vitest/ui": "^2.1.3", "autoprefixer": "^10.4.13", - "eslint": "^9.15.0", + "eslint": "^8", "eslint-plugin-react": "^7.37.2", "eslint-plugin-strict-null-checks": "^0.1.3", "jsdom": "^25.0.1", diff --git a/gui/public/logos/function-network.png b/gui/public/logos/function-network.png new file mode 100644 index 000000000..177f22fb6 Binary files /dev/null and b/gui/public/logos/function-network.png differ diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 2e09970be..244d811b5 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -5,14 +5,12 @@ import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; import ConfigErrorPage from "./pages/config-error"; -import Edit from "./pages/edit"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; import MigrationPage from "./pages/migration"; import MonacoPage from "./pages/monaco"; import MorePage from "./pages/More"; -import SettingsPage from "./pages/settings"; import Stats from "./pages/stats"; import { ROUTES } from "./util/navigation"; import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; @@ -31,10 +29,6 @@ const router = createMemoryRouter([ path: "/", element: , }, - { - path: "/edit", - element: , - }, { path: "/history", element: , @@ -43,10 +37,6 @@ const router = createMemoryRouter([ path: "/stats", element: , }, - { - path: "/settings", - element: , - }, { path: "/addModel", element: , diff --git a/gui/src/components/AccountDialog.tsx b/gui/src/components/AccountDialog.tsx index 04937b31d..cd9ef0b55 100644 --- a/gui/src/components/AccountDialog.tsx +++ b/gui/src/components/AccountDialog.tsx @@ -12,9 +12,9 @@ import { } from "."; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useAuth } from "../context/Auth"; -import { setSelectedProfileId } from "../redux/slices/stateSlice"; +import { setSelectedProfileId } from "../redux/slices/sessionSlice"; import { useDispatch } from "react-redux"; -import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice"; +import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { NewSessionButton } from "./mainInput/NewSessionButton"; const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean }>` diff --git a/gui/src/components/ChatScrollAnchor.tsx b/gui/src/components/ChatScrollAnchor.tsx index 40c0f9d19..9b32e7283 100644 --- a/gui/src/components/ChatScrollAnchor.tsx +++ b/gui/src/components/ChatScrollAnchor.tsx @@ -1,5 +1,6 @@ import { useEffect } from "react"; import { useInView } from "react-intersection-observer"; +import { vscBackground } from "."; interface ChatScrollAnchorProps { trackVisibility: boolean; @@ -25,5 +26,13 @@ export function ChatScrollAnchor({ } }, [inView, entry, isAtBottom, trackVisibility]); - return
; + return ( +
+ ); } diff --git a/gui/src/pages/edit/AddFileButton.tsx b/gui/src/components/CodeToEditCard/AddFileButton.tsx similarity index 97% rename from gui/src/pages/edit/AddFileButton.tsx rename to gui/src/components/CodeToEditCard/AddFileButton.tsx index 8e8096eab..91542e8e4 100644 --- a/gui/src/pages/edit/AddFileButton.tsx +++ b/gui/src/components/CodeToEditCard/AddFileButton.tsx @@ -2,8 +2,8 @@ import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useDispatch } from "react-redux"; import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; -import { addCodeToEdit } from "../../redux/slices/editModeState"; import { Listbox } from "@headlessui/react"; +import { addCodeToEdit } from "../../redux/slices/sessionSlice"; export interface AddFileButtonProps { onClick: () => void; diff --git a/gui/src/pages/edit/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx similarity index 94% rename from gui/src/pages/edit/AddFileCombobox.tsx rename to gui/src/components/CodeToEditCard/AddFileCombobox.tsx index e219b01da..b79365fb1 100644 --- a/gui/src/pages/edit/AddFileCombobox.tsx +++ b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx @@ -4,9 +4,8 @@ import { useSubmenuContextProviders, } from "../../context/SubmenuContextProviders"; import { Combobox } from "@headlessui/react"; -import FileIcon from "../../components/FileIcon"; -import { useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; +import FileIcon from "../FileIcon"; +import { useAppSelector } from "../../redux/hooks"; export interface AddFileComboboxProps { onSelect: (filepaths: string[]) => void; @@ -26,9 +25,7 @@ export default function AddFileCombobox({ const buttonRef = useRef(null); const { getSubmenuContextItems } = useSubmenuContextProviders(); const allFiles = getSubmenuContextItems("file", ""); - const codeToEdit = useSelector( - (state: RootState) => state.editModeState.codeToEdit, - ); + const codeToEdit = useAppSelector((state) => state.session.codeToEdit); const remainingFiles = allFiles.filter( (file) => !codeToEdit.find((code) => code.filepath === file.id), ); diff --git a/gui/src/pages/edit/CodeToEdit.tsx b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx similarity index 84% rename from gui/src/pages/edit/CodeToEdit.tsx rename to gui/src/components/CodeToEditCard/CodeToEditCard.tsx index 659255942..3f4ef372d 100644 --- a/gui/src/pages/edit/CodeToEdit.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx @@ -1,24 +1,22 @@ import { useContext, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { - removeCodeToEdit, - addCodeToEdit, -} from "../../redux/slices/editModeState"; -import { RootState } from "../../redux/store"; import CodeToEditListItem from "./CodeToEditListItem"; -import { CodeToEdit, RangeInFileWithContents } from "core"; +import type { CodeToEdit, RangeInFileWithContents } from "core"; import AddFileButton from "./AddFileButton"; import AddFileCombobox from "./AddFileCombobox"; import { XMarkIcon } from "@heroicons/react/24/outline"; +import { useAppSelector } from "../../redux/hooks"; +import { + addCodeToEdit, + removeCodeToEdit, +} from "../../redux/slices/sessionSlice"; -export default function WorkingSet() { +export default function CodeToEditCard() { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); const [showAddFileCombobox, setShowAddFileCombobox] = useState(false); - const codeToEdit = useSelector( - (state: RootState) => state.editModeState.codeToEdit, - ); + const codeToEdit = useAppSelector((state) => state.session.codeToEdit); const title = codeToEdit.length === 0 @@ -57,7 +55,7 @@ export default function WorkingSet() { } return ( -
+
{title} setShowAddFileCombobox(true)} /> diff --git a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx new file mode 100644 index 000000000..ed46517e2 --- /dev/null +++ b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx @@ -0,0 +1,134 @@ +import FileIcon from "../FileIcon"; +import { + ChevronDownIcon, + ChevronRightIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { useState } from "react"; +import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import { getLastNPathParts, getMarkdownLanguageTagForFile } from "core/util"; +import styled from "styled-components"; +import { CodeToEdit } from "core"; + +export interface CodeToEditListItemProps { + code: CodeToEdit; + onDelete: (codeToEdit: CodeToEdit) => void; + onClickFilename: (codeToEdit: CodeToEdit) => void; +} + +const NoPaddingWrapper = styled.div` + > * { + margin: 0 !important; + padding: 0 !important; + } + + pre { + margin: 0 !important; + padding: 0px 0px 0px 10px !important; + } +`; + +export default function CodeToEditListItem({ + code, + onDelete, + onClickFilename, +}: CodeToEditListItemProps) { + const [showCodeSnippet, setShowCodeSnippet] = useState(false); + + const filepath = code.filepath.split("/").pop() || code.filepath; + const fileSubpath = getLastNPathParts(code.filepath, 2); + + let isInsertion = false; + let title = filepath; + + if ("range" in code) { + const start = code.range.start.line + 1; + const end = code.range.end.line + 1; + + isInsertion = start === end; + + title += isInsertion + ? ` - Inserting at line ${start}` + : ` (${start} - ${end})`; + } + + const source = + "```" + + getMarkdownLanguageTagForFile(code.filepath) + + "\n" + + code.contents + + "\n" + + "```"; + + return ( +
  • { + if (!isInsertion) { + setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet); + } + }} + > +
    +
    + +
    + { + e.stopPropagation(); + onClickFilename(code); + }} + > + {title} + + + {fileSubpath} + +
    +
    + +
    +
    + {showCodeSnippet ? ( + { + e.stopPropagation(); + setShowCodeSnippet(false); + }} + className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20" + /> + ) : ( + { + e.stopPropagation(); + setShowCodeSnippet(true); + }} + className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20" + /> + )} +
    +
    + { + e.stopPropagation(); + onDelete(code); + }} + className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20" + /> +
    +
    +
    + + {showCodeSnippet && ( +
    + + + +
    + )} +
  • + ); +} diff --git a/gui/src/components/CodeToEditCard/index.ts b/gui/src/components/CodeToEditCard/index.ts new file mode 100644 index 000000000..2e7d342eb --- /dev/null +++ b/gui/src/components/CodeToEditCard/index.ts @@ -0,0 +1 @@ +export { default } from "./CodeToEditCard"; diff --git a/gui/src/components/Footer.tsx b/gui/src/components/Footer.tsx index c121feeb1..9b5a6840c 100644 --- a/gui/src/components/Footer.tsx +++ b/gui/src/components/Footer.tsx @@ -1,10 +1,10 @@ -import { useSelector } from "react-redux"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import { useAppSelector } from "../redux/hooks"; +import { selectDefaultModel } from "../redux/slices/configSlice"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar"; function Footer() { - const defaultModel = useSelector(defaultModelSelector); + const defaultModel = useAppSelector(selectDefaultModel); if (defaultModel?.provider === "free-trial") { return ( diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 4364d7bfd..016aae329 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,12 +1,12 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionMetadata } from "core"; import React, { useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; import useHistory from "../../hooks/useHistory"; -import { RootState } from "../../redux/store"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { useAppSelector } from "../../redux/hooks"; function lastPartOfPath(path: string): string { const sep = path.includes("/") ? "/" : "\\"; @@ -32,9 +32,7 @@ export function HistoryTableRow({ const [sessionTitleEditValue, setSessionTitleEditValue] = useState( sessionMetadata.title, ); - const currentSessionId = useSelector( - (state: RootState) => state.state.sessionId, - ); + const currentSessionId = useAppSelector((state) => state.session.id); const { saveSession, deleteSession, loadSession, getSession, updateSession } = useHistory(dispatch); diff --git a/gui/src/components/InfoHover.tsx b/gui/src/components/InfoHover.tsx index aa6541c5b..4b0774efe 100644 --- a/gui/src/components/InfoHover.tsx +++ b/gui/src/components/InfoHover.tsx @@ -1,17 +1,28 @@ import { InformationCircleIcon } from "@heroicons/react/24/outline"; +import { ReactNode } from "react"; import { ToolTip } from "./gui/Tooltip"; -const InfoHover = ({ msg }: { msg: string }) => { - const id = `info-hover-${encodeURIComponent(msg)}`; +const DEFAULT_SIZE = "5"; + +const InfoHover = ({ + msg, + size, + id, +}: { + id: string; + msg: ReactNode; + size?: string; +}) => { + const dataTooltipId = `info-hover-${encodeURIComponent(id)}`; return ( <> - + {msg} diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 6727fcd2c..038655ec0 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -1,25 +1,18 @@ -import { useContext, useEffect, useMemo } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useEffect, useMemo } from "react"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; -import { CustomScrollbarDiv, defaultBorderRadius, vscInputBackground } from "."; -import { IdeMessengerContext } from "../context/IdeMessenger"; +import { CustomScrollbarDiv, defaultBorderRadius } from "."; import { LastSessionProvider } from "../context/LastSessionContext"; import { useWebviewListener } from "../hooks/useWebviewListener"; -import { useConfigError } from "../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../redux/hooks"; +import { setEditStatus, focusEdit } from "../redux/slices/editModeState"; +import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { - setEditDone, - setEditStatus, addCodeToEdit, - focusEdit, - clearCodeToEdit, -} from "../redux/slices/editModeState"; -import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice"; -import { updateApplyState, - updateCurCheckpoint, -} from "../redux/slices/stateSlice"; -import { RootState } from "../redux/store"; + setMode, + newSession, +} from "../redux/slices/sessionSlice"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; import { ROUTES } from "../util/navigation"; @@ -29,6 +22,8 @@ import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import PostHogPageView from "./PosthogPageView"; import AccountDialog from "./AccountDialog"; import { AuthProvider } from "../context/Auth"; +import useHistory from "../hooks/useHistory"; +import { exitEditMode } from "../redux/thunks"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; @@ -57,23 +52,20 @@ const GridDiv = styled.div` const Layout = () => { const navigate = useNavigate(); const location = useLocation(); - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); + const dispatch = useAppDispatch(); const onboardingCard = useOnboardingCard(); const { pathname } = useLocation(); + const { saveSession, loadLastSession } = useHistory(dispatch); - const configError = useConfigError(); + const configError = useAppSelector((state) => state.config.configError); const hasFatalErrors = useMemo(() => { return configError?.some((error) => error.fatal); }, [configError]); - const dialogMessage = useSelector( - (state: RootState) => state.uiState.dialogMessage, - ); - const showDialog = useSelector( - (state: RootState) => state.uiState.showDialog, - ); + const dialogMessage = useAppSelector((state) => state.ui.dialogMessage); + + const showDialog = useAppSelector((state) => state.ui.showDialog); useWebviewListener( "openDialogMessage", @@ -135,12 +127,12 @@ const Layout = () => { useWebviewListener( "updateApplyState", async (state) => { - dispatch( - updateCurCheckpoint({ - filepath: state.filepath, - content: state.fileContent, - }), - ); + // dispatch( + // updateCurCheckpoint({ + // filepath: state.filepath, + // content: state.fileContent, + // }), + // ); dispatch(updateApplyState(state)); }, [], @@ -165,20 +157,23 @@ const Layout = () => { useWebviewListener( "focusEdit", async () => { + await saveSession(false); + dispatch(newSession()); dispatch(focusEdit()); - dispatch(clearCodeToEdit()); - navigate("/edit"); + dispatch(setMode("edit")); }, - [navigate], + [], ); useWebviewListener( "focusEditWithoutClear", async () => { + await saveSession(false); + dispatch(newSession()); dispatch(focusEdit()); - navigate("/edit"); + dispatch(setMode("edit")); }, - [navigate], + [], ); useWebviewListener( @@ -197,14 +192,13 @@ const Layout = () => { [], ); - useWebviewListener( - "exitEditMode", - async () => { - dispatch(setEditDone()); - navigate("/"); - }, - [navigate], - ); + useWebviewListener("exitEditMode", async () => { + loadLastSession().catch((e) => + console.error(`Failed to load last session: ${e}`), + ); + + dispatch(exitEditMode()); + }); useEffect(() => { const handleKeyDown = (event: any) => { diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx index 52f1d2a60..a76f6b57b 100644 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx @@ -6,8 +6,8 @@ import { Button, Input, InputSubtext, lightGray } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { models } from "../../../pages/AddNewModel/configs/models"; import { providers } from "../../../pages/AddNewModel/configs/providers"; -import { setDefaultModel } from "../../../redux/slices/stateSlice"; import AddModelButtonSubtext from "../../AddModelButtonSubtext"; +import { setDefaultModel } from "../../../redux/slices/configSlice"; const { anthropic, mistral } = providers; const chatProvider = anthropic!; diff --git a/gui/src/components/OnboardingCard/components/JetBrainsFetchGitHubTokenDialog.tsx b/gui/src/components/OnboardingCard/components/JetBrainsFetchGitHubTokenDialog.tsx index cc20e77d7..0f7c51248 100644 --- a/gui/src/components/OnboardingCard/components/JetBrainsFetchGitHubTokenDialog.tsx +++ b/gui/src/components/OnboardingCard/components/JetBrainsFetchGitHubTokenDialog.tsx @@ -2,7 +2,7 @@ import { ArrowTopRightOnSquareIcon } from "@heroicons/react/24/outline"; import { useContext, useState } from "react"; import { StyledActionButton, Input, Button, ButtonSubtext } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { setShowDialog } from "../../../redux/slices/uiStateSlice"; +import { setShowDialog } from "../../../redux/slices/uiSlice"; import { useDispatch } from "react-redux"; interface JetBrainsFetchGitHubTokenDialogProps { diff --git a/gui/src/components/OnboardingCard/components/ProviderAlert.tsx b/gui/src/components/OnboardingCard/components/ProviderAlert.tsx index cd3d50a5d..13e2eae11 100644 --- a/gui/src/components/OnboardingCard/components/ProviderAlert.tsx +++ b/gui/src/components/OnboardingCard/components/ProviderAlert.tsx @@ -1,9 +1,6 @@ import { useDispatch } from "react-redux"; import AddModelForm from "../../../forms/AddModelForm"; -import { - setDialogMessage, - setShowDialog, -} from "../../../redux/slices/uiStateSlice"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import Alert from "../../gui/Alert"; import { useSubmitOnboarding } from "../hooks"; diff --git a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx index 2113be710..02a682416 100644 --- a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx +++ b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx @@ -3,14 +3,11 @@ import { useContext } from "react"; import { useDispatch } from "react-redux"; import { Button, ButtonSubtext } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { setDefaultModel } from "../../../redux/slices/stateSlice"; -import { - setDialogMessage, - setShowDialog, -} from "../../../redux/slices/uiStateSlice"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { isJetBrains } from "../../../util"; import { useSubmitOnboarding } from "../hooks"; import JetBrainsFetchGitHubTokenDialog from "./JetBrainsFetchGitHubTokenDialog"; +import { setDefaultModel } from "../../../redux/slices/configSlice"; function QuickstartSubmitButton() { const ideMessenger = useContext(IdeMessengerContext); diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts index f6a29a472..d653012f0 100644 --- a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts +++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts @@ -1,11 +1,11 @@ -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import { TabTitle } from "../components/OnboardingCardTabs"; import useHistory from "../../../hooks/useHistory"; -import { setOnboardingCard } from "../../../redux/slices/uiStateSlice"; +import { setOnboardingCard } from "../../../redux/slices/uiSlice"; import { OnboardingCardState } from ".."; -import { RootState } from "../../../redux/store"; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; +import { useAppSelector } from "../../../redux/hooks"; export interface UseOnboardingCard { show: OnboardingCardState["show"]; @@ -20,9 +20,7 @@ export function useOnboardingCard(): UseOnboardingCard { const dispatch = useDispatch(); const { saveSession } = useHistory(dispatch); - const onboardingCard = useSelector( - (state: RootState) => state.uiState.onboardingCard, - ); + const onboardingCard = useAppSelector((state) => state.ui.onboardingCard); const onboardingStatus = getLocalStorage("onboardingStatus"); const hasDismissedOnboardingCard = getLocalStorage( diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx index ac0273ab9..9008c8700 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx @@ -8,12 +8,12 @@ import { useContext, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; import { Button } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { setDefaultModel } from "../../../redux/slices/stateSlice"; import { hasPassedFTL } from "../../../util/freeTrial"; import AddModelButtonSubtext from "../../AddModelButtonSubtext"; import OllamaModelDownload from "../components/OllamaModelDownload"; import { OllamaStatus } from "../components/OllamaStatus"; import { useSubmitOnboarding } from "../hooks"; +import { setDefaultModel } from "../../../redux/slices/configSlice"; const OLLAMA_CHECK_INTERVAL_MS = 3000; diff --git a/gui/src/components/ProfileSwitcher.tsx b/gui/src/components/ProfileSwitcher.tsx index 4e79972d8..3a5d620de 100644 --- a/gui/src/components/ProfileSwitcher.tsx +++ b/gui/src/components/ProfileSwitcher.tsx @@ -25,6 +25,7 @@ import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice import { RootState } from "../redux/store"; import { getFontSize } from "../util"; import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip"; +import { useAppSelector } from "../redux/hooks"; const StyledListbox = styled(Listbox)` background-color: ${vscBackground}; @@ -129,12 +130,12 @@ function ProfileSwitcher() { const [profiles, setProfiles] = useState([]); const dispatch = useDispatch(); - const lastControlServerBetaEnabledStatus = useSelector( - (state: RootState) => state.misc.lastControlServerBetaEnabledStatus, + const lastControlServerBetaEnabledStatus = useAppSelector( + (state) => state.misc.lastControlServerBetaEnabledStatus, ); - const selectedProfileId = useSelector( - (store: RootState) => store.state.selectedProfileId, + const selectedProfileId = useAppSelector( + (store) => store.session.selectedProfileId, ); const [controlServerBetaEnabled, setControlServerBetaEnabled] = diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index 632468a65..7fbbf07c6 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -3,6 +3,8 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; import { getMetaKeyLabel } from "../../util"; +import { useAppSelector } from "../../redux/hooks"; +import { selectIsSingleRangeEditOrInsertion } from "../../redux/slices/sessionSlice"; export interface AcceptRejectAllButtonsProps { pendingApplyStates: ApplyState[]; @@ -14,9 +16,7 @@ export default function AcceptRejectAllButtons({ onAcceptOrReject, }: AcceptRejectAllButtonsProps) { const ideMessenger = useContext(IdeMessengerContext); - - // To handle the case of a single-range edit - const hasSinglePendingApplyStates = pendingApplyStates.length === 1; + const isSingleRangeEdit = useAppSelector(selectIsSingleRangeEditOrInsertion); async function handleAcceptOrReject(status: "acceptDiff" | "rejectDiff") { for (const { filepath, streamId } of pendingApplyStates) { @@ -37,7 +37,7 @@ export default function AcceptRejectAllButtons({ onClick={() => handleAcceptOrReject("rejectDiff")} > - {hasSinglePendingApplyStates ? ( + {isSingleRangeEdit ? ( Reject ({getMetaKeyLabel()}⇧⌫) ) : ( <> @@ -52,7 +52,7 @@ export default function AcceptRejectAllButtons({ onClick={() => handleAcceptOrReject("acceptDiff")} > - {hasSinglePendingApplyStates ? ( + {isSingleRangeEdit ? ( Accept ({getMetaKeyLabel()}⇧⏎) ) : ( <> diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx index 733ae623b..99e1ce94a 100644 --- a/gui/src/components/StepContainer/EditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -1,11 +1,12 @@ -import { useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; +import { ChatHistoryItem } from "core"; import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; import FeedbackButtons from "./FeedbackButtons"; -import UndoAndRedoButtons from "./UndoAndRedoButtons"; -import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; + +import { renderChatMessage } from "core/util/messageContent"; import { CopyIconButton } from "../gui/CopyIconButton"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import useHistory from "../../hooks/useHistory"; +import { exitEditMode } from "../../redux/thunks/exitEditMode"; export interface EditActionsProps { index: number; @@ -16,11 +17,13 @@ export default function EditActions({ index, item }: EditActionsProps) { // const curCheckpointIndex = useSelector( // (store: RootState) => store.state.curCheckpointIndex, // ); + const dispatch = useAppDispatch(); + const { loadLastSession } = useHistory(dispatch); - const active = useSelector((state: RootState) => state.state.active); + const isStreaming = useAppSelector((state) => state.session.isStreaming); - const applyStates = useSelector( - (state: RootState) => state.state.applyStates, + const applyStates = useAppSelector( + (state) => state.session.codeBlockApplyStates.states, ); const pendingApplyStates = applyStates.filter( @@ -34,7 +37,7 @@ export default function EditActions({ index, item }: EditActionsProps) { // const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; const hasPendingApplies = pendingApplyStates.length > 0; - if (active) return; + if (isStreaming) return; return (
    {hasPendingApplies && ( - + { + loadLastSession().catch((e) => + console.error(`Failed to load last session: ${e}`), + ); + + dispatch(exitEditMode()); + }} + /> )} {/* {hasClosedAllStreams && } */}
    @@ -61,7 +73,7 @@ export default function EditActions({ index, item }: EditActionsProps) {
    diff --git a/gui/src/components/StepContainer/FeedbackButtons.tsx b/gui/src/components/StepContainer/FeedbackButtons.tsx index 55e870991..e621fda33 100644 --- a/gui/src/components/StepContainer/FeedbackButtons.tsx +++ b/gui/src/components/StepContainer/FeedbackButtons.tsx @@ -5,9 +5,8 @@ import { import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { ChatHistoryItem } from "core"; import { useState, useContext } from "react"; -import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { RootState } from "../../redux/store"; +import { useAppSelector } from "../../redux/hooks"; export interface FeedbackButtonsProps { item: ChatHistoryItem; @@ -16,7 +15,7 @@ export interface FeedbackButtonsProps { export default function FeedbackButtons({ item }: FeedbackButtonsProps) { const [feedback, setFeedback] = useState(undefined); const ideMessenger = useContext(IdeMessengerContext); - const sessionId = useSelector((store: RootState) => store.state.sessionId); + const sessionId = useAppSelector((store) => store.session.id); const sendFeedback = (feedback: boolean) => { setFeedback(feedback); @@ -49,7 +48,7 @@ export default function FeedbackButtons({ item }: FeedbackButtonsProps) { - {" "} + ); } diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 8e09cb142..958595aee 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -1,12 +1,12 @@ import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; -import { useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; +import { renderChatMessage } from "core/util/messageContent"; import { CopyIconButton } from "../gui/CopyIconButton"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import EditActions from "./EditActions"; import FeedbackButtons from "./FeedbackButtons"; +import { useAppSelector } from "../../redux/hooks"; +import { selectIsInEditMode } from "../../redux/slices/sessionSlice"; export interface ResponseActionsProps { isTruncated: boolean; @@ -14,6 +14,7 @@ export interface ResponseActionsProps { index: number; onDelete: () => void; item: ChatHistoryItem; + shouldHideActions: boolean; } export default function ResponseActions({ @@ -22,38 +23,46 @@ export default function ResponseActions({ item, isTruncated, onDelete, + shouldHideActions, }: ResponseActionsProps) { - const isInEditMode = useSelector( - (store: RootState) => store.editModeState.isInEditMode, - ); + const isInEditMode = useAppSelector(selectIsInEditMode); if (isInEditMode) { return ; } return ( -
    - {isTruncated && ( - - - +
    + {shouldHideActions || ( + <> + {isTruncated && ( + + + + )} + + + + + + + + + )} - - - - - - -
    ); } diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 7620f16ca..a497a0b22 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -1,15 +1,15 @@ import { ChatHistoryItem } from "core"; -import { stripImages } from "core/llm/images"; +import { renderChatMessage, stripImages } from "core/util/messageContent"; import { useEffect, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import styled from "styled-components"; import { vscBackground } from ".."; -import useUIConfig from "../../hooks/useUIConfig"; -import { deleteMessage } from "../../redux/slices/stateSlice"; -import { RootState } from "../../redux/store"; import { getFontSize } from "../../util"; import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; import ResponseActions from "./ResponseActions"; +import { useAppSelector } from "../../redux/hooks"; +import { selectUIConfig } from "../../redux/slices/configSlice"; +import { deleteMessage } from "../../redux/slices/sessionSlice"; interface StepContainerProps { item: ChatHistoryItem; @@ -19,6 +19,7 @@ interface StepContainerProps { const ContentDiv = styled.div<{ fontSize?: number }>` padding-top: 4px; + padding-bottom: 4px; background-color: ${vscBackground}; font-size: ${getFontSize()}px; overflow: hidden; @@ -27,22 +28,23 @@ const ContentDiv = styled.div<{ fontSize?: number }>` export default function StepContainer(props: StepContainerProps) { const dispatch = useDispatch(); const [isTruncated, setIsTruncated] = useState(false); - const active = useSelector((store: RootState) => store.state.active); - const curCheckpointIndex = useSelector( - (store: RootState) => store.state.curCheckpointIndex, + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const historyItemAfterThis = useAppSelector( + (state) => state.session.history[props.index + 1], ); - const isInEditMode = useSelector( - (store: RootState) => store.editModeState.isInEditMode, - ); - const uiConfig = useUIConfig(); - const shouldHideActions = active && props.isLast; + const uiConfig = useAppSelector(selectUIConfig); + + const shouldHideActions = + (isStreaming && props.isLast) || + historyItemAfterThis?.message.role === "assistant"; + // const isStepAheadOfCurCheckpoint = // isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex; useEffect(() => { - if (!active) { - const content = stripImages(props.item.message.content).trim(); - const endingPunctuation = [".", "?", "!", "```"]; + if (!isStreaming) { + const content = renderChatMessage(props.item.message).trim(); + const endingPunctuation = [".", "?", "!", "```", ":"]; // If not ending in punctuation or emoji, we assume the response got truncated if ( @@ -56,7 +58,7 @@ export default function StepContainer(props: StepContainerProps) { setIsTruncated(false); } } - }, [props.item.message.content, active]); + }, [props.item.message.content, isStreaming]); function onDelete() { dispatch(deleteMessage(props.index)); @@ -76,10 +78,7 @@ export default function StepContainer(props: StepContainerProps) { return (
    {uiConfig?.displayRawMarkdown ? ( @@ -87,7 +86,7 @@ export default function StepContainer(props: StepContainerProps) { className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4" style={{ fontSize: getFontSize() - 2 }} > - {stripImages(props.item.message.content)} + {renderChatMessage(props.item.message)} ) : ( )}
    diff --git a/gui/src/components/StepContainer/UndoAndRedoButtons.tsx b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx index 2ee69a11a..a57b29bd2 100644 --- a/gui/src/components/StepContainer/UndoAndRedoButtons.tsx +++ b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx @@ -1,26 +1,26 @@ -import { useDispatch, useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; +import { useDispatch } from "react-redux"; import { ArrowUturnLeftIcon, ArrowUturnRightIcon, } from "@heroicons/react/24/outline"; -import { setCurCheckpointIndex } from "../../redux/slices/stateSlice"; +import { setCurCheckpointIndex } from "../../redux/slices/sessionSlice"; import { useContext } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppSelector } from "../../redux/hooks"; export default function UndoAndRedoButtons() { const dispatch = useDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const checkpoints = useSelector( - (store: RootState) => store.state.checkpoints, + const checkpoints = useAppSelector( + (store) => store.session.history.at(-1).checkpoint, ); - const curCheckpointIndex = useSelector( - (store: RootState) => store.state.curCheckpointIndex, + const curCheckpointIndex = useAppSelector( + (store) => store.session.curCheckpointIndex, ); - const shouldRenderRedo = curCheckpointIndex !== checkpoints.length - 1; + const shouldRenderRedo = false; // curCheckpointIndex !== checkpoints.length - 1; async function handleUndoOrRedo(type: "undo" | "redo") { const checkpointIndex = Math.max( diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 2559dc205..51d11498d 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -7,19 +7,16 @@ import { import { IndexingStatus, PackageDocsResult, SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; import { useContext, useLayoutEffect, useMemo, useRef, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { Input, SecondaryButton } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { - setDialogMessage, - setShowDialog, -} from "../../redux/slices/uiStateSlice"; -import { RootState } from "../../redux/store"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { ToolTip } from "../gui/Tooltip"; import FileIcon from "../FileIcon"; import DocsIndexingPeeks from "../indexing/DocsIndexingPeeks"; -import { updateIndexingStatus } from "../../redux/slices/stateSlice"; import preIndexedDocs from "core/indexing/docs/preIndexedDocs"; +import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; +import { useAppSelector } from "../../redux/hooks"; function AddDocsDialog() { const posthog = usePostHog(); @@ -33,8 +30,8 @@ function AddDocsDialog() { const [faviconUrl, setFaviconUrl] = useState(""); const ideMessenger = useContext(IdeMessengerContext); - const indexingStatuses = useSelector( - (store: RootState) => store.state.indexing.statuses, + const indexingStatuses = useAppSelector( + (store) => store.indexing.indexing.statuses, ); const docsIndexingStatuses: IndexingStatus[] = useMemo(() => { @@ -43,11 +40,8 @@ function AddDocsDialog() { ); }, [indexingStatuses]); - const docsSuggestions = useSelector( - (store: RootState) => store.state.docsSuggestions, - ); - - const configDocs = useSelector((store: RootState) => store.state.config.docs); + const docsSuggestions = useAppSelector((store) => store.misc.docsSuggestions); + const configDocs = useAppSelector((store) => store.config.config.docs); const sortedDocsSuggestions = useMemo(() => { const docsFromConfig = configDocs ?? []; diff --git a/gui/src/components/dialogs/ConfirmationDialog.test.tsx b/gui/src/components/dialogs/ConfirmationDialog.test.tsx index d426791de..a5e209947 100644 --- a/gui/src/components/dialogs/ConfirmationDialog.test.tsx +++ b/gui/src/components/dialogs/ConfirmationDialog.test.tsx @@ -2,13 +2,13 @@ import { configureStore } from "@reduxjs/toolkit"; import { fireEvent, render, screen } from "@testing-library/react"; import { Provider } from "react-redux"; import { describe, expect, it, vi } from "vitest"; -import { uiStateSlice } from "../../redux/slices/uiStateSlice"; +import { uiSlice } from "../../redux/slices/uiSlice"; import ConfirmationDialog from "./ConfirmationDialog"; const createMockStore = () => { return configureStore({ reducer: { - uiState: uiStateSlice.reducer, + uiState: uiSlice.reducer, }, }); }; diff --git a/gui/src/components/dialogs/ConfirmationDialog.tsx b/gui/src/components/dialogs/ConfirmationDialog.tsx index 965d38e07..f41f04a20 100644 --- a/gui/src/components/dialogs/ConfirmationDialog.tsx +++ b/gui/src/components/dialogs/ConfirmationDialog.tsx @@ -1,10 +1,7 @@ import { useDispatch } from "react-redux"; import styled from "styled-components"; import { Button, lightGray, SecondaryButton } from ".."; -import { - setDialogMessage, - setShowDialog, -} from "../../redux/slices/uiStateSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; const GridDiv = styled.div` display: grid; diff --git a/gui/src/components/dialogs/FeedbackDialog.tsx b/gui/src/components/dialogs/FeedbackDialog.tsx new file mode 100644 index 000000000..d8da4e93b --- /dev/null +++ b/gui/src/components/dialogs/FeedbackDialog.tsx @@ -0,0 +1,64 @@ +import { usePostHog } from "posthog-js/react"; +import { setDialogMessage } from "../../redux/slices/uiSlice"; +import { useAppDispatch } from "../../redux/hooks"; + +export default function FeedbackDialog() { + const posthog = usePostHog(); + const dispatch = useAppDispatch(); + + return ( +
    + 👋 Thanks for using Continue. We are always trying to improve and love + hearing from users. If you're interested in speaking, enter your name and + email. We won't use this information for anything other than reaching out. +
    +
    +
    { + e.preventDefault(); + posthog?.capture("user_interest_form", { + name: e.target.elements[0].value, + email: e.target.elements[1].value, + }); + dispatch( + setDialogMessage( +
    + Thanks! We'll be in touch soon. +
    , + ), + ); + }} + style={{ + display: "flex", + flexDirection: "column", + gap: "10px", + }} + > + + + +
    +
    + ); +} diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 8a3a67fe8..9bdbec5de 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -11,7 +11,7 @@ import { vscForeground, } from ".."; import { useDispatch } from "react-redux"; -import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { setShowDialog } from "../../redux/slices/uiSlice"; import { XMarkIcon } from "@heroicons/react/24/outline"; interface TextDialogProps { diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index cd9088302..9bf965d0f 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -15,6 +15,7 @@ import { useSelector } from "react-redux"; import { HeaderButton, Input } from ".."; import { RootState } from "../../redux/store"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import { useAppSelector } from "../../redux/hooks"; interface SearchMatch { index: number; @@ -346,7 +347,8 @@ export const useFindWidget = (searchRef: RefObject) => { // Triggers that should cause results to temporarily disappear and then reload // Active = LLM is generating, etc. - const active = useSelector((state: RootState) => state.state.active); + const active = useAppSelector((state) => state.session.isStreaming); + useEffect(() => { if (active || isResizing) setMatches([]); else refreshSearch("none"); diff --git a/gui/src/components/indexing/ChatIndexingPeeks.tsx b/gui/src/components/indexing/ChatIndexingPeeks.tsx index 46086cb0d..1ec1076c0 100644 --- a/gui/src/components/indexing/ChatIndexingPeeks.tsx +++ b/gui/src/components/indexing/ChatIndexingPeeks.tsx @@ -1,11 +1,10 @@ -import { useDispatch, useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; - +import { useDispatch } from "react-redux"; import { IndexingStatus } from "core"; -import { useMemo, useState } from "react"; +import { useMemo } from "react"; import { useNavigate } from "react-router-dom"; import { ArrowPathIcon, EyeSlashIcon } from "@heroicons/react/24/outline"; -import { setIndexingChatPeekHidden } from "../../redux/slices/stateSlice"; +import { useAppSelector } from "../../redux/hooks"; +import { setIndexingChatPeekHidden } from "../../redux/slices/indexingSlice"; interface MergedIndexingState { displayName: string; @@ -27,8 +26,8 @@ export interface ChatIndexingPeekProps { function ChatIndexingPeek({ state }: ChatIndexingPeekProps) { const navigate = useNavigate(); const dispatch = useDispatch(); - const hiddenPeeks = useSelector( - (store: RootState) => store.state.indexing.hiddenChatPeekTypes, + const hiddenPeeks = useAppSelector( + (store) => store.indexing.indexing.hiddenChatPeekTypes, ); if (hiddenPeeks[state.type]) return null; @@ -41,7 +40,7 @@ function ChatIndexingPeek({ state }: ChatIndexingPeekProps) { >
    -

    +

    {state.displayName}

    @@ -76,8 +75,8 @@ function ChatIndexingPeek({ state }: ChatIndexingPeekProps) { } function ChatIndexingPeeks() { - const indexingStatuses = useSelector( - (store: RootState) => store.state.indexing.statuses, + const indexingStatuses = useAppSelector( + (store) => store.indexing.indexing.statuses, ); const mergedIndexingStates: MergedIndexingState[] = useMemo(() => { const mergedStates: MergedIndexingState[] = []; diff --git a/gui/src/components/indexing/DocsIndexingPeeks.tsx b/gui/src/components/indexing/DocsIndexingPeeks.tsx index d63012865..f659b48f9 100644 --- a/gui/src/components/indexing/DocsIndexingPeeks.tsx +++ b/gui/src/components/indexing/DocsIndexingPeeks.tsx @@ -1,14 +1,8 @@ -import { useDispatch, useSelector } from "react-redux"; - +import { useDispatch } from "react-redux"; import { IndexingStatus } from "core"; import { useMemo } from "react"; import { useNavigate } from "react-router-dom"; -import { ArrowPathIcon } from "@heroicons/react/24/outline"; -import { - setDialogMessage, - setShowDialog, -} from "../../redux/slices/uiStateSlice"; -import { RootState } from "../../redux/store"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; export interface DocsIndexingPeekProps { status: IndexingStatus; @@ -59,9 +53,6 @@ interface DocsIndexingPeeksProps { } function DocsIndexingPeekList({ statuses }: DocsIndexingPeeksProps) { - const config = useSelector((store: RootState) => store.state.config); - const configDocs = config.docs ?? []; - // const docs return (

    diff --git a/gui/src/components/indexing/DocsIndexingStatus.tsx b/gui/src/components/indexing/DocsIndexingStatus.tsx index 4fb5013cd..03a941c80 100644 --- a/gui/src/components/indexing/DocsIndexingStatus.tsx +++ b/gui/src/components/indexing/DocsIndexingStatus.tsx @@ -1,18 +1,16 @@ import { IndexingStatus, SiteIndexingConfig } from "core"; -import { PropsWithChildren, useContext, useMemo } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { usePostHog } from "posthog-js/react"; +import { useContext, useMemo } from "react"; +import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { ArrowPathIcon, - ArrowRightStartOnRectangleIcon, ArrowTopRightOnSquareIcon, CheckCircleIcon, PauseCircleIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { updateIndexingStatus } from "../../redux/slices/stateSlice"; -import { RootState } from "../../redux/store"; +import { useAppSelector } from "../../redux/hooks"; +import { updateIndexingStatus } from "../../redux/slices/indexingSlice"; interface IndexingStatusViewerProps { docConfig: SiteIndexingConfig; @@ -30,12 +28,10 @@ const STATUS_TO_ICON: Record = { function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) { const ideMessenger = useContext(IdeMessengerContext); - const posthog = usePostHog(); const dispatch = useDispatch(); - // const status = undefined; - const status = useSelector( - (store: RootState) => store.state.indexing.statuses[docConfig.startUrl], + const status = useAppSelector( + (store) => store.indexing.indexing.statuses[docConfig.startUrl], ); const reIndex = () => diff --git a/gui/src/components/indexing/DocsIndexingStatuses.tsx b/gui/src/components/indexing/DocsIndexingStatuses.tsx index 84fdba903..a54ffd2a5 100644 --- a/gui/src/components/indexing/DocsIndexingStatuses.tsx +++ b/gui/src/components/indexing/DocsIndexingStatuses.tsx @@ -1,22 +1,17 @@ -import { useMemo } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; -import IndexingStatusViewer from "./DocsIndexingStatus"; +import { useDispatch } from "react-redux"; import { SecondaryButton } from ".."; -import { - setDialogMessage, - setShowDialog, -} from "../../redux/slices/uiStateSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import AddDocsDialog from "../dialogs/AddDocsDialog"; import DocsIndexingStatus from "./DocsIndexingStatus"; +import { useAppSelector } from "../../redux/hooks"; function DocsIndexingStatuses() { const dispatch = useDispatch(); - const config = useSelector((store: RootState) => store.state.config); + const config = useAppSelector((store) => store.config.config); const configDocs = config.docs ?? []; // const indexingStatuses = useSelector( - // (store: RootState) => store.state.indexing.statuses, + // (store: RootState) => store.indexing.indexing.statuses, // ); // const docsStatuses = useMemo(() => { // const docs = Object.values(indexingStatuses).filter( diff --git a/gui/src/components/loaders/FreeTrialProgressBar.tsx b/gui/src/components/loaders/FreeTrialProgressBar.tsx index 6363ede49..dd8d2be39 100644 --- a/gui/src/components/loaders/FreeTrialProgressBar.tsx +++ b/gui/src/components/loaders/FreeTrialProgressBar.tsx @@ -2,10 +2,7 @@ import { ExclamationCircleIcon } from "@heroicons/react/24/outline"; import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import AddModelForm from "../../forms/AddModelForm"; -import { - setDialogMessage, - setShowDialog, -} from "../../redux/slices/uiStateSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial"; import { ToolTip } from "../gui/Tooltip"; diff --git a/gui/src/components/mainInput/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index a8f3eeeb1..f8c359e14 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -8,7 +8,7 @@ export const CodeBlockComponent = (props: any) => { const item: ContextItemWithId = node.attrs.item; // const contextItems = useSelector( // (store: RootState) => - // store.state.history[store.state.history.length - 1].contextItems, + // store.session.messages[store.session.messages.length - 1].contextItems, // ); // const isFirstContextItem = item.id === contextItems[0]?.id; const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 3772ba057..2f97af73b 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -1,17 +1,19 @@ -import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; +import { + ArrowTopRightOnSquareIcon, + ChevronDownIcon, + ChevronRightIcon, +} from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; +import { getBasename } from "core/util"; import { useContext, useMemo, useState } from "react"; import { AnimatedEllipsis, lightGray, vscBackground } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; -import { INSTRUCTIONS_BASE_ITEM } from "core/context/providers/utils"; import { getIconFromDropdownItem } from "./MentionList"; -import { getBasename } from "core/util"; -import { RootState } from "../../redux/store"; -import { useSelector } from "react-redux"; -import { ArrowTopRightOnSquareIcon } from "@heroicons/react/24/outline"; +import { useAppSelector } from "../../redux/hooks"; +import { selectIsGatheringContext } from "../../redux/slices/sessionSlice"; interface ContextItemsPeekProps { contextItems?: ContextItemWithId[]; @@ -133,19 +135,10 @@ function ContextItemsPeek({ const [open, setOpen] = useState(false); const ctxItems = useMemo(() => { - return ( - contextItems?.filter( - (ctxItem) => !ctxItem.name.includes(INSTRUCTIONS_BASE_ITEM.name), - ) ?? [] - ); + return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; }, [contextItems]); - const isGatheringContext = useSelector( - (store: RootState) => store.state.context.isGathering, - ); - const gatheringMessage = useSelector( - (store: RootState) => store.state.context.gatheringMessage, - ); + const isGatheringContext = useAppSelector(selectIsGatheringContext); const indicateIsGathering = isCurrentContextPeek && isGatheringContext; @@ -154,7 +147,12 @@ function ContextItemsPeek({ } return ( -

    +
    setOpen((prev) => !prev)} @@ -174,7 +172,7 @@ function ContextItemsPeek({ {isGatheringContext ? ( <> - {gatheringMessage} + Gathering context... ) : ( diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 93ac4fddf..7625ca0d6 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,15 +1,19 @@ import { Editor, JSONContent } from "@tiptap/react"; import { ContextItemWithId, InputModifiers } from "core"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; -import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice"; -import { RootState } from "../../redux/store"; import ContextItemsPeek from "./ContextItemsPeek"; import TipTapEditor from "./TipTapEditor"; +import { useAppSelector } from "../../redux/hooks"; +import { newSession, setMessageAtIndex } from "../../redux/slices/sessionSlice"; +import { ToolbarOptions } from "./InputToolbar"; +import { useMemo } from "react"; + interface ContinueInputBoxProps { + isEditMode?: boolean; isLastUserInput: boolean; isMainInput?: boolean; onEnter: ( @@ -22,6 +26,18 @@ interface ContinueInputBoxProps { hidden?: boolean; } +const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ + "codebase", + "tree", + "open", + "web", + "diff", + "folder", + "search", + "debugger", + "repo-map", +]; + const gradient = keyframes` 0% { background-position: 0px 0; @@ -62,11 +78,52 @@ const GradientBorder = styled.div<{ function ContinueInputBox(props: ContinueInputBoxProps) { const dispatch = useDispatch(); - const active = useSelector((store: RootState) => store.state.active); - const availableSlashCommands = useSelector(selectSlashCommandComboBoxInputs); - const availableContextProviders = useSelector( - (store: RootState) => store.state.config.contextProviders, + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const availableSlashCommands = useAppSelector( + selectSlashCommandComboBoxInputs, ); + const availableContextProviders = useAppSelector( + (state) => state.config.config.contextProviders, + ); + const useTools = useAppSelector( + (state) => state.config.config.experimental?.useTools !== false, + ); + const editModeState = useAppSelector((state) => state.editModeState); + + const filteredSlashCommands = props.isEditMode ? [] : availableSlashCommands; + const filteredContextProviders = useMemo(() => { + if (!props.isEditMode) { + availableContextProviders; + } + + return ( + availableContextProviders?.filter( + (provider) => + !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), + ) ?? [] + ); + }, [availableContextProviders]); + + const isStreamingEdit = + editModeState.editStatus === "streaming" || + editModeState.editStatus === "accepting"; + + const historyKey = props.isEditMode ? "edit" : "chat"; + const placeholder = props.isEditMode + ? "Describe how to modify the code - use '#' to add files" + : undefined; + const toolbarOptions: ToolbarOptions = props.isEditMode + ? { + hideAddContext: false, + hideImageUpload: false, + hideUseCodebase: true, + hideSelectModel: false, + hideTools: true, + enterText: isStreamingEdit ? "Retry" : "Edit", + } + : { + hideTools: !useTools, + }; useWebviewListener( "newSessionWithPrompt", @@ -85,27 +142,24 @@ function ContinueInputBox(props: ContinueInputBoxProps) { ); return ( -
    -
    +
    +
    { - props.onEnter(...args); - if (props.isMainInput) { - args[2].commands.clearContent(true); - } - }} + onEnter={props.onEnter} + placeholder={placeholder} isMainInput={props.isMainInput ?? false} - availableContextProviders={availableContextProviders ?? []} - availableSlashCommands={availableSlashCommands} - historyKey="chat" + availableContextProviders={filteredContextProviders} + availableSlashCommands={filteredSlashCommands} + historyKey={historyKey} + toolbarOptions={toolbarOptions} />
    diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index e1fd7ad74..a7591b84c 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -2,7 +2,6 @@ import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; import { modelSupportsImages } from "core/llm/autodetect"; import { useRef } from "react"; -import { useSelector } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius, @@ -11,7 +10,6 @@ import { vscInputBackground, } from ".."; import { selectUseActiveFile } from "../../redux/selectors"; -import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; import { getAltKeyLabel, getFontSize, @@ -20,6 +18,10 @@ import { } from "../../util"; 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 { selectDefaultModel } from "../../redux/slices/configSlice"; const StyledDiv = styled.div<{ isHidden?: boolean }>` padding-top: 4px; @@ -38,17 +40,6 @@ const StyledDiv = styled.div<{ isHidden?: boolean }>` } `; -const HoverItem = styled.span<{ isActive?: boolean }>` - padding: 0 4px; - padding-top: 2px; - padding-bottom: 2px; - cursor: pointer; - transition: - color 200ms, - background-color 200ms, - box-shadow 200ms; -`; - const EnterButton = styled.button` all: unset; padding: 2px 4px; @@ -69,6 +60,7 @@ export interface ToolbarOptions { hideAddContext?: boolean; enterText?: string; hideSelectModel?: boolean; + hideTools?: boolean; } interface InputToolbarProps { @@ -85,8 +77,8 @@ interface InputToolbarProps { function InputToolbar(props: InputToolbarProps) { const fileInputRef = useRef(null); - const defaultModel = useSelector(defaultModelSelector); - const useActiveFile = useSelector(selectUseActiveFile); + const defaultModel = useAppSelector(selectDefaultModel); + const useActiveFile = useAppSelector(selectUseActiveFile); const supportsImages = defaultModel && @@ -145,6 +137,8 @@ function InputToolbar(props: InputToolbarProps) { )} + + {props.toolbarOptions?.hideTools || }
    @@ -153,7 +147,7 @@ function InputToolbar(props: InputToolbarProps) {
    {props.activeKey === "Alt" ? ( - {`${getAltKeyLabel()}⏎ + {`${getAltKeyLabel()}⏎ ${useActiveFile ? "No active file" : "Active file"}`} ) : ( diff --git a/gui/src/components/mainInput/InputToolbar/HoverItem.tsx b/gui/src/components/mainInput/InputToolbar/HoverItem.tsx new file mode 100644 index 000000000..e668a69f2 --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/HoverItem.tsx @@ -0,0 +1,14 @@ +import styled from "styled-components"; + +const HoverItem = styled.span<{ isActive?: boolean }>` + padding: 0 4px; + padding-top: 2px; + padding-bottom: 2px; + cursor: pointer; + transition: + color 200ms, + background-color 200ms, + box-shadow 200ms; +`; + +export default HoverItem; diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx new file mode 100644 index 000000000..ba2c75024 --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx @@ -0,0 +1,159 @@ +import { Listbox, Transition } from "@headlessui/react"; +import { + ChevronDownIcon, + ChevronUpIcon, + WrenchScrewdriverIcon, +} from "@heroicons/react/24/outline"; +import { modelSupportsTools } from "core/llm/autodetect"; +import { useEffect, useRef, useState } from "react"; +import { useDispatch } from "react-redux"; +import styled from "styled-components"; +import { defaultBorderRadius, lightGray, vscForeground } from "../.."; +import { toggleUseTools } from "../../../redux/slices/uiSlice"; +import { getFontSize } from "../../../util"; +import InfoHover from "../../InfoHover"; +import HoverItem from "./HoverItem"; +import ToolDropdownItem from "./ToolDropdownItem"; +import { useAppSelector } from "../../../redux/hooks"; +import { selectDefaultModel } from "../../../redux/slices/configSlice"; + +const BackgroundDiv = styled.div<{ useTools: boolean }>` + background-color: ${(props) => + props.useTools ? `${lightGray}33` : "transparent"}; + border-radius: ${defaultBorderRadius}; + padding: 1px; + + font-size: ${getFontSize() - 4}px; + + display: flex; + flex-direction: row; + align-items: center; + gap: 2px; + + transition: background-color 200ms; +`; + +export default function ToolDropdown() { + const buttonRef = useRef(null); + const dispatch = useDispatch(); + const [isDropdownOpen, setDropdownOpen] = useState(false); + + const useTools = useAppSelector((state) => state.ui.useTools); + const availableTools = useAppSelector((state) => state.config.config.tools); + const defaultModel = useAppSelector(selectDefaultModel); + + const [showAbove, setShowAbove] = useState(false); + + useEffect(() => { + const checkPosition = () => { + if (buttonRef.current) { + const rect = buttonRef.current.getBoundingClientRect(); + const windowHeight = window.innerHeight; + const spaceBelow = windowHeight - rect.bottom; + setShowAbove(spaceBelow < 250); + } + }; + + if (isDropdownOpen) { + checkPosition(); + } + }, [isDropdownOpen]); + + if (!defaultModel || !modelSupportsTools(defaultModel.model)) { + return null; + } + + return ( + dispatch(toggleUseTools())}> + + + {useTools && ( + <> + Tools + +
    + {}}> + { + e.stopPropagation(); + setDropdownOpen((prev) => !prev); + }} + className="text-lightgray flex cursor-pointer items-center border-none bg-transparent outline-none" + > + {isDropdownOpen ? ( + + ) : ( + + )} + + + +
    +
    + Tool policies{" "} + +

    + + Automatic: + {" "} + Can be used without asking +

    +

    + + Allowed: + {" "} + Will ask before using +

    +

    + Disabled:{" "} + Cannot be used +

    +
    + } + /> +
    +
    +
    + {availableTools.map((tool) => ( + + + + ))} +
    + + + +
    + + )} + + + ); +} diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx new file mode 100644 index 000000000..be2162118 --- /dev/null +++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx @@ -0,0 +1,59 @@ +import { Tool } from "core"; +import { useEffect } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { RootState } from "../../../redux/store"; +import { addTool, toggleToolSetting } from "../../../redux/slices/uiSlice"; + +interface ToolDropdownItemProps { + tool: Tool; +} + +function ToolDropdownItem(props: ToolDropdownItemProps) { + const dispatch = useDispatch(); + const settings = useSelector( + (state: RootState) => state.ui.toolSettings[props.tool.function.name], + ); + + useEffect(() => { + if (!settings) { + dispatch(addTool(props.tool)); + } + }, [props.tool.function.name, settings]); + + if (!settings) { + return null; + } + + return ( +
    { + dispatch(toggleToolSetting(props.tool.function.name)); + e.stopPropagation(); + e.preventDefault(); + }} + > + + {props.tool.displayTitle}{" "} + {/* */} + +
    + {(settings === "allowedWithPermission" || settings === undefined) && ( + Allowed + )} + {settings === "allowedWithoutPermission" && ( + Automatic + )} + {settings === "disabled" && ( + Disabled + )} +
    +
    + ); +} + +export default ToolDropdownItem; diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index dae812dcf..02cf4d8aa 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -37,10 +37,7 @@ import { vscQuickInputBackground, } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { - setDialogMessage, - setShowDialog, -} from "../../redux/slices/uiStateSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import FileIcon from "../FileIcon"; import SafeImg from "../SafeImg"; diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 5d015e9d4..479876f0f 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -24,7 +24,6 @@ import { useRef, useState, } from "react"; -import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { v4 } from "uuid"; import { @@ -44,12 +43,6 @@ import useIsOSREnabled from "../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../hooks/useUpdatingRef"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { selectUseActiveFile } from "../../redux/selectors"; -import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; -import { - addCodeToEdit, - clearCodeToEdit, -} from "../../redux/slices/editModeState"; -import { RootState } from "../../redux/store"; import { getFontSize, isJetBrains, @@ -70,6 +63,14 @@ import { handleVSCMetaKeyIssues, } from "./handleMetaKeyIssues"; import { ComboBoxItem } from "./types"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { selectDefaultModel } from "../../redux/slices/configSlice"; +import { + addCodeToEdit, + clearCodeToEdit, + selectIsInEditMode, +} from "../../redux/slices/sessionSlice"; +import { exitEditMode } from "../../redux/thunks"; const InputBoxDiv = styled.div<{ border?: string }>` resize: none; @@ -175,36 +176,24 @@ interface TipTapEditorProps { } function TipTapEditor(props: TipTapEditorProps) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const { getSubmenuContextItems } = useSubmenuContextProviders(); - const historyLength = useSelector( - (store: RootState) => store.state.history.length, - ); + const historyLength = useAppSelector((store) => store.session.history.length); - const useActiveFile = useSelector(selectUseActiveFile); + const useActiveFile = useAppSelector(selectUseActiveFile); - const { saveSession, loadSession } = useHistory(dispatch); + const { saveSession, loadSession, loadLastSession } = useHistory(dispatch); const posthog = usePostHog(); - const [isEditorFocused, setIsEditorFocused] = useState(false); - const [hasDefaultModel, setHasDefaultModel] = useState(true); const inSubmenuRef = useRef(undefined); const inDropdownRef = useRef(false); const isOSREnabled = useIsOSREnabled(); - const isInEditMode = useSelector( - (state: RootState) => state.editModeState.isInEditMode, - ); - - const shouldAddFileForEditing = useSelector( - (state: RootState) => state.uiState.shouldAddFileForEditing, - ); - const enterSubmenu = async (editor: Editor, providerId: string) => { const contents = editor.getText(); const indexOfAt = contents.lastIndexOf("@"); @@ -246,7 +235,7 @@ function TipTapEditor(props: TipTapEditorProps) { inDropdownRef.current = true; }; - const defaultModel = useSelector(defaultModelSelector); + const defaultModel = useAppSelector(selectDefaultModel); const defaultModelRef = useUpdatingRef(defaultModel); const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems); @@ -259,22 +248,11 @@ function TipTapEditor(props: TipTapEditorProps) { props.availableSlashCommands, ); - const active = useSelector((state: RootState) => state.state.active); - const activeRef = useUpdatingRef(active); + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const isStreamingRef = useUpdatingRef(isStreaming); - // Only set `hasDefaultModel` after a timeout to prevent jank - useEffect(() => { - const timer = setTimeout(() => { - setHasDefaultModel( - !!defaultModel && - defaultModel.apiKey !== undefined && - defaultModel.apiKey !== "", - ); - }, 3500); - - // Cleanup function to clear the timeout if the component unmounts - return () => clearTimeout(timer); - }, [defaultModel]); + const isInEditMode = useAppSelector(selectIsInEditMode); + const isInEditModeRef = useUpdatingRef(isInEditMode); async function handleImageFile( file: File, @@ -320,8 +298,8 @@ function TipTapEditor(props: TipTapEditorProps) { return undefined; } - const mainEditorContent = useSelector( - (store: RootState) => store.state.mainEditorContent, + const mainEditorContent = useAppSelector( + (store) => store.session.mainEditorContent, ); const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey); @@ -369,11 +347,10 @@ function TipTapEditor(props: TipTapEditorProps) { }, }), Placeholder.configure({ - placeholder: - props.placeholder ?? - (historyLengthRef.current === 0 - ? "Ask anything, '@' to add context" - : "Ask a follow-up"), + placeholder: getPlaceholderText( + props.placeholder, + historyLengthRef.current, + ), }), Paragraph.extend({ addKeyboardShortcuts() { @@ -411,7 +388,7 @@ function TipTapEditor(props: TipTapEditorProps) { // If you press cmd+backspace wanting to cancel, // but are inside of a text box, it shouldn't // delete the text - if (activeRef.current) { + if (isStreamingRef.current) { return true; } }, @@ -440,6 +417,19 @@ function TipTapEditor(props: TipTapEditorProps) { return true; } }, + Escape: () => { + if (inDropdownRef.current || !isInEditModeRef.current) { + return false; + } + + loadLastSession().catch((e) => + console.error(`Failed to load last session: ${e}`), + ); + + dispatch(exitEditMode()); + + return true; + }, ArrowDown: () => { if ( this.editor.state.selection.anchor < @@ -482,7 +472,7 @@ function TipTapEditor(props: TipTapEditorProps) { return `@${props.node.attrs.label || props.node.attrs.id}`; }, }), - isInEditMode + isInEditModeRef.current ? AddCodeToEdit.configure({ HTMLAttributes: { class: "add-code-to-edit", @@ -550,10 +540,7 @@ function TipTapEditor(props: TipTapEditorProps) { }, }, content: props.editorState || mainEditorContent || "", - onFocus: () => setIsEditorFocused(true), - onBlur: () => setIsEditorFocused(false), - // onUpdate - editable: !active || props.isMainInput, + editable: !isStreaming || props.isMainInput, }); const [shouldHideToolbar, setShouldHideToolbar] = useState(false); @@ -561,6 +548,38 @@ function TipTapEditor(props: TipTapEditorProps) { setShouldHideToolbar(value); }, 200); + function getPlaceholderText( + placeholder: TipTapEditorProps["placeholder"], + historyLength: number, + ) { + if (placeholder) { + return placeholder; + } + + return historyLength === 0 + ? "Ask anything, '@' to add context" + : "Ask a follow-up"; + } + + useEffect(() => { + const placeholder = getPlaceholderText( + props.placeholder, + historyLengthRef.current, + ); + + editor.extensionManager.extensions.filter( + (extension) => extension.name === "placeholder", + )[0].options["placeholder"] = placeholder; + + editor.view.dispatch(editor.state.tr); + }, [editor, props.placeholder, historyLengthRef.current]); + + useEffect(() => { + if (props.isMainInput) { + editor.commands.clearContent(true); + } + }, [isInEditMode, props.isMainInput]); + useEffect(() => { if (editor) { const handleFocus = () => { @@ -613,7 +632,7 @@ function TipTapEditor(props: TipTapEditorProps) { const onEnterRef = useUpdatingRef( (modifiers: InputModifiers) => { - if (active) { + if (isStreaming) { return; } @@ -636,10 +655,10 @@ function TipTapEditor(props: TipTapEditorProps) { // Re-focus main input after done generating useEffect(() => { - if (editor && !active && props.isMainInput && document.hasFocus()) { + if (editor && !isStreaming && props.isMainInput && document.hasFocus()) { editor.commands.focus(undefined, { scrollIntoView: false }); } - }, [props.isMainInput, active, editor]); + }, [props.isMainInput, isStreaming, editor]); // IDE event listeners useWebviewListener( @@ -783,6 +802,34 @@ function TipTapEditor(props: TipTapEditorProps) { ], ); + useWebviewListener( + "focusEdit", + async () => { + if (!props.isMainInput) { + return; + } + + setTimeout(() => { + editor?.commands.focus("end"); + }, 20); + }, + [editor, props.isMainInput], + ); + + useWebviewListener( + "focusEditWithoutClear", + async () => { + if (!props.isMainInput) { + return; + } + + setTimeout(() => { + editor?.commands.focus("end"); + }, 2000); + }, + [editor, props.isMainInput], + ); + useWebviewListener( "isContinueInputFocused", async () => { @@ -915,7 +962,7 @@ function TipTapEditor(props: TipTapEditorProps) { }); }); }} - disabled={active} + disabled={isStreaming} /> diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 96ab0d93b..ae9dd88a9 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -7,10 +7,10 @@ import { MessagePart, RangeInFile, } from "core"; -import { stripImages } from "core/llm/images"; +import { stripImages } from "core/util/messageContent"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { Dispatch } from "@reduxjs/toolkit"; -import { setIsGatheringContext } from "../../redux/slices/stateSlice"; +import { setIsGatheringContext } from "../../redux/slices/sessionSlice"; interface MentionAttrs { label: string; @@ -110,12 +110,7 @@ async function resolveEditorContent( const shouldGatherContext = modifiers.useCodebase || slashCommand; if (shouldGatherContext) { - dispatch( - setIsGatheringContext({ - isGathering: true, - gatheringMessage: "Gathering context", - }), - ); + dispatch(setIsGatheringContext(true)); } let contextItemsText = ""; @@ -188,12 +183,7 @@ async function resolveEditorContent( } if (shouldGatherContext) { - dispatch( - setIsGatheringContext({ - isGathering: false, - gatheringMessage: "Gathering context", - }), - ); + dispatch(setIsGatheringContext(true)); } return [contextItems, selectedCode, parts]; diff --git a/gui/src/components/markdown/StepContainerPreActionButtons.tsx b/gui/src/components/markdown/StepContainerPreActionButtons.tsx index fa84ae8ec..3e42c5872 100644 --- a/gui/src/components/markdown/StepContainerPreActionButtons.tsx +++ b/gui/src/components/markdown/StepContainerPreActionButtons.tsx @@ -11,12 +11,13 @@ import { isJetBrains } from "../../util"; import { isTerminalCodeBlock, getTerminalCommand } from "./utils"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { CopyIconButton } from "../gui/CopyIconButton"; -import useUIConfig from "../../hooks/useUIConfig"; import { v4 as uuidv4 } from "uuid"; import { useWebviewListener } from "../../hooks/useWebviewListener"; -import { useSelector } from "react-redux"; -import { RootState } from "../../redux/store"; -import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; +import { useAppSelector } from "../../redux/hooks"; +import { + selectDefaultModel, + selectUIConfig, +} from "../../redux/slices/configSlice"; const TopDiv = styled.div` outline: 0.5px solid rgba(153, 153, 152); @@ -63,10 +64,10 @@ export default function StepContainerPreActionButtons({ }: StepContainerPreActionButtonsProps) { const [hovering, setHovering] = useState(false); const ideMessenger = useContext(IdeMessengerContext); - const uiConfig = useUIConfig(); - const streamIdRef = useRef(uuidv4()); - const nextCodeBlockIndex = useSelector( - (state: RootState) => state.state.nextCodeBlockToApplyIndex, + const uiConfig = useAppSelector(selectUIConfig); + const streamIdRef = useRef(null); + const nextCodeBlockIndex = useAppSelector( + (state) => state.session.codeBlockApplyStates.curIndex, ); const isBottomToolbarPosition = @@ -75,7 +76,12 @@ export default function StepContainerPreActionButtons({ !isJetBrains() && isTerminalCodeBlock(language, codeBlockContent); const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; - const defaultModel = useSelector(defaultModelSelector); + if (streamIdRef.current === null) { + streamIdRef.current = uuidv4(); + } + + const defaultModel = useAppSelector(selectDefaultModel); + function onClickApply() { if (!defaultModel) { return; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index d96afc7fe..42ee8e048 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -1,10 +1,10 @@ -import { CheckIcon, XMarkIcon, PlayIcon } from "@heroicons/react/24/outline"; -import Spinner from "./Spinner"; -import { lightGray, vscForeground } from "../.."; -import { useState } from "react"; -import { getMetaKeyLabel } from "../../../util"; -import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; +import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; +import { useState } from "react"; +import { lightGray, vscForeground } from "../.."; +import { getMetaKeyLabel } from "../../../util"; +import Spinner from "./Spinner"; +import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; interface ApplyActionsProps { applyState?: ApplyState; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx new file mode 100644 index 000000000..35bc54349 --- /dev/null +++ b/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -0,0 +1,35 @@ +import { CommandLineIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { lightGray, vscForeground } from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; + +interface RunInTerminalButtonProps { + command: string; +} + +export default function RunInTerminalButton({ + command, +}: RunInTerminalButtonProps) { + const ideMessenger = useContext(IdeMessengerContext); + + function runInTerminal() { + void ideMessenger.post("runCommand", { command }); + } + + return ( +
    +
    + <> + + Run + +
    +
    + ); +} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index b147fff2e..61dcfbb3a 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -1,43 +1,32 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { debounce } from "lodash"; -import { useContext, useEffect, useMemo, useRef, useState } from "react"; -import { useSelector } from "react-redux"; -import styled, { css, keyframes } from "styled-components"; +import { useContext, useEffect, useRef, useState } from "react"; +import styled from "styled-components"; import { v4 as uuidv4 } from "uuid"; import { defaultBorderRadius, lightGray, vscEditorBackground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; -import { childrenToText } from "../utils"; +import { childrenToText, isTerminalCodeBlock } from "../utils"; import ApplyActions from "./ApplyActions"; import CopyButton from "./CopyButton"; import FileInfo from "./FileInfo"; import GeneratingCodeLoader from "./GeneratingCodeLoader"; -import { defaultModelSelector } from "../../../redux/selectors/modelSelectors"; +import RunInTerminalButton from "./RunInTerminalButton"; +import { useAppSelector } from "../../../redux/hooks"; +import { selectDefaultModel } from "../../../redux/slices/configSlice"; +import { + selectApplyStateByStreamId, + selectIsInEditMode, +} from "../../../redux/slices/sessionSlice"; -const fadeInAnimation = keyframes` - from { - opacity: 0; - } - to { - opacity: 1; - } -`; - -const TopDiv = styled.div<{ active?: boolean }>` +const TopDiv = styled.div` outline: 1px solid rgba(153, 153, 152); outline-offset: -0.5px; border-radius: ${defaultBorderRadius}; margin-bottom: 8px !important; background-color: ${vscEditorBackground}; min-width: 0; - ${(props) => - props.active - ? "animation: none;" - : css` - animation: ${fadeInAnimation} 300ms ease-out forwards; - `} `; const ToolbarDiv = styled.div<{ isExpanded: boolean }>` @@ -60,6 +49,8 @@ export interface StepContainerPreToolbarProps { codeBlockIndex: number; // To track which codeblock we are applying range?: string; children: any; + expanded?: boolean; + hideApply?: boolean; } export default function StepContainerPreToolbar( @@ -68,38 +59,35 @@ export default function StepContainerPreToolbar( const ideMessenger = useContext(IdeMessengerContext); const streamIdRef = useRef(uuidv4()); const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); - const isInEditMode = useSelector( - (state: RootState) => state.editModeState.isInEditMode, + const isInEditMode = useAppSelector(selectIsInEditMode); + const [isExpanded, setIsExpanded] = useState( + props.expanded ?? (isInEditMode ? false : true), ); - const active = useSelector((state: RootState) => state.state.active); - const [isExpanded, setIsExpanded] = useState(isInEditMode ? false : true); const [codeBlockContent, setCodeBlockContent] = useState(""); - const isChatActive = useSelector((state: RootState) => state.state.active); + const isStreaming = useAppSelector((state) => state.session.isStreaming); - const nextCodeBlockIndex = useSelector( - (state: RootState) => state.state.nextCodeBlockToApplyIndex, + const nextCodeBlockIndex = useAppSelector( + (state) => state.session.codeBlockApplyStates.curIndex, ); - const applyStates = useSelector( - (store: RootState) => store.state.applyStates, + const applyState = useAppSelector((state) => + selectApplyStateByStreamId(state, streamIdRef.current), ); - const applyState = useMemo(() => { - return applyStates.find((state) => state.streamId === streamIdRef.current); - }, [applyStates, streamIdRef]); // This handles an edge case when the last node in the markdown syntax tree is a codeblock. // In this scenario, `isGeneratingCodeBlock` is never set to false since we determine if // we are done generating based on whether the next node in the tree is not a codeblock. // The tree parsing logic for Remark is defined on page load, so we can't access state // during the actual tree parsing. - const isGeneratingCodeBlock = !isChatActive + const isGeneratingCodeBlock = !isStreaming ? false : props.isGeneratingCodeBlock; const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; const hasFileExtension = /\.[0-9a-z]+$/i.test(props.filepath); - const defaultModel = useSelector(defaultModelSelector); + const defaultModel = useAppSelector(selectDefaultModel); + function onClickApply() { if (!defaultModel) { return; @@ -139,6 +127,7 @@ export default function StepContainerPreToolbar( useEffect(() => { const hasCompletedGenerating = wasGeneratingRef.current && !isGeneratingCodeBlock; + const shouldAutoApply = hasCompletedGenerating && isInEditMode; if (shouldAutoApply) { @@ -173,7 +162,7 @@ export default function StepContainerPreToolbar( } return ( - +
    - + {props.hideApply || + (isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( + + ) : ( + + ))} )}
    diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 6afb7c09d..1f7246cba 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,9 +1,10 @@ -import { memo, useCallback, useEffect, useMemo, useRef } from "react"; +import { SymbolWithRange } from "core"; +import { ctxItemToRifWithContents } from "core/commands/util"; +import { memo, useEffect, useRef } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; import remarkMath from "remark-math"; -import remarkGfm from "remark-gfm"; import styled from "styled-components"; import { visit } from "unist-util-visit"; import { @@ -13,20 +14,17 @@ import { vscForeground, } from ".."; import { getFontSize, isJetBrains } from "../../util"; +import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; -import { ctxItemToRifWithContents } from "core/commands/util"; -import FilenameLink from "./FilenameLink"; -import StepContainerPreToolbar from "./StepContainerPreToolbar"; -import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import StepContainerPreActionButtons from "./StepContainerPreActionButtons"; -import { patchNestedMarkdown } from "./utils/patchNestedMarkdown"; -import { RootState } from "../../redux/store"; -import { ContextItemWithId, SymbolWithRange } from "core"; +import StepContainerPreToolbar from "./StepContainerPreToolbar"; import SymbolLink from "./SymbolLink"; -import { useSelector } from "react-redux"; import useUpdatingRef from "../../hooks/useUpdatingRef"; import { remarkTables } from "./utils/remarkTables"; +import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; +import { patchNestedMarkdown } from "./utils/patchNestedMarkdown"; +import { useAppSelector } from "../../redux/hooks"; const StyledMarkdown = styled.div<{ fontSize?: number; @@ -161,13 +159,13 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( // The refs are a workaround because rehype options are stored on initiation // So they won't use the most up-to-date state values // So in this case we just put them in refs - const contextItems = useSelector( - (state: RootState) => - state.state.history[props.itemIndex - 1]?.contextItems, + const contextItems = useAppSelector( + (state) => state.session.history[props.itemIndex - 1]?.contextItems, ); const contextItemsRef = useUpdatingRef(contextItems); - const symbols = useSelector((state: RootState) => state.state.symbols); + const symbols = useAppSelector((state) => state.session.symbols); + const symbolsRef = useRef([]); useEffect(() => { // Note, before I was only looking for symbols that matched @@ -267,9 +265,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const content = getCodeChildrenContent(codeProps.children); if (content && contextItemsRef.current) { - const ctxItem = contextItemsRef.current.find((ctxItem) => - ctxItem.uri?.value.includes(content), + const ctxItem = contextItemsRef.current.find( + (ctxItem) => + ctxItem.uri?.value.includes(content) && + ctxItem.uri.type === "file", ); + if (ctxItem) { const rif = ctxItemToRifWithContents(ctxItem); return ; diff --git a/gui/src/components/markdown/SyntaxHighlightedPre.tsx b/gui/src/components/markdown/SyntaxHighlightedPre.tsx index a3caba685..6e2be08f2 100644 --- a/gui/src/components/markdown/SyntaxHighlightedPre.tsx +++ b/gui/src/components/markdown/SyntaxHighlightedPre.tsx @@ -1,6 +1,6 @@ import { useContext } from "react"; import styled from "styled-components"; -import { vscForeground, defaultBorderRadius } from ".."; +import { defaultBorderRadius, vscForeground } from ".."; import { VscThemeContext } from "../../context/VscTheme"; const generateThemeStyles = (theme: any) => { diff --git a/gui/src/components/modelSelection/ModelCard.tsx b/gui/src/components/modelSelection/ModelCard.tsx index 85658d173..2c34bdc51 100644 --- a/gui/src/components/modelSelection/ModelCard.tsx +++ b/gui/src/components/modelSelection/ModelCard.tsx @@ -175,7 +175,10 @@ function ModelCard(props: ModelCardProps) { <>
    - +

    {dimension.name}

    @@ -204,6 +207,7 @@ function ModelCard(props: ModelCardProps) {
    ` `} `; -const IconBase = styled.div<{ hovered: boolean }>` +const IconBase = styled.div<{ $hovered: boolean }>` width: 1.2em; height: 1.2em; cursor: pointer; padding: 4px; border-radius: ${defaultBorderRadius}; - opacity: ${(props) => (props.hovered ? 0.75 : 0)}; - visibility: ${(props) => (props.hovered ? "visible" : "hidden")}; + opacity: ${(props) => (props.$hovered ? 0.75 : 0)}; + visibility: ${(props) => (props.$hovered ? "visible" : "hidden")}; &:hover { opacity: 1; @@ -204,9 +203,9 @@ function ModelOption({
    - + {showDelete && ( - + )}
    @@ -217,17 +216,15 @@ function ModelOption({ function ModelSelect() { const dispatch = useDispatch(); - const defaultModel = useSelector(defaultModelSelector); - const allModels = useSelector( - (state: RootState) => state.state.config.models, - ); + const defaultModel = useAppSelector(selectDefaultModel); + const allModels = useAppSelector((state) => state.config.config.models); const ideMessenger = useContext(IdeMessengerContext); const [showAbove, setShowAbove] = useState(false); const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); - const selectedProfileId = useSelector( - (store: RootState) => store.state.selectedProfileId, + const selectedProfileId = useAppSelector( + (store) => store.session.selectedProfileId, ); // Sort so that options without an API key are at the end diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 8e63d5059..8653b360a 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -1,4 +1,3 @@ -// AuthContext.tsx import React, { createContext, useContext, @@ -7,16 +6,16 @@ import React, { useMemo, } from "react"; import { ControlPlaneSessionInfo } from "core/control-plane/client"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import ConfirmationDialog from "../components/dialogs/ConfirmationDialog"; import { IdeMessengerContext } from "./IdeMessenger"; -import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice"; +import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import { RootState } from "../redux/store"; import { ProfileDescription } from "core/config/ProfileLifecycleManager"; import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice"; import { useWebviewListener } from "../hooks/useWebviewListener"; import AccountDialog from "../components/AccountDialog"; +import { useAppSelector } from "../redux/hooks"; interface AuthContextType { session: ControlPlaneSessionInfo | undefined; @@ -36,8 +35,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ undefined, ); const [profiles, setProfiles] = useState([]); - const selectedProfileId = useSelector( - (store: RootState) => store.state.selectedProfileId, + const selectedProfileId = useAppSelector( + (store) => store.session.selectedProfileId, ); const selectedProfile = useMemo(() => { return profiles.find((p) => p.id === selectedProfileId); @@ -46,8 +45,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); - const lastControlServerBetaEnabledStatus = useSelector( - (state: RootState) => state.misc.lastControlServerBetaEnabledStatus, + const lastControlServerBetaEnabledStatus = useAppSelector( + (state) => state.misc.lastControlServerBetaEnabledStatus, ); const login = () => { diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index c5c4f9b3e..bddd3fbbe 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -156,7 +156,7 @@ export class IdeMessenger implements IIdeMessenger { this.post(messageType, data, messageId); - let buffer = ""; + const buffer: any[] = []; let index = 0; let done = false; let returnVal = undefined; @@ -169,7 +169,7 @@ export class IdeMessenger implements IIdeMessenger { done = true; returnVal = responseData; } else { - buffer += responseData.content; + buffer.push(responseData.content); } } }; @@ -181,16 +181,16 @@ export class IdeMessenger implements IIdeMessenger { while (!done) { if (buffer.length > index) { - const chunk = buffer.slice(index); - index = buffer.length; + const chunk = buffer[index]; + index++; yield chunk; } await new Promise((resolve) => setTimeout(resolve, 50)); } - if (buffer.length > index) { - const chunk = buffer.slice(index); - index = buffer.length; + while (buffer.length > index) { + const chunk = buffer[index]; + index++; yield chunk; } @@ -215,7 +215,7 @@ export class IdeMessenger implements IIdeMessenger { let next = await gen.next(); while (!next.done) { - yield { role: "user", content: next.value }; + yield next.value; next = await gen.next(); } diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx index f080792f5..b9cbe3bc7 100644 --- a/gui/src/context/SubmenuContextProviders.tsx +++ b/gui/src/context/SubmenuContextProviders.tsx @@ -7,12 +7,18 @@ import { groupByLastNPathParts, } from "core/util"; import MiniSearch, { SearchResult } from "minisearch"; -import { useCallback, useContext, useEffect, useMemo, useState } from "react"; -import { useSelector } from "react-redux"; +import { + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; import { IdeMessengerContext } from "./IdeMessenger"; import { selectContextProviderDescriptions } from "../redux/selectors"; -import { RootState } from "../redux/store"; import { useWebviewListener } from "../hooks/useWebviewListener"; +import { useAppSelector } from "../redux/hooks"; const MINISEARCH_OPTIONS = { prefix: true, @@ -41,6 +47,19 @@ const initialContextProviders: SubtextContextProvidersContextType = { const SubmenuContextProvidersContext = createContext(initialContextProviders); +function isOpenFilesChanged( + newFiles: { id: string }[], + oldFiles: { id: string }[], +) { + if (newFiles.length > oldFiles.length) { + return true; + } + for (let i = 0; i < newFiles.length; ++i) { + if (newFiles[i].id !== oldFiles[i].id) return true; + } + return false; +} + export const SubmenuContextProvidersProvider = ({ children, }: { @@ -53,17 +72,19 @@ export const SubmenuContextProvidersProvider = ({ [id: string]: ContextSubmenuItem[]; }>({}); - const contextProviderDescriptions = useSelector( + const contextProviderDescriptions = useAppSelector( selectContextProviderDescriptions, ); - const disableIndexing = useSelector( - (store: RootState) => store.state.config.disableIndexing, + const disableIndexing = useAppSelector( + (store) => store.config.config.disableIndexing, ); const [initialLoadComplete, setInitialLoadComplete] = useState(false); const [isLoading, setIsLoading] = useState(false); const [autoLoadTriggered, setAutoLoadTriggered] = useState(false); + const config = useAppSelector((store) => store.config.config); + const ideMessenger = useContext(IdeMessengerContext); const getOpenFilesItems = useCallback(async () => { @@ -122,18 +143,22 @@ export const SubmenuContextProvidersProvider = ({ [minisearches], ); + const lastOpenFilesRef = useRef([]); useEffect(() => { let isMounted = true; const refreshOpenFiles = async () => { if (!isMounted) return; const openFiles = await getOpenFilesItems(); - setFallbackResults((prev) => ({ - ...prev, - file: deduplicateArray( - [...openFiles, ...(Array.isArray(prev.file) ? prev.file : [])], - (a, b) => a.id === b.id, - ), - })); + if (isOpenFilesChanged(openFiles, lastOpenFilesRef.current)) { + setFallbackResults((prev) => ({ + ...prev, + file: deduplicateArray( + [...openFiles, ...(Array.isArray(prev.file) ? prev.file : [])], + (a, b) => a.id === b.id, + ), + })); + lastOpenFilesRef.current = openFiles; + } }; const interval = setInterval(refreshOpenFiles, 2000); diff --git a/gui/src/editorInset/EditorInset.tsx b/gui/src/editorInset/EditorInset.tsx index 8ba56f97b..c06661971 100644 --- a/gui/src/editorInset/EditorInset.tsx +++ b/gui/src/editorInset/EditorInset.tsx @@ -1,12 +1,12 @@ import { useContext, useEffect, useRef } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import styled from "styled-components"; import { defaultBorderRadius } from "../components"; import TipTapEditor from "../components/mainInput/TipTapEditor"; import { IdeMessengerContext } from "../context/IdeMessenger"; import useSetup from "../hooks/useSetup"; import { selectSlashCommandComboBoxInputs } from "../redux/selectors"; -import { RootState } from "../redux/store"; +import { useAppSelector } from "../redux/hooks"; const EditorInsetDiv = styled.div` max-width: 500px; @@ -18,9 +18,11 @@ const EditorInsetDiv = styled.div` function EditorInset() { const dispatch = useDispatch(); - const availableSlashCommands = useSelector(selectSlashCommandComboBoxInputs); - const availableContextProviders = useSelector( - (store: RootState) => store.state.config.contextProviders, + const availableSlashCommands = useAppSelector( + selectSlashCommandComboBoxInputs, + ); + const availableContextProviders = useAppSelector( + (store) => store.config.config.contextProviders, ); useSetup(dispatch); diff --git a/gui/src/forms/AddModelForm.tsx b/gui/src/forms/AddModelForm.tsx index fdb7faf77..41f88e969 100644 --- a/gui/src/forms/AddModelForm.tsx +++ b/gui/src/forms/AddModelForm.tsx @@ -11,9 +11,9 @@ import { ProviderInfo, providers, } from "../pages/AddNewModel/configs/providers"; -import { setDefaultModel } from "../redux/slices/stateSlice"; import { FREE_TRIAL_LIMIT_REQUESTS, hasPassedFTL } from "../util/freeTrial"; import { completionParamsInputs } from "../pages/AddNewModel/configs/completionParamsInputs"; +import { setDefaultModel } from "../redux/slices/configSlice"; interface QuickModelSetupProps { onDone: () => void; diff --git a/gui/src/hooks/CustomPostHogProvider.tsx b/gui/src/hooks/CustomPostHogProvider.tsx index 592288bb8..5555f8c12 100644 --- a/gui/src/hooks/CustomPostHogProvider.tsx +++ b/gui/src/hooks/CustomPostHogProvider.tsx @@ -1,12 +1,11 @@ import posthog from "posthog-js"; import { PostHogProvider } from "posthog-js/react"; import React, { PropsWithChildren, useEffect } from "react"; -import { useSelector } from "react-redux"; -import { RootState } from "../redux/store"; +import { useAppSelector } from "../redux/hooks"; const CustomPostHogProvider = ({ children }: PropsWithChildren) => { - const allowAnonymousTelemetry = useSelector( - (store: RootState) => store?.state?.config.allowAnonymousTelemetry, + const allowAnonymousTelemetry = useAppSelector( + (store) => store?.config?.config?.allowAnonymousTelemetry, ); const [client, setClient] = React.useState(undefined); diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts deleted file mode 100644 index 06e60102e..000000000 --- a/gui/src/hooks/useChatHandler.ts +++ /dev/null @@ -1,341 +0,0 @@ -import { Dispatch } from "@reduxjs/toolkit"; -import { JSONContent } from "@tiptap/react"; -import { - ChatHistoryItem, - ChatMessage, - ContextItemWithId, - InputModifiers, - MessageContent, - PromptLog, - RangeInFile, - SlashCommandDescription, -} from "core"; -import { constructMessages } from "core/llm/constructMessages"; -import { stripImages } from "core/llm/images"; -import { getBasename, getRelativePath } from "core/util"; -import { usePostHog } from "posthog-js/react"; -import { useEffect, useMemo, useRef, useState } from "react"; -import { useSelector } from "react-redux"; -import resolveEditorContent, { - hasSlashCommandOrContextProvider, -} from "../components/mainInput/resolveInput"; -import { IIdeMessenger } from "../context/IdeMessenger"; -import { defaultModelSelector } from "../redux/selectors/modelSelectors"; -import { - abortStream, - addPromptCompletionPair, - clearLastEmptyResponse, - initNewActiveMessage, - resubmitAtIndex, - setCurCheckpointIndex, - setInactive, - setIsGatheringContext, - setMessageAtIndex, - streamUpdate, -} from "../redux/slices/stateSlice"; -import { resetNextCodeBlockToApplyIndex } from "../redux/slices/stateSlice"; -import { RootState } from "../redux/store"; -import useHistory from "./useHistory"; -import { updateFileSymbolsFromContextItems } from "../util/symbols"; -import { - selectDefaultContextProviders, - selectSlashCommands, -} from "../redux/selectors"; - -function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { - const posthog = usePostHog(); - - const defaultModel = useSelector(defaultModelSelector); - const defaultContextProviders = useSelector(selectDefaultContextProviders); - - const slashCommands = useSelector(selectSlashCommands); - - const history = useSelector((store: RootState) => store.state.history); - const active = useSelector((store: RootState) => store.state.active); - const streamAborter = useSelector( - (store: RootState) => store.state.streamAborter, - ); - const activeRef = useRef(active); - - const { saveSession } = useHistory(dispatch); - const [save, triggerSave] = useState(false); - - useEffect(() => { - saveSession(false); - }, [save]); - - useEffect(() => { - activeRef.current = active; - }, [active]); - - async function _streamNormalInput(messages: ChatMessage[]) { - if (!defaultModel) { - throw new Error("Default model not defined"); - } - const gen = ideMessenger.llmStreamChat( - defaultModel.title, - streamAborter.signal, - messages, - ); - let next = await gen.next(); - while (!next.done) { - if (!activeRef.current) { - dispatch(abortStream()); - break; - } - dispatch(streamUpdate(stripImages((next.value as ChatMessage).content))); - next = await gen.next(); - } - - let returnVal = next.value as PromptLog; - if (returnVal) { - dispatch(addPromptCompletionPair([returnVal])); - } - } - - const getSlashCommandForInput = ( - input: MessageContent, - ): [SlashCommandDescription, string] | undefined => { - let slashCommand: SlashCommandDescription | undefined; - let slashCommandName: string | undefined; - - let lastText = - typeof input === "string" - ? input - : input.filter((part) => part.type === "text").slice(-1)[0]?.text || ""; - - if (lastText.startsWith("/")) { - slashCommandName = lastText.split(" ")[0].substring(1); - slashCommand = slashCommands.find( - (command) => command.name === slashCommandName, - ); - } - if (!slashCommand || !slashCommandName) { - return undefined; - } - - // Convert to actual slash command object with runnable function - return [slashCommand, stripImages(input)]; - }; - - async function _streamSlashCommand( - messages: ChatMessage[], - slashCommand: SlashCommandDescription, - input: string, - historyIndex: number, - selectedCode: RangeInFile[], - contextItems: ContextItemWithId[], - ) { - if (!defaultModel) { - throw new Error("Default model not defined"); - } - - const modelTitle = defaultModel.title; - - const checkActiveInterval = setInterval(() => { - if (!activeRef.current) { - dispatch(abortStream()); - clearInterval(checkActiveInterval); - } - }, 100); - - try { - for await (const update of ideMessenger.streamRequest( - "command/run", - { - input, - history: messages, - modelTitle, - slashCommandName: slashCommand.name, - contextItems, - params: slashCommand.params, - historyIndex, - selectedCode, - }, - streamAborter.signal, - )) { - if (!activeRef.current) { - dispatch(abortStream()); - clearInterval(checkActiveInterval); - break; - } - if (typeof update === "string") { - dispatch(streamUpdate(update)); - } - } - } catch (e) { - throw e; - } finally { - clearInterval(checkActiveInterval); - } - } - - async function streamResponse( - editorState: JSONContent, - modifiers: InputModifiers, - ideMessenger: IIdeMessenger, - index?: number, - promptPreamble?: string, - ) { - try { - if (typeof index === "number") { - dispatch(resubmitAtIndex({ index, editorState })); - } else { - dispatch(initNewActiveMessage({ editorState })); - } - - // Reset current code block index - dispatch(resetNextCodeBlockToApplyIndex()); - - if (index) { - dispatch(setCurCheckpointIndex(Math.floor(index / 2))); - } - - const shouldGatherContext = - modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState); - - if (shouldGatherContext) { - dispatch( - setIsGatheringContext({ - isGathering: true, - gatheringMessage: "Gathering Context", - }), - ); - } - - // Resolve context providers and construct new history - let [selectedContextItems, selectedCode, content] = - await resolveEditorContent( - editorState, - modifiers, - ideMessenger, - defaultContextProviders, - dispatch, - ); - - // Automatically use currently open file - if (!modifiers.noContext) { - const usingFreeTrial = defaultModel?.provider === "free-trial"; - - const currentFile = await ideMessenger.ide.getCurrentFile(); - if (currentFile) { - let currentFileContents = currentFile.contents; - if (usingFreeTrial) { - currentFileContents = currentFile.contents - .split("\n") - .slice(0, 1000) - .join("\n"); - } - if ( - !selectedContextItems.find( - (item) => item.uri?.value === currentFile.path, - ) - ) { - // don't add the file if it's already in the context items - selectedContextItems.unshift({ - content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath( - currentFile.path, - await ideMessenger.ide.getWorkspaceDirs(), - )}\n${currentFileContents}\n\`\`\``, - name: `Active file: ${getBasename(currentFile.path)}`, - description: currentFile.path, - id: { - itemId: currentFile.path, - providerTitle: "file", - }, - uri: { - type: "file", - value: currentFile.path, - }, - }); - } - } - } - - await updateFileSymbolsFromContextItems( - selectedContextItems, - ideMessenger, - dispatch, - ); - if (promptPreamble) { - if (typeof content === "string") { - content = promptPreamble + content; - } else { - content[0].text = promptPreamble + content[0].text; - } - } - - const message: ChatMessage = { - role: "user", - content, - }; - - const historyItem: ChatHistoryItem = { - message, - contextItems: selectedContextItems, - editorState, - }; - - let newHistory: ChatHistoryItem[] = [ - ...history.slice(0, index), - historyItem, - ]; - const historyIndex = index || newHistory.length - 1; - dispatch( - setMessageAtIndex({ - message, - index: historyIndex, - contextItems: selectedContextItems, - }), - ); - - // TODO: hacky way to allow rerender - await new Promise((resolve) => setTimeout(resolve, 0)); - - posthog.capture("step run", { - step_name: "User Input", - params: {}, - }); - posthog.capture("userInput", {}); - - const messages = constructMessages(newHistory, defaultModel.model); - - // Determine if the input is a slash command - let commandAndInput = getSlashCommandForInput(content); - - if (!commandAndInput) { - await _streamNormalInput(messages); - } else { - const [slashCommand, commandInput] = commandAndInput; - - let updatedContextItems = []; - - posthog.capture("step run", { - step_name: slashCommand.name, - params: {}, - }); - - await _streamSlashCommand( - messages, - slashCommand, - commandInput, - historyIndex, - selectedCode, - updatedContextItems, - ); - } - } catch (e: any) { - dispatch(clearLastEmptyResponse()); - console.debug("Error streaming response: ", e); - } finally { - dispatch(setInactive()); - triggerSave(!save); - } - } - - return { - streamResponse, - }; -} - -export default useChatHandler; diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index e477dfba9..415e8bffc 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -1,14 +1,12 @@ import { Dispatch } from "@reduxjs/toolkit"; import { Session, SessionMetadata } from "core"; - -import { stripImages } from "core/llm/images"; +import { renderChatMessage } from "core/util/messageContent"; import { useCallback, useContext } from "react"; -import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { useLastSessionContext } from "../context/LastSessionContext"; -import { newSession, updateSessionTitle } from "../redux/slices/stateSlice"; -import { RootState } from "../redux/store"; +import { newSession, updateSessionTitle } from "../redux/slices/sessionSlice"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; +import { useAppSelector } from "../redux/hooks"; const MAX_TITLE_LENGTH = 100; @@ -20,13 +18,10 @@ function truncateText(text: string, maxLength: number) { } function useHistory(dispatch: Dispatch) { - const sessionId = useSelector((store: RootState) => store.state.sessionId); - const config = useSelector((store: RootState) => store.state.config); - const history = useSelector((store: RootState) => store.state.history); - const checkpoints = useSelector( - (store: RootState) => store.state.checkpoints, - ); - const title = useSelector((store: RootState) => store.state.title); + const sessionId = useAppSelector((store) => store.session.id); + const config = useAppSelector((store) => store.config.config); + const history = useAppSelector((store) => store.session.history); + const title = useAppSelector((store) => store.session.title); const ideMessenger = useContext(IdeMessengerContext); const { lastSessionId, setLastSessionId } = useLastSessionContext(); @@ -77,7 +72,7 @@ function useHistory(dispatch: Dispatch) { let newTitle = currentTitle === "New Session" ? truncateText( - stripImages(history[0].message.content) + renderChatMessage(history[0].message) .split("\n") .filter((l) => l.trim() !== "") .slice(-1)[0] || "", @@ -92,7 +87,6 @@ function useHistory(dispatch: Dispatch) { title: newTitle, workspaceDirectory: window.workspacePaths?.[0] || "", history, - checkpoints, }; await ideMessenger.request("history/save", session); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index e1c1e103e..da02306fd 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,31 +1,30 @@ -import { Dispatch } from "@reduxjs/toolkit"; import { useCallback, useContext, useEffect, useRef } from "react"; -import { useSelector } from "react-redux"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; -import { setVscMachineId } from "../redux/slices/configSlice"; -import { - addContextItemsAtIndex, - setConfig, - setConfigError, - setInactive, - setSelectedProfileId, - setTTSActive, - updateDocsSuggestions, - updateIndexingStatus, -} from "../redux/slices/stateSlice"; -import { RootState } from "../redux/store"; +import { AppDispatch } from "../redux/store"; +import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { isJetBrains } from "../util"; import { setLocalStorage } from "../util/localStorage"; -import useChatHandler from "./useChatHandler"; -import { useWebviewListener } from "./useWebviewListener"; import { updateFileSymbolsFromContextItems } from "../util/symbols"; +import { useWebviewListener } from "./useWebviewListener"; +import { useAppSelector } from "../redux/hooks"; +import { setConfig, setConfigError } from "../redux/slices/configSlice"; +import { updateIndexingStatus } from "../redux/slices/indexingSlice"; +import { updateDocsSuggestions } from "../redux/slices/miscSlice"; +import { + setSelectedProfileId, + setInactive, + addContextItemsAtIndex, +} from "../redux/slices/sessionSlice"; +import { setTTSActive } from "../redux/slices/uiSlice"; -function useSetup(dispatch: Dispatch) { +function useSetup(dispatch: AppDispatch) { const ideMessenger = useContext(IdeMessengerContext); - const history = useSelector((store: RootState) => store.state.history); - + const history = useAppSelector((store) => store.session.history); + const defaultModelTitle = useAppSelector( + (store) => store.config.defaultModelTitle, + ); const hasLoadedConfig = useRef(false); const loadConfig = useCallback( async (initial: boolean) => { @@ -81,8 +80,9 @@ function useSetup(dispatch: Dispatch) { ); // Load symbols for chat on any session change - const sessionId = useSelector((store: RootState) => store.state.sessionId); + const sessionId = useAppSelector((state) => state.session.id); const sessionIdRef = useRef(""); + useEffect(() => { if (sessionIdRef.current !== sessionId) { updateFileSymbolsFromContextItems( @@ -110,8 +110,6 @@ function useSetup(dispatch: Dispatch) { (window as any).workspacePaths = msg.workspacePaths; (window as any).vscMachineId = msg.vscMachineId; (window as any).vscMediaUrl = msg.vscMediaUrl; - dispatch(setVscMachineId(msg.vscMachineId)); - // dispatch(setVscMediaUrl(msg.vscMediaUrl)); }); // Save theme colors to local storage for immediate loading in JetBrains @@ -131,8 +129,6 @@ function useSetup(dispatch: Dispatch) { dispatch(updateDocsSuggestions(data)); }); - const { streamResponse } = useChatHandler(dispatch, ideMessenger); - // IDE event listeners useWebviewListener( "getWebviewHistoryLength", @@ -163,10 +159,11 @@ function useSetup(dispatch: Dispatch) { // TODO - remove? useWebviewListener("submitMessage", async (data) => { - streamResponse( - data.message, - { useCodebase: false, noContext: true }, - ideMessenger, + dispatch( + streamResponseThunk({ + editorState: data.message, + modifiers: { useCodebase: false, noContext: true }, + }), ); }); @@ -183,10 +180,6 @@ function useSetup(dispatch: Dispatch) { dispatch(updateIndexingStatus(data)); }); - const defaultModelTitle = useSelector( - (store: RootState) => store.state.defaultModelTitle, - ); - useWebviewListener( "getDefaultModelTitle", async () => { diff --git a/gui/src/hooks/useUIConfig.ts b/gui/src/hooks/useUIConfig.ts deleted file mode 100644 index fc4a25df7..000000000 --- a/gui/src/hooks/useUIConfig.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { useSelector } from "react-redux"; -import { RootState } from "../redux/store"; - -function useUIConfig() { - return useSelector((store: RootState) => store?.state?.config?.ui ?? null); -} - -export default useUIConfig; diff --git a/gui/src/pages/AddNewModel/AddNewModel.tsx b/gui/src/pages/AddNewModel/AddNewModel.tsx index 46ac8fdf2..89212e9e3 100644 --- a/gui/src/pages/AddNewModel/AddNewModel.tsx +++ b/gui/src/pages/AddNewModel/AddNewModel.tsx @@ -13,10 +13,10 @@ import ModelCard from "../../components/modelSelection/ModelCard"; import Toggle from "../../components/modelSelection/Toggle"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { setDefaultModel } from "../../redux/slices/stateSlice"; import { ModelPackage, models } from "./configs/models"; import { providers } from "./configs/providers"; import { CustomModelButton } from "./ConfigureProvider"; +import { setDefaultModel } from "../../redux/slices/configSlice"; const IntroDiv = styled.div` padding: 8px 12px; diff --git a/gui/src/pages/AddNewModel/ConfigureProvider.tsx b/gui/src/pages/AddNewModel/ConfigureProvider.tsx index 55342b51d..33a3366d6 100644 --- a/gui/src/pages/AddNewModel/ConfigureProvider.tsx +++ b/gui/src/pages/AddNewModel/ConfigureProvider.tsx @@ -16,10 +16,10 @@ import ModelCard from "../../components/modelSelection/ModelCard"; import { ModelProviderTag } from "../../components/modelSelection/ModelProviderTag"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { setDefaultModel } from "../../redux/slices/stateSlice"; import { updatedObj } from "../../util"; import type { ProviderInfo } from "./configs/providers"; import { providers } from "./configs/providers"; +import { setDefaultModel } from "../../redux/slices/configSlice"; const GridDiv = styled.div` display: grid; diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index cc668c0c2..4c56dd8a6 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -137,6 +137,31 @@ export const providers: Partial> = { ...completionParamsInputsConfigs, ], }, + "function-network": { + title: "Function Network", + provider: "function-network", + refPage: "function-network", + description: + "Run open-source models on Function Network. Private, Affordable User-Owned AI", + icon: "function-network.png", + longDescription: `Function Network is a private, affordable user-owned AI platform that allows you to run open-source models. Experience bleeding-edge Generative AI models with limitless scalability, all powered by our distributed inference network.`, + tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource], + params: { + apiKey: "", + }, + collectInputFor: [ + { + inputType: "text", + key: "apiKey", + label: "API Key", + placeholder: "Enter your Function Network API key", + required: true, + }, + ...completionParamsInputsConfigs, + ], + packages: [models.llama31Chat, models.deepseek], + apiKeyUrl: "https://function.network/join-waitlist", + }, azure: { title: "Azure OpenAI", provider: "azure", diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx index 1f06f428c..6f39c84cd 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx @@ -10,10 +10,7 @@ import IndexingProgressTitleText from "./IndexingProgressTitleText"; import IndexingProgressSubtext from "./IndexingProgressSubtext"; import { usePostHog } from "posthog-js/react"; import ConfirmationDialog from "../../../components/dialogs/ConfirmationDialog"; -import { - setShowDialog, - setDialogMessage, -} from "../../../redux/slices/uiStateSlice"; +import { setShowDialog, setDialogMessage } from "../../../redux/slices/uiSlice"; import IndexingProgressErrorText from "./IndexingProgressErrorText"; export function getProgressPercentage( diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx index fff7ab9a8..ada887cf3 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressErrorText.tsx @@ -1,17 +1,16 @@ import { IndexingProgressUpdate } from "core"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; -import { useSelector } from "react-redux"; -import { RootState } from "../../../redux/store"; import { isJetBrains } from "../../../util"; import { XCircleIcon } from "@heroicons/react/24/outline"; +import { useAppSelector } from "../../../redux/hooks"; export interface IndexingProgressErrorTextProps { update: IndexingProgressUpdate; } function IndexingProgressErrorText({ update }: IndexingProgressErrorTextProps) { - const embeddingsProvider = useSelector( - (state: RootState) => state.state.config.embeddingsProvider, + const embeddingsProvider = useAppSelector( + (state) => state.config.config.embeddingsProvider, ); const showJbError = diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx index 944fdc917..83abeed11 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx @@ -17,6 +17,7 @@ const STATUS_TO_ICON: Record = { paused: PauseCircleIcon, done: CheckCircleIcon, failed: null, // Since we show an erorr message below + cancelled: null, }; function IndexingProgressIndicator({ update }: IndexingProgressIndicatorProps) { diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx index 6c07babb0..a73148009 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx @@ -15,6 +15,7 @@ const STATUS_TO_SUBTITLE_TEXT: Record< paused: "Click to resume", failed: "Click to retry", disabled: "Click to open config.json and enable indexing (requires reload)", + cancelled: "Click to restart", }; function IndexingProgressSubtext({ diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx index 61d4bbba6..e15ba5713 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressTitleText.tsx @@ -12,6 +12,7 @@ const STATUS_TO_TEXT: Record = { paused: "Indexing paused", failed: "Indexing failed", disabled: "Indexing disabled", + cancelled: "Indexing cancelled", }; function IndexingProgressTitleText({ update }: IndexingProgressTitleTextProps) { diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 81648b41b..5f97f9b31 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -11,7 +11,7 @@ import KeyboardShortcuts from "./KeyboardShortcuts"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; import { useDispatch } from "react-redux"; -import { setOnboardingCard } from "../../redux/slices/uiStateSlice"; +import { setOnboardingCard } from "../../redux/slices/uiSlice"; import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; import IndexingProgress from "./IndexingProgress"; diff --git a/gui/src/pages/config-error/index.tsx b/gui/src/pages/config-error/index.tsx index aa0e22f22..2f1ee934d 100644 --- a/gui/src/pages/config-error/index.tsx +++ b/gui/src/pages/config-error/index.tsx @@ -6,11 +6,11 @@ import { import { useNavigate } from "react-router-dom"; import { vscBackground } from "../../components"; import { ROUTES } from "../../util/navigation"; -import { useConfigError } from "../../redux/hooks"; +import { useAppSelector } from "../../redux/hooks"; export default function ConfigErrorPage() { const navigate = useNavigate(); - const configError = useConfigError(); + const configError = useAppSelector((state) => state.config.configError); const sortedErrors = configError ? [...configError].sort((a, b) => (b.fatal ? 1 : 0) - (a.fatal ? 1 : 0)) diff --git a/gui/src/pages/edit/CodeToEditListItem.tsx b/gui/src/pages/edit/CodeToEditListItem.tsx deleted file mode 100644 index d2cdb638d..000000000 --- a/gui/src/pages/edit/CodeToEditListItem.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import FileIcon from "../../components/FileIcon"; -import { - ChevronDownIcon, - ChevronRightIcon, - XMarkIcon, -} from "@heroicons/react/24/outline"; -import { useState } from "react"; -import StyledMarkdownPreview from "../../components/markdown/StyledMarkdownPreview"; -import { getMarkdownLanguageTagForFile } from "core/util"; -import styled from "styled-components"; -import { CodeToEdit } from "core"; - -export interface CodeToEditListItemProps { - code: CodeToEdit; - onDelete: (codeToEdit: CodeToEdit) => void; - onClickFilename: (codeToEdit: CodeToEdit) => void; -} - -// Easiest method to overwrite the top level styling of the markdown preview -const NoPaddingWrapper = styled.div` - > * { - margin: 0 !important; - padding: 0 !important; - } - - pre { - margin: 0 !important; - padding: 0px 0px 0px 10px !important; - } -`; - -export default function CodeToEditListItem({ - code, - onDelete, - onClickFilename, -}: CodeToEditListItemProps) { - const [showCodeSnippet, setShowCodeSnippet] = useState(false); - - const filepath = code.filepath.split("/").pop() || code.filepath; - let title = filepath; - - if ("range" in code) { - const start = code.range.start.line + 1; - const end = code.range.end.line + 1; - title += - start === end ? ` - Inserting at line ${start}` : ` (${start} - ${end})`; - } - - const source = - "```" + - getMarkdownLanguageTagForFile(code.filepath) + - "\n" + - code.contents + - "\n" + - "```"; - - return ( -
  • setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet)} - > -
    -
    - {showCodeSnippet ? ( - { - e.stopPropagation(); - setShowCodeSnippet(false); - }} - className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 hover:bg-opacity-20" - /> - ) : ( - { - e.stopPropagation(); - setShowCodeSnippet(true); - }} - className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 hover:bg-opacity-20" - /> - )} - - { - e.stopPropagation(); - onClickFilename(code); - }} - > - {title} - -
    -
    - { - e.stopPropagation(); - onDelete(code); - }} - className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 hover:bg-opacity-20" - /> -
    -
    - - {showCodeSnippet && ( -
    - - - -
    - )} -
  • - ); -} diff --git a/gui/src/pages/edit/Edit.tsx b/gui/src/pages/edit/Edit.tsx deleted file mode 100644 index 201a4bc4c..000000000 --- a/gui/src/pages/edit/Edit.tsx +++ /dev/null @@ -1,240 +0,0 @@ -import { ArrowLeftIcon } from "@heroicons/react/24/outline"; -import { Editor, JSONContent } from "@tiptap/core"; -import { InputModifiers, RangeInFileWithContents } from "core"; -import { stripImages } from "core/llm/images"; -import { useCallback, useContext, useEffect, useMemo } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { useNavigate } from "react-router-dom"; -import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; -import resolveEditorContent from "../../components/mainInput/resolveInput"; -import TipTapEditor from "../../components/mainInput/TipTapEditor"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { - clearCodeToEdit, - setEditDone, - submitEdit, -} from "../../redux/slices/editModeState"; -import { RootState } from "../../redux/store"; -import CodeToEdit from "./CodeToEdit"; -import useChatHandler from "../../hooks/useChatHandler"; -import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; -import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import StepContainer from "../../components/StepContainer"; -import getMultifileEditPrompt from "./getMultifileEditPrompt"; -import { selectApplyState } from "../../redux/selectors"; - -const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ - "codebase", - "tree", - "open", - "web", - "diff", - "folder", - "search", - "debugger", - "repo-map", -]; - -export default function Edit() { - const dispatch = useDispatch(); - const navigate = useNavigate(); - const ideMessenger = useContext(IdeMessengerContext); - const { streamResponse } = useChatHandler(dispatch, ideMessenger); - const editModeState = useSelector((state: RootState) => state.editModeState); - const availableContextProviders = useSelector( - (store: RootState) => store.state.config.contextProviders, - ); - - const filteredContextProviders = useMemo(() => { - return ( - availableContextProviders?.filter( - (provider) => - !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), - ) ?? [] - ); - }, [availableContextProviders]); - - const history = useSelector((state: RootState) => state.state.history); - - const applyStates = useSelector( - (state: RootState) => state.state.applyStates, - ); - - const applyState = useSelector(selectApplyState); - - const isSingleRangeEdit = - editModeState.codeToEdit.length === 0 || - (editModeState.codeToEdit.length === 1 && - "range" in editModeState.codeToEdit[0]); - - useEffect(() => { - if (editModeState.editStatus === "done") { - ideMessenger.post("edit/escape", undefined); - navigate("/"); - } - }, [editModeState.editStatus]); - - useEffect(() => { - if (applyState === "closed" && editModeState.editStatus === "accepting") { - dispatch(setEditDone()); - } - }, [applyState, editModeState.editStatus]); - - const pendingApplyStates = applyStates.filter( - (state) => state.status === "done", - ); - - const isStreaming = - editModeState.editStatus === "streaming" || - editModeState.editStatus === "accepting"; - - const toolbarOptions = { - hideAddContext: false, - hideImageUpload: false, - hideUseCodebase: true, - hideSelectModel: false, - enterText: isStreaming ? "Retry" : "Edit", - }; - - const hasPendingApplies = pendingApplyStates.length > 0; - - async function handleSingleRangeEdit( - editorState: JSONContent, - modifiers: InputModifiers, - editor: Editor, - ) { - const [contextItems, __, userInstructions] = await resolveEditorContent( - editorState, - { - noContext: true, - useCodebase: false, - }, - ideMessenger, - [], - dispatch, - ); - - const prompt = [ - ...contextItems.map((item) => item.content), - stripImages(userInstructions), - ].join("\n\n"); - - ideMessenger.post("edit/sendPrompt", { - prompt, - range: editModeState.codeToEdit[0] as RangeInFileWithContents, - }); - - dispatch(submitEdit(prompt)); - editor.commands.selectTextblockEnd(); - } - - async function handleEditorEnter( - editorState: JSONContent, - modifiers: InputModifiers, - editor: Editor, - ) { - if (isSingleRangeEdit) { - handleSingleRangeEdit(editorState, modifiers, editor); - } else { - const promptPreamble = getMultifileEditPrompt(editModeState.codeToEdit); - - streamResponse( - editorState, - modifiers, - ideMessenger, - undefined, - promptPreamble, - ); - } - } - - function handleBackClick() { - dispatch(setEditDone()); - } - - const isLastUserInput = useCallback( - (index: number): boolean => { - return !history - .slice(index + 1) - .some((entry) => entry.message.role === "user"); - }, - [history], - ); - - return ( -
    -
    -
    - - -
    - - {!isSingleRangeEdit && history.length > 1 && ( -
    - {history.slice(1).map((item, index: number) => ( -
    - {item.message.role === "user" ? ( - { - streamResponse( - editorState, - modifiers, - ideMessenger, - index, - ); - }} - isLastUserInput={isLastUserInput(index)} - isMainInput={false} - editorState={item.editorState} - contextItems={item.contextItems} - /> - ) : ( - - )} -
    - ))} - - {/* {!active && ( - - )} */} -
    - )} - -
    - {hasPendingApplies && isSingleRangeEdit && ( - dispatch(clearCodeToEdit())} - /> - )} - - {!hasPendingApplies && isSingleRangeEdit && ( - - - Back to Chat - - )} -
    -
    -
    - ); -} diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx deleted file mode 100644 index d1c8752c8..000000000 --- a/gui/src/pages/edit/index.tsx +++ /dev/null @@ -1 +0,0 @@ -export { default } from "./Edit"; diff --git a/gui/src/pages/error.tsx b/gui/src/pages/error.tsx index d00dd533d..96171886a 100644 --- a/gui/src/pages/error.tsx +++ b/gui/src/pages/error.tsx @@ -1,6 +1,6 @@ import { useDispatch } from "react-redux"; import { useNavigate, useRouteError } from "react-router-dom"; -import { newSession } from "../redux/slices/stateSlice"; +import { newSession } from "../redux/slices/sessionSlice"; import { GithubIcon } from "../components/svg/GithubIcon"; import { DiscordIcon } from "../components/svg/DiscordIcon"; import { useContext, useEffect, useState } from "react"; @@ -31,12 +31,12 @@ const ErrorPage: React.FC = () => { }, 500); }, []); return ( -
    +

    Error in Continue UI

    -
    -        {error.statusText || error.message}
    -      
    + + {error.statusText || error.message} + @@ -120,24 +129,38 @@ function fallbackRender({ error, resetErrorBoundary }: any) { export function Chat() { const posthog = usePostHog(); - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const { streamResponse } = useChatHandler(dispatch, ideMessenger); const onboardingCard = useOnboardingCard(); const { showTutorialCard, closeTutorialCard } = useTutorialCard(); - const defaultModel = useSelector(defaultModelSelector); - const ttsActive = useSelector((state: RootState) => state.state.ttsActive); - const active = useSelector((state: RootState) => state.state.active); + const defaultModel = useAppSelector(selectDefaultModel); + const ttsActive = useAppSelector((state) => state.ui.ttsActive); + const active = useAppSelector((state) => state.session.isStreaming); const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); const mainTextInputRef = useRef(null); const stepsDivRef = useRef(null); const [isAtBottom, setIsAtBottom] = useState(false); - const history = useSelector((store: RootState) => store.state.history); - const showChatScrollbar = useSelector( - (store: RootState) => store.state.config?.ui?.showChatScrollbar, + const history = useAppSelector((state) => state.session.history); + const showChatScrollbar = useAppSelector( + (state) => state.config.config.ui?.showChatScrollbar, ); const { saveSession, getLastSessionId, loadLastSession } = useHistory(dispatch); + const codeToEdit = useAppSelector((state) => state.session.codeToEdit); + const toolCallState = useSelector( + selectCurrentToolCall, + ); + const applyStates = useAppSelector( + (state) => state.session.codeBlockApplyStates.states, + ); + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); + const hasPendingApplies = pendingApplyStates.length > 0; + const isInEditMode = useAppSelector(selectIsInEditMode); + const isSingleRangeEditOrInsertion = useAppSelector( + selectIsSingleRangeEditOrInsertion, + ); const snapToBottom = useCallback(() => { if (!stepsDivRef.current) return; @@ -158,6 +181,10 @@ export function Chat() { setIsAtBottom(true); }, [stepsDivRef, setIsAtBottom]); + const returnToLastSessionButtonText = isInEditMode + ? "Back to Chat" + : "Last Session"; + useEffect(() => { if (active) snapToBottom(); }, [active, snapToBottom]); @@ -176,7 +203,7 @@ export function Chat() { isMetaEquivalentKeyPressed(e) && !e.shiftKey ) { - dispatch(setInactive()); + // dispatch(cancelGeneration()); TODO!!! } }; window.addEventListener("keydown", listener); @@ -201,7 +228,7 @@ export function Chat() { const { widget, highlights } = useFindWidget(stepsDivRef); const sendInput = useCallback( - (editorState: JSONContent, modifiers: InputModifiers) => { + (editorState: JSONContent, modifiers: InputModifiers, editor: Editor) => { if (defaultModel?.provider === "free-trial") { const u = getLocalStorage("ftc"); if (u) { @@ -221,71 +248,25 @@ export function Chat() { } } - streamResponse(editorState, modifiers, ideMessenger); + if (isSingleRangeEditOrInsertion) { + handleSingleRangeEditOrInsertion(editorState); + return; + } + + editor.commands.clearContent(true); + + const promptPreamble = isInEditMode + ? getMultifileEditPrompt(codeToEdit) + : undefined; + + dispatch(streamResponseThunk({ editorState, modifiers, promptPreamble })); // Increment localstorage counter for popup const currentCount = getLocalStorage("mainTextEntryCounter"); if (currentCount) { setLocalStorage("mainTextEntryCounter", currentCount + 1); if (currentCount === 300) { - dispatch( - setDialogMessage( -
    - 👋 Thanks for using Continue. We are always trying to improve - and love hearing from users. If you're interested in speaking, - enter your name and email. We won't use this information for - anything other than reaching out. -
    -
    -
    { - e.preventDefault(); - posthog?.capture("user_interest_form", { - name: e.target.elements[0].value, - email: e.target.elements[1].value, - }); - dispatch( - setDialogMessage( -
    - Thanks! We'll be in touch soon. -
    , - ), - ); - }} - style={{ - display: "flex", - flexDirection: "column", - gap: "10px", - }} - > - - - -
    -
    , - ), - ); + dispatch(setDialogMessage()); dispatch(setDialogEntryOn(false)); dispatch(setShowDialog(true)); } @@ -293,14 +274,46 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [history, defaultModel, streamResponse], + [ + history, + defaultModel, + streamResponse, + isSingleRangeEditOrInsertion, + codeToEdit, + ], ); + async function handleSingleRangeEditOrInsertion(editorState: JSONContent) { + const [contextItems, __, userInstructions] = await resolveEditorContent( + editorState, + { + noContext: true, + useCodebase: false, + }, + ideMessenger, + [], + dispatch, + ); + + const prompt = [ + ...contextItems.map((item) => item.content), + stripImages(userInstructions), + ].join("\n\n"); + + ideMessenger.post("edit/sendPrompt", { + prompt, + range: codeToEdit[0] as RangeInFileWithContents, + }); + + dispatch(submitEdit(prompt)); + } + useWebviewListener( "newSession", async () => { saveSession(); mainTextInputRef.current?.focus?.(); + dispatch(exitEditMode()); }, [saveSession], ); @@ -314,9 +327,7 @@ export function Chat() { [history], ); - const showScrollbar = useMemo(() => { - return showChatScrollbar ?? window.innerHeight > 5000; - }, [showChatScrollbar]); + const showScrollbar = showChatScrollbar || window.innerHeight > 5000; return ( <> @@ -328,7 +339,12 @@ export function Chat() { > {highlights} {history.map((item, index: number) => ( - +
    { @@ -336,15 +352,37 @@ export function Chat() { }} > {item.message.role === "user" ? ( - { - streamResponse(editorState, modifiers, ideMessenger, index); - }} - isLastUserInput={isLastUserInput(index)} - isMainInput={false} - editorState={item.editorState} + <> + {isInEditMode && index === 0 && } + + + ) : item.message.role === "tool" ? ( + + ) : item.message.role === "assistant" && + item.message.toolCalls && + item.toolCallState ? ( +
    + {item.message.toolCalls?.map((toolCall, i) => { + return ( +
    + +
    + ); + })} +
    ) : (
    )} - +
    ))} )}
    - { - sendInput(editorContent, modifiers); - }} - /> + + {toolCallState?.status === "generated" && } + + {isInEditMode && history.length === 0 && } + + {isInEditMode && history.length > 0 ? null : ( + + )} +
    - {history.length === 0 && getLastSessionId() ? ( + {history.length === 0 && + getLastSessionId() && + !hasPendingApplies ? (
    { loadLastSession().catch((e) => console.error(`Failed to load last session: ${e}`), ); + + if (isInEditMode) { + dispatch(exitEditMode()); + } }} className="flex items-center gap-2" > - Last Session + {returnToLastSessionButtonText}
    ) : null} @@ -445,6 +496,19 @@ export function Chat() {
    + {hasPendingApplies && isSingleRangeEditOrInsertion && ( + { + loadLastSession().catch((e) => + console.error(`Failed to load last session: ${e}`), + ); + + dispatch(exitEditMode()); + }} + /> + )} + {history.length === 0 && ( <> {onboardingCard.show && ( diff --git a/gui/src/pages/gui/ConfigError.tsx b/gui/src/pages/gui/ConfigError.tsx index ff8d306ef..8bab2c3c9 100644 --- a/gui/src/pages/gui/ConfigError.tsx +++ b/gui/src/pages/gui/ConfigError.tsx @@ -1,14 +1,11 @@ import { useLocation, useNavigate } from "react-router-dom"; import HeaderButtonWithToolTip from "../../components/gui/HeaderButtonWithToolTip"; -import { useSelector } from "react-redux"; import { ROUTES } from "../../util/navigation"; -import { RootState } from "../../redux/store"; import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; +import { useAppSelector } from "../../redux/hooks"; const ConfigErrorIndicator = () => { - const configError = useSelector( - (store: RootState) => store.state.configError, - ); + const configError = useAppSelector((store) => store.config.configError); const navigate = useNavigate(); const { pathname } = useLocation(); diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx new file mode 100644 index 000000000..dd0380066 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -0,0 +1,15 @@ +import { getMarkdownLanguageTagForFile } from "core/util"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; + +interface CreateFileToolCallProps { + filepath: string; + fileContents: string; +} + +export function CreateFile(props: CreateFileToolCallProps) { + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.filepath ?? "test.txt")} ${props.filepath}\n${props.fileContents ?? ""}\n\`\`\``; + + return props.filepath ? ( + + ) : null; +} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx new file mode 100644 index 000000000..d55055b03 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -0,0 +1,31 @@ +import { ToolCall, ToolCallState } from "core"; +import { CreateFile } from "./CreateFile"; +import { RunTerminalCommand } from "./RunTerminalCommand"; + +function FunctionSpecificToolCallDiv({ + toolCall, + toolCallState, +}: { + toolCall: ToolCall; + toolCallState: ToolCallState; +}) { + const args = toolCallState.parsedArgs; + + switch (toolCall.function.name) { + case "create_new_file": + return ( + + ); + case "run_terminal_command": + return ( + + ); + default: + return null; + } +} + +export default FunctionSpecificToolCallDiv; diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx new file mode 100644 index 000000000..35fc0e54f --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -0,0 +1,16 @@ +import { ToolCallState } from "core"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; + +interface RunTerminalCommandToolCallProps { + command: string; + toolCallState: ToolCallState; +} + +export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) { + return ( + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx new file mode 100644 index 000000000..e54345c5d --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx @@ -0,0 +1,75 @@ +import { Tool, ToolCall, ToolCallState } from "core"; +import Mustache from "mustache"; +import styled from "styled-components"; +import { useAppSelector } from "../../../redux/hooks"; + +interface ThreadDivProps { + children: React.ReactNode; + icon: React.ReactNode; + toolCall: ToolCall; + toolCallState: ToolCallState; + reactKey: string; +} + +const Container = styled.div` + display: flex; + flex-direction: column; + justify-content: center; + position: relative; + padding: 8px; + padding-bottom: 0; +`; + +const ChildrenDiv = styled.div``; + +const W = 16; + +const HeaderDiv = styled.div` + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 8px; +`; + +export function ThreadDiv(props: ThreadDivProps) { + const availableTools = useAppSelector((state) => state.config.config.tools); + + function renderWouldLikeToMessage( + tool: Tool | undefined, + toolCallState: ToolCallState, + ): string { + if (!tool) return ""; + + const rendered = Mustache.render( + tool.wouldLikeTo, + toolCallState.parsedArgs, + ); + return rendered; + } + + return ( + + +
    + {props.icon} +
    + Continue wants to{" "} + {renderWouldLikeToMessage( + availableTools.find( + (tool) => props.toolCall.function.name === tool.function.name, + ), + props.toolCallState, + )} +
    + {props.children} +
    + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx new file mode 100644 index 000000000..291e15e74 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx @@ -0,0 +1,91 @@ +import { useSelector } from "react-redux"; +import styled from "styled-components"; +import { + defaultBorderRadius, + lightGray, + vscButtonBackground, + vscButtonForeground, +} from "../../../components"; +import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; +import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall"; +import { callTool } from "../../../redux/thunks/callTool"; +import { cancelTool } from "../../../redux/thunks/cancelTool"; +import { useAppDispatch } from "../../../redux/hooks"; + +const ButtonContainer = styled.div` + display: flex; + gap: 8px; + margin-top: 12px; + margin: 8px; +`; + +const Button = styled.button` + padding: 5px; + border-radius: ${defaultBorderRadius}; + flex: 1; + + &:hover { + cursor: pointer; + opacity: 0.8; + } +`; + +const AcceptButton = styled(Button)` + color: ${vscButtonForeground}; + border: none; + background-color: ${vscButtonBackground}; + color: ${vscButtonForeground}; + + &:hover { + cursor: pointer; + } +`; + +const RejectButton = styled(Button)` + color: ${lightGray}; + border: 1px solid ${lightGray}; + background-color: transparent; +`; + +interface ToolCallButtonsProps {} + +export function ToolCallButtons(props: ToolCallButtonsProps) { + const dispatch = useAppDispatch(); + const toolCallState = useSelector(selectCurrentToolCall); + + if (!toolCallState) { + return null; + } + + return ( + <> + + {toolCallState.status === "generating" ? ( +
    + Thinking... +
    + ) : toolCallState.status === "generated" ? ( + <> + dispatch(cancelTool())}> + Cancel + + dispatch(callTool())}> + Continue + + + ) : toolCallState.status === "calling" ? ( +
    + Loading... + +
    + ) : null} +
    + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx new file mode 100644 index 000000000..46057e90c --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx @@ -0,0 +1,24 @@ +import { ContextItemWithId } from "core"; +import ContextItemsPeek from "../../../components/mainInput/ContextItemsPeek"; + +interface ToolOutputProps { + contextItems: ContextItemWithId[]; + toolCallId: string; +} + +function ToolOutput(props: ToolOutputProps) { + if (props.contextItems.length === 0) { + return null; + } + + return ( +
    + +
    + ); +} + +export default ToolOutput; diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx new file mode 100644 index 000000000..e1745c459 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -0,0 +1,46 @@ +import { + ArrowRightIcon, + CheckIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { ToolCall, ToolCallState, ToolStatus } from "core"; +import { vscButtonBackground } from "../../../components"; +import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner"; +import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; +import { ThreadDiv } from "./ThreadDiv"; + +interface ToolCallDivProps { + toolCall: ToolCall; + toolCallState: ToolCallState; + reactKey: string; +} + +export function ToolCallDiv(props: ToolCallDivProps) { + function getIcon(state: ToolStatus) { + switch (state) { + case "generating": + case "calling": + return ; + case "generated": + return ; + case "done": + return ; + case "canceled": + return ; + } + } + + return ( + + + + ); +} diff --git a/gui/src/pages/settings.tsx b/gui/src/pages/settings.tsx deleted file mode 100644 index 613d5f2b1..000000000 --- a/gui/src/pages/settings.tsx +++ /dev/null @@ -1,290 +0,0 @@ -import { ArrowLeftIcon } from "@heroicons/react/24/outline"; -import { ContinueConfig } from "core"; -import { useContext, useEffect } from "react"; -import { FormProvider, useForm } from "react-hook-form"; -import { useDispatch, useSelector } from "react-redux"; -import { useNavigate } from "react-router-dom"; -import styled from "styled-components"; -import { - Button, - Hr, - NumberInput, - TextArea, - lightGray, - vscBackground, - vscForeground, - vscInputBackground, -} from "../components"; -import InfoHover from "../components/InfoHover"; -import Loader from "../components/loaders/Loader"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { RootState } from "../redux/store"; -import { getFontSize, getPlatform } from "../util"; -import { setLocalStorage } from "../util/localStorage"; - -const CancelButton = styled(Button)` - background-color: transparent; - color: ${lightGray}; - border: 1px solid ${lightGray}; - &:hover { - background-color: ${lightGray}; - color: black; - } -`; - -const SaveButton = styled(Button)` - &:hover { - opacity: 0.8; - } -`; - -const Slider = styled.input.attrs({ type: "range" })` - --webkit-appearance: none; - width: 100%; - background-color: ${vscInputBackground}; - outline: none; - border: none; - opacity: 0.7; - -webkit-transition: 0.2s; - transition: opacity 0.2s; - &:hover { - opacity: 1; - } - &::-webkit-slider-runnable-track { - width: 100%; - height: 8px; - cursor: pointer; - background: ${lightGray}; - border-radius: 4px; - } - &::-webkit-slider-thumb { - -webkit-appearance: none; - appearance: none; - width: 8px; - height: 8px; - cursor: pointer; - margin-top: -3px; - } - &::-moz-range-thumb { - width: 8px; - height: 8px; - cursor: pointer; - margin-top: -3px; - } - - &:focus { - outline: none; - border: none; - } -`; - -const ConfigJsonButton = styled(Button)` - padding: 2px 4px; - margin-left: auto; - margin-right: 4px; - background-color: transparent; - color: ${vscForeground}; - border: 1px solid ${lightGray}; - &:hover { - background-color: ${lightGray}; - } -`; - -const ALL_MODEL_ROLES = ["default", "summarize", "edit", "chat"]; - -function Settings() { - const formMethods = useForm(); - const onSubmit = (data: ContinueConfig) => console.log(data); - - const ideMessenger = useContext(IdeMessengerContext); - - const navigate = useNavigate(); - const config = useSelector((state: RootState) => state.state.config); - const dispatch = useDispatch(); - - const submitChanges = () => { - // TODO - // if (!client) return; - // const systemMessage = formMethods.watch("system_message") as - // | string - // | undefined; - // const temperature = formMethods.watch("temperature") as number | undefined; - // // const models = formMethods.watch("models"); - // client.setSystemMessage(systemMessage || ""); - // if (temperature) client.setTemperature(temperature); - // if (models) { - // for (const role of ALL_MODEL_ROLES) { - // if (models[role]) { - // client.setModelForRole(role, models[role] as string, models[role]); - // } - // } - // } - }; - - const submitAndLeave = () => { - submitChanges(); - navigate("/"); - }; - - useEffect(() => { - if (!config) return; - - formMethods.setValue("systemMessage", config.systemMessage); - formMethods.setValue( - "completionOptions.temperature", - config.completionOptions?.temperature, - ); - }, [config]); - - return ( - -
    -
    - -

    Settings

    - { - ideMessenger.post("showFile", { - filepath: - getPlatform() == "windows" - ? "~\\.continue\\config.json" - : "~/.continue/config.json", - }); - }} - > - Open config.json - -
    -
    - {config ? ( -
    -

    - System Message - -

    -