diff --git a/.eslintrc.shared.json b/.eslintrc.shared.json index f62954280..db8cb1271 100644 --- a/.eslintrc.shared.json +++ b/.eslintrc.shared.json @@ -7,6 +7,7 @@ "plugins": ["@typescript-eslint", "import"], "rules": { "@typescript-eslint/naming-convention": "off", + "@typescript-eslint/no-floating-promises": "warn", "@typescript-eslint/semi": "warn", "curly": "warn", "eqeqeq": "warn", diff --git a/.github/workflows/auto-assign-issue.yaml b/.github/workflows/auto-assign-issue.yaml index dc5388ef3..940f7cf54 100644 --- a/.github/workflows/auto-assign-issue.yaml +++ b/.github/workflows/auto-assign-issue.yaml @@ -16,9 +16,9 @@ jobs: repo-token: ${{ secrets.CI_GITHUB_TOKEN }} assignees: sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa numOfAssignee: 1 - - name: "Add default labels" - uses: actions-ecosystem/action-add-labels@v1 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - labels: | - "needs-triage" + # - name: "Add default labels" + # uses: actions-ecosystem/action-add-labels@v1 + # with: + # github_token: ${{ secrets.GITHUB_TOKEN }} + # labels: | + # "needs-triage" diff --git a/core/.eslintrc.json b/core/.eslintrc.json index fa760cc0c..08948b866 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -7,7 +7,8 @@ "rules": { "quotes": ["off", "double", {}], "@typescript-eslint/naming-convention": "off", - "@typescript-eslint/no-floating-promises": "off", + // This is important: when floating promises cause unhandled rejections, the JetBrains binary blows up + "@typescript-eslint/no-floating-promises": "error", "import/order": "off", "curly": "off", "@typescript-eslint/semi": "off", diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 2d3fe9eba..fd9cf2923 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -261,7 +261,9 @@ export class CompletionProvider { // Save to cache if (!outcome.cacheHit && helper.options.useCache) { - (await this.autocompleteCache).put(outcome.prefix, outcome.completion); + (await this.autocompleteCache) + .put(outcome.prefix, outcome.completion) + .catch((e) => console.warn(`Failed to save to cache: ${e.message}`)); } // When using the JetBrains extension, Mark as displayed diff --git a/core/autocomplete/context/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts index e2288138a..0115b443f 100644 --- a/core/autocomplete/context/ImportDefinitionsService.ts +++ b/core/autocomplete/context/ImportDefinitionsService.ts @@ -22,7 +22,13 @@ export class ImportDefinitionsService { constructor(private readonly ide: IDE) { ide.onDidChangeActiveTextEditor((filepath) => { - this.cache.initKey(filepath); + this.cache + .initKey(filepath) + .catch((e) => + console.warn( + `Failed to initialize ImportDefinitionService: ${e.message}`, + ), + ); }); } diff --git a/core/autocomplete/generation/ListenableGenerator.ts b/core/autocomplete/generation/ListenableGenerator.ts index e6b36019b..3fddb55a3 100644 --- a/core/autocomplete/generation/ListenableGenerator.ts +++ b/core/autocomplete/generation/ListenableGenerator.ts @@ -3,16 +3,18 @@ export class ListenableGenerator { private _buffer: T[] = []; private _listeners: Set<(value: T) => void> = new Set(); private _isEnded = false; - private _abortController: AbortController + private _abortController: AbortController; constructor( source: AsyncGenerator, private readonly onError: (e: any) => void, - abortController: AbortController + abortController: AbortController, ) { this._source = source; this._abortController = abortController; - this._start(); + this._start().catch((e) => + console.log(`Listenable generator failed: ${e.message}`), + ); } public cancel() { diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index b304c4058..6385fa22b 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -157,11 +157,11 @@ const mercuryMultifileFimTemplate: AutocompleteTemplate = { if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { return [ - `<|file_sep|>${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n${prefix}`, + `<|file_sep|>${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n<|fim_prefix|>${prefix}`, suffix, ]; } - return [prefix, suffix]; + return [`<|fim_prefix|>${prefix}`, suffix]; } const relativePaths = getShortestUniqueRelativeUriPaths( diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index c830ef10e..0c3167b7b 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -349,7 +349,7 @@ export class ConfigHandler { this.currentOrg = org; if (profileId) { - this.setSelectedProfileId(profileId); + await this.setSelectedProfileId(profileId); } else { this.currentProfile = org.currentProfile; await this.reloadConfig(); diff --git a/core/config/load.ts b/core/config/load.ts index 18c61ce93..5a74aa6bb 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -627,6 +627,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { contextLength: llm.contextLength, template: llm.template, completionOptions: llm.completionOptions, + baseAgentSystemMessage: llm.baseAgentSystemMessage, baseChatSystemMessage: llm.baseChatSystemMessage, requestOptions: llm.requestOptions, promptTemplates: serializePromptTemplates(llm.promptTemplates), @@ -969,5 +970,6 @@ export { finalToBrowserConfig, intermediateToFinalConfig, loadContinueConfigFromJson, - type BrowserSerializedContinueConfig, + type BrowserSerializedContinueConfig }; + diff --git a/core/config/types.ts b/core/config/types.ts index ee3e308f8..ee4b500bf 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -235,10 +235,6 @@ declare global { loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; } - export interface Checkpoint { - [filepath: string]: string; - } - export interface Session { sessionId: string; title: string; @@ -423,8 +419,6 @@ declare global { promptLogs?: PromptLog[]; toolCallState?: ToolCallState; isGatheringContext?: boolean; - checkpoint?: Checkpoint; - isBeforeCheckpoint?: boolean; } export interface LLMFullCompletionOptions extends BaseCompletionOptions { @@ -1051,13 +1045,6 @@ declare global { repoMapFileSelection?: string; } - export type EditStatus = - | "not-started" - | "streaming" - | "accepting" - | "accepting:full-diff" - | "done"; - export type ApplyStateStatus = | "streaming" // Changes are being applied to the file | "done" // All changes have been applied, awaiting user to accept/reject diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts deleted file mode 100644 index dbc567005..000000000 --- a/core/config/yaml/convertFromJson.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; - -import { SerializedContinueConfig } from "../.."; - -/* -TODO this is not functional -*/ -export function convertConfigJsonToConfigYaml( - configJson: SerializedContinueConfig, -): AssistantUnrolled { - return { - name: "Local Assistant", - version: "1.0.0", - schema: "v1", - models: [ - ...configJson.models.map( - (model): ModelConfig => ({ - model: model.model, - name: model.title, - // defaultCompletionOptions: model.completionOptions, - provider: model.provider, - roles: ["chat", "edit", "apply", "summarize"], - }), - ), - // TODO - // tabAutocompleteModels - // embeddingsModels - // rerankModels - ], - context: configJson.contextProviders?.map((provider) => ({ - provider: provider.name, - params: provider.params, - })), - }; -} diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 6e15787bc..ffa891df6 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -60,8 +60,9 @@ async function modelConfigToBaseLLM({ logger: llmLogger, uniqueId, title: model.name, - template: model.promptTemplates?.chatTemplate, + template: model.promptTemplates?.chat, promptTemplates: model.promptTemplates, + baseAgentSystemMessage: model.chatOptions?.baseAgentSystemMessage, baseChatSystemMessage: model.chatOptions?.baseSystemMessage, capabilities: { tools: model.capabilities?.includes("tool_use"), diff --git a/core/core.ts b/core/core.ts index 21208970d..e5c9eeab0 100644 --- a/core/core.ts +++ b/core/core.ts @@ -349,8 +349,8 @@ export class Core { return await this.configHandler.getSerializedConfig(); }); - on("config/ideSettingsUpdate", (msg) => { - this.configHandler.updateIdeSettings(msg.data); + on("config/ideSettingsUpdate", async (msg) => { + await this.configHandler.updateIdeSettings(msg.data); }); on("config/refreshProfiles", async (msg) => { @@ -389,7 +389,7 @@ export class Core { }); on("mcp/reloadServer", async (msg) => { - MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); + await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); }); // Context providers on("context/addDocs", async (msg) => { @@ -743,7 +743,7 @@ export class Core { if (!config) { return false; } - + const llm = config?.selectedModelByRole.chat; if (!llm) { throw new Error("No chat model selected"); @@ -1034,10 +1034,9 @@ export class Core { } this.indexingCancellationController = new AbortController(); try { - for await (const update of (await this.codebaseIndexerPromise).refreshDirs( - paths, - this.indexingCancellationController.signal, - )) { + for await (const update of ( + await this.codebaseIndexerPromise + ).refreshDirs(paths, this.indexingCancellationController.signal)) { let updateToSend = { ...update }; void this.messenger.request("indexProgress", updateToSend); @@ -1067,10 +1066,10 @@ export class Core { return; } this.indexingCancellationController = new AbortController(); - try{ - for await (const update of (await this.codebaseIndexerPromise).refreshFiles( - files, - )) { + try { + for await (const update of ( + await this.codebaseIndexerPromise + ).refreshFiles(files)) { let updateToSend = { ...update }; void this.messenger.request("indexProgress", updateToSend); @@ -1093,18 +1092,18 @@ export class Core { // private handleIndexingError(e: any) { - if (e instanceof LLMError) { - // Need to report this specific error to the IDE for special handling - this.messenger.request("reportError", e); - } - // broadcast indexing error - let updateToSend: IndexingProgressUpdate = { - progress: 0, - status: "failed", - desc: e.message, - }; - void this.messenger.request("indexProgress", updateToSend); - this.codebaseIndexingState = updateToSend; - void this.sendIndexingErrorTelemetry(updateToSend); + if (e instanceof LLMError) { + // Need to report this specific error to the IDE for special handling + void this.messenger.request("reportError", e); + } + // broadcast indexing error + let updateToSend: IndexingProgressUpdate = { + progress: 0, + status: "failed", + desc: e.message, + }; + void this.messenger.request("indexProgress", updateToSend); + this.codebaseIndexingState = updateToSend; + void this.sendIndexingErrorTelemetry(updateToSend); } } diff --git a/core/edit/constants.ts b/core/edit/constants.ts new file mode 100644 index 000000000..ecc3340ca --- /dev/null +++ b/core/edit/constants.ts @@ -0,0 +1 @@ +export const EDIT_MODE_STREAM_ID = "edit-mode"; diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index f88aeefc0..320962b7c 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -161,9 +161,11 @@ export async function* streamDiffLines({ ? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction, + reasoning: false, }) : llm.streamChat(prompt, new AbortController().signal, { prediction, + reasoning: false, }); let lines = streamLines(completion); diff --git a/core/index.d.ts b/core/index.d.ts index 7aa8d00ec..3a711e408 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -158,9 +158,7 @@ export interface ModelInstaller { progressReporter?: (task: string, increment: number, total: number) => void, ): Promise; - isInstallingModel( - modelName: string - ): Promise; + isInstallingModel(modelName: string): Promise; } export type ContextProviderType = "normal" | "query" | "submenu"; @@ -248,10 +246,6 @@ export interface IContextProvider { loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; } -export interface Checkpoint { - [filepath: string]: string; -} - export interface Session { sessionId: string; title: string; @@ -464,8 +458,6 @@ export interface ChatHistoryItem { promptLogs?: PromptLog[]; toolCallState?: ToolCallState; isGatheringContext?: boolean; - checkpoint?: Checkpoint; - isBeforeCheckpoint?: boolean; reasoning?: Reasoning; } @@ -569,6 +561,7 @@ export interface LLMOptions { title?: string; uniqueId?: string; + baseAgentSystemMessage?: string; baseChatSystemMessage?: string; contextLength?: number; maxStopWords?: number; @@ -1052,6 +1045,7 @@ export interface ModelDescription { maxStopWords?: number; template?: TemplateType; completionOptions?: BaseCompletionOptions; + baseAgentSystemMessage?: string; baseChatSystemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; @@ -1213,13 +1207,6 @@ export interface ExperimentalMCPOptions { faviconUrl?: string; } -export type EditStatus = - | "not-started" - | "streaming" - | "accepting" - | "accepting:full-diff" - | "done"; - export type ApplyStateStatus = | "not-started" // Apply state created but not necessarily streaming | "streaming" // Changes are being applied to the file diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index bf733b5ce..9a2da5008 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -57,7 +57,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { FOREIGN KEY (snippetId) REFERENCES code_snippets (id) )`); - migrate("add_signature_column", async () => { + await migrate("add_signature_column", async () => { const tableInfo = await db.all("PRAGMA table_info(code_snippets)"); const signatureColumnExists = tableInfo.some( (column) => column.name === "signature", @@ -71,7 +71,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { } }); - migrate("delete_duplicate_code_snippets", async () => { + await migrate("delete_duplicate_code_snippets", async () => { // Delete duplicate entries in code_snippets await db.exec(` DELETE FROM code_snippets @@ -256,7 +256,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { progress: i / results.compute.length, status: "indexing", }; - markComplete([compute], IndexResultType.Compute); + await markComplete([compute], IndexResultType.Compute); } // Delete @@ -278,7 +278,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { ); } - markComplete([del], IndexResultType.Delete); + await markComplete([del], IndexResultType.Delete); } // Add tag @@ -313,7 +313,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { ); } - markComplete([results.addTag[i]], IndexResultType.AddTag); + await markComplete([results.addTag[i]], IndexResultType.AddTag); } // Remove tag @@ -343,7 +343,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { ); } - markComplete([results.removeTag[i]], IndexResultType.RemoveTag); + await markComplete([results.removeTag[i]], IndexResultType.RemoveTag); } } diff --git a/core/indexing/TestCodebaseIndex.ts b/core/indexing/TestCodebaseIndex.ts index e36dff7ce..86b22ab98 100644 --- a/core/indexing/TestCodebaseIndex.ts +++ b/core/indexing/TestCodebaseIndex.ts @@ -48,10 +48,10 @@ export class TestCodebaseIndex implements CodebaseIndex { ); } - markComplete(results.compute, IndexResultType.Compute); - markComplete(results.addTag, IndexResultType.AddTag); - markComplete(results.del, IndexResultType.Delete); - markComplete(results.removeTag, IndexResultType.RemoveTag); + await markComplete(results.compute, IndexResultType.Compute); + await markComplete(results.addTag, IndexResultType.AddTag); + await markComplete(results.del, IndexResultType.Delete); + await markComplete(results.removeTag, IndexResultType.RemoveTag); } async getIndexedFilesForTags(tags: IndexTag[]): Promise { diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index cc9eef842..d82c34b20 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -510,7 +510,7 @@ export default class DocsService { } catch (e) { if (e instanceof LLMError) { // Report the error to the IDE - this.messenger?.request("reportError", e); + await this.messenger?.request("reportError", e); } this.handleStatusUpdate({ ...fixedStatus, diff --git a/core/llm/asyncEncoder.test.ts b/core/llm/asyncEncoder.test.ts index 9ed5eb80a..0b02b3d5a 100644 --- a/core/llm/asyncEncoder.test.ts +++ b/core/llm/asyncEncoder.test.ts @@ -1,4 +1,4 @@ -import { LlamaAsyncEncoder, GPTAsyncEncoder } from "./asyncEncoder"; +import { GPTAsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder"; describe("llama encoder", () => { var tokenizer: LlamaAsyncEncoder; @@ -8,7 +8,7 @@ describe("llama encoder", () => { }); afterAll(() => { - tokenizer.close(); + tokenizer.close().catch((e) => {}); }); test("hello world", async () => { @@ -30,7 +30,7 @@ describe("tiktoken encoder", () => { }); afterAll(() => { - tokenizer.close(); + tokenizer.close().catch((e) => {}); }); test("hello world", async () => { diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 145cb1ac6..1393ac44e 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -72,6 +72,7 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [ "sagemaker", "continue-proxy", "openrouter", + "venice", "sambanova", "vertexai", "azure", @@ -96,7 +97,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "pixtral", "llama3.2", "llama-3.2", - "llama4" + "llama4", ]; function modelSupportsTools(modelDescription: ModelDescription) { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 11701feb8..8a6382ca4 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -60,7 +60,7 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ export function constructMessages( history: ChatHistoryItem[], - baseChatSystemMessage: string | undefined, + baseChatOrAgentSystemMessage: string | undefined, rules: RuleWithSource[], ): ChatMessage[] { const filteredHistory = history.filter( @@ -100,7 +100,7 @@ export function constructMessages( | undefined; const systemMessage = getSystemMessageWithRules({ - baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE, + baseSystemMessage: baseChatOrAgentSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE, rules, userMessage: lastUserMsg, }); diff --git a/core/llm/index.ts b/core/llm/index.ts index aa115fb71..96fdb319c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -130,6 +130,7 @@ export abstract class BaseLLM implements ILLM { title?: string; baseChatSystemMessage?: string; + baseAgentSystemMessage?: string; contextLength: number; maxStopWords?: number | undefined; completionOptions: CompletionOptions; @@ -196,6 +197,7 @@ export abstract class BaseLLM implements ILLM { this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; + this.baseAgentSystemMessage = options.baseAgentSystemMessage; this.baseChatSystemMessage = options.baseChatSystemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; diff --git a/core/llm/llms/Docker.ts b/core/llm/llms/Docker.ts index 131f45b14..3860a9b9e 100644 --- a/core/llm/llms/Docker.ts +++ b/core/llm/llms/Docker.ts @@ -60,7 +60,7 @@ class Docker extends OpenAI implements ModelInstaller { } // Check if Docker Model Runner is active and enable it if needed - this.ensureModelRunnerEnabled(); + this.ensureModelRunnerEnabled().catch((e) => {}); } /** @@ -198,7 +198,7 @@ class Docker extends OpenAI implements ModelInstaller { return { success: true, stdout, stderr }; } catch (error) { console.error(`Failed to install Docker model ${targetModel}:`, error); -// Fix: Type check the error before accessing message property + // Fix: Type check the error before accessing message property const errorMessage = error instanceof Error ? error.message : String(error); throw new Error( diff --git a/core/llm/llms/HuggingFaceTEI.ts b/core/llm/llms/HuggingFaceTEI.ts index 52580c187..187db8122 100644 --- a/core/llm/llms/HuggingFaceTEI.ts +++ b/core/llm/llms/HuggingFaceTEI.ts @@ -35,14 +35,20 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { } async doEmbedRequest(batch: string[]): Promise { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers["Authorization"] = `Bearer ${this.apiKey}`; + } + const resp = await this.fetch(new URL("embed", this.apiBase), { method: "POST", body: JSON.stringify({ inputs: batch, }), - headers: { - "Content-Type": "application/json", - }, + headers, }); if (!resp.ok) { const text = await resp.text(); diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index 481532f95..c9812cca3 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -14,18 +14,22 @@ class HuggingFaceTGI extends BaseLLM { this.fetch(new URL("info", this.apiBase), { method: "GET", - }).then(async (response) => { - if (response.status !== 200) { - console.warn( - "Error calling Hugging Face TGI /info endpoint: ", - await response.text(), - ); - return; - } - const json = await response.json(); - this.model = json.model_id; - this.contextLength = Number.parseInt(json.max_input_length); - }); + }) + .then(async (response) => { + if (response.status !== 200) { + console.warn( + "Error calling Hugging Face TGI /info endpoint: ", + await response.text(), + ); + return; + } + const json = await response.json(); + this.model = json.model_id; + this.contextLength = Number.parseInt(json.max_input_length); + }) + .catch((e) => { + console.log(`Failed to list models for HuggingFace TGI: ${e.message}`); + }); } private _convertArgs(options: CompletionOptions, prompt: string) { diff --git a/core/llm/llms/Venice.ts b/core/llm/llms/Venice.ts new file mode 100644 index 000000000..fd4c0ebfe --- /dev/null +++ b/core/llm/llms/Venice.ts @@ -0,0 +1,22 @@ +import { ChatCompletionCreateParams } from "@continuedev/openai-adapters"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; + +import OpenAI from "./OpenAI"; + +class Venice extends OpenAI { + static providerName = "venice"; + static defaultOptions: Partial = { + apiBase: "https://api.venice.ai/api/v1", + }; + + protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams { + const finalOptions = super._convertArgs(options, messages) as ChatCompletionCreateParams & { venice_parameters?: any }; + if ("venice_parameters" in options && typeof options.venice_parameters === "object") { + finalOptions.venice_parameters = { ...options.venice_parameters }; + } + return finalOptions; + } + +} + +export default Venice; \ No newline at end of file diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 84f471c6f..cc1b70b19 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -22,7 +22,11 @@ class VertexAI extends BaseLLM { private clientPromise = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform", - }).getClient(); + }) + .getClient() + .catch((e) => { + console.warn(`Failed to load credentials for Vertex AI: ${e.message}`); + }); private static getDefaultApiBaseFrom(options: LLMOptions) { const { region, projectId } = options; @@ -60,8 +64,8 @@ class VertexAI extends BaseLLM { async fetch(url: RequestInfo | URL, init?: RequestInit) { const client = await this.clientPromise; - const { token } = await client.getAccessToken(); - if (!token) { + const result = await client?.getAccessToken(); + if (!result?.token) { throw new Error( "Could not get an access token. Set up your Google Application Default Credentials.", ); @@ -70,7 +74,7 @@ class VertexAI extends BaseLLM { ...init, headers: { "Content-Type": "application/json", - Authorization: `Bearer ${token}`, + Authorization: `Bearer ${result.token}`, ...init?.headers, }, }); @@ -370,8 +374,8 @@ class VertexAI extends BaseLLM { protected async _embed(chunks: string[]): Promise { const client = await this.clientPromise; - const { token } = await client.getAccessToken(); - if (!token) { + const result = await client?.getAccessToken(); + if (!result?.token) { throw new Error( "Could not get an access token. Set up your Google Application Default Credentials.", ); @@ -386,7 +390,7 @@ class VertexAI extends BaseLLM { }), headers: { "Content-Type": "application/json", - Authorization: `Bearer ${token}`, + Authorization: `Bearer ${result.token}`, }, }, ); @@ -402,8 +406,4 @@ class VertexAI extends BaseLLM { } } -async function delay(seconds: number) { - return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); -} - export default VertexAI; diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts index 7273a67f6..b237b4c7e 100644 --- a/core/llm/llms/Vllm.ts +++ b/core/llm/llms/Vllm.ts @@ -16,19 +16,23 @@ class Vllm extends OpenAI { this.fetch(this._getEndpoint("models"), { method: "GET", headers: this._getHeaders(), - }).then(async (response) => { - if (response.status !== 200) { - console.warn( - "Error calling vLLM /models endpoint: ", - await response.text(), - ); - return; - } - const json = await response.json(); - const data = json.data[0]; - this.model = data.id; - this.contextLength = Number.parseInt(data.max_model_len); - }); + }) + .then(async (response) => { + if (response.status !== 200) { + console.warn( + "Error calling vLLM /models endpoint: ", + await response.text(), + ); + return; + } + const json = await response.json(); + const data = json.data[0]; + this.model = data.id; + this.contextLength = Number.parseInt(data.max_model_len); + }) + .catch((e) => { + console.log(`Failed to list models for vLLM: ${e.message}`); + }); } } diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index d04f02dfe..43e70972f 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -57,6 +57,7 @@ import ContinueProxy from "./stubs/ContinueProxy"; import TestLLM from "./Test"; import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; +import Venice from "./Venice"; import VertexAI from "./VertexAI"; import Vllm from "./Vllm"; import Voyage from "./Voyage"; @@ -109,6 +110,7 @@ export const LLMClasses = [ Cerebras, Asksage, Nebius, + Venice, VertexAI, xAI, SiliconFlow, @@ -158,6 +160,7 @@ export async function llmFromDescription( cls.defaultOptions?.completionOptions?.maxTokens, }, baseChatSystemMessage, + baseAgentSystemMessage: baseChatSystemMessage, logger: llmLogger, uniqueId, }; diff --git a/core/package-lock.json b/core/package-lock.json index d1cc6a59a..71133e753 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -14,7 +14,7 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.4", + "@continuedev/fetch": "^1.0.6", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", @@ -2925,9 +2925,9 @@ "link": true }, "node_modules/@continuedev/fetch": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.4.tgz", - "integrity": "sha512-lFLMQMdyo3y5ZpgAxTtOLj3lvhQAQUoI96SPCXjdV6NQp2gF/XmmIadCD+Hfx03Iz750Y5PF8jYdrGTMFxwlaQ==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.6.tgz", + "integrity": "sha512-QpB9cHgEw5avoouFR0qm7/XTo44SrVfkGAmzbDTui2P9djj+DYvj+0yaJ8e/Ubyc5PUjFTUS2YnRar7NfYpHIg==", "dependencies": { "@continuedev/config-types": "^1.0.5", "follow-redirects": "^1.15.6", diff --git a/core/package.json b/core/package.json index 3b92245c7..9332baa21 100644 --- a/core/package.json +++ b/core/package.json @@ -48,7 +48,7 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.4", + "@continuedev/fetch": "^1.0.6", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index cc1191d92..17c09a348 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import type { ApplyState, CodeToEdit, - EditStatus, MessageContent, RangeInFileWithContents, } from "../"; @@ -50,9 +49,10 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { prompt: MessageContent; range: RangeInFileWithContents; }, - void, + string | undefined, ]; - "edit/exit": [{ shouldFocusEditor: boolean }, void]; + "edit/addCurrentSelection": [undefined, void]; + "edit/clearDecorations": [undefined, void]; }; export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { @@ -71,7 +71,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { }, void, ]; - addCodeToEdit: [CodeToEdit, void]; + setCodeToEdit: [CodeToEdit, void]; navigateTo: [{ path: string; toggle?: boolean }, void]; addModel: [undefined, void]; @@ -87,8 +87,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { openOnboardingCard: [undefined, void]; applyCodeFromChat: [undefined, void]; updateApplyState: [ApplyState, void]; - setEditStatus: [{ status: EditStatus; fileAfterEdit?: string }, void]; exitEditMode: [undefined, void]; focusEdit: [undefined, void]; - focusEditWithoutClear: [undefined, void]; }; diff --git a/docs/docs/customize/model-providers/more/venice.md b/docs/docs/customize/model-providers/more/venice.md new file mode 100644 index 000000000..b612189ae --- /dev/null +++ b/docs/docs/customize/model-providers/more/venice.md @@ -0,0 +1,35 @@ +# Venice + +Venice.AI is a privacy focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data. To get started with Venice's API, either purchase a pro account, stake $VVV to obtain daily inference allotments or fund your account with USD and head over to https://venice.ai/settings/api. Venice hosts state of the art open-source AI models and supports the OpenAI API standard, allowing users to easily interact with the platform. Learn more about the Venice API at https://venice.ai/api. + +Change `~/.continue/config.json` to look like the following. + +```json title="config.json" +{ + "models": [ + { + "provider": "venice", + "title": "Autodetect", + "model": "AUTODETECT", + "apiKey": "..." + } + ] +} +``` + +To utilize features offered by the venice API that are not apart of the standard OpenAI API schema, include these as `venice_parameters` + +For example, to use models with no system prompt, you can explicitly turn off the feature like so: + +```json title="config.json" +{ + "completionOptions": { + "venice_parameters": { + "include_venice_system_prompt" : false + }, + ... + } +} +``` + +Learn more about available settings [here](https://docs.venice.ai/api-reference/api-spec). \ No newline at end of file diff --git a/docs/docs/customize/model-roles/embeddings.mdx b/docs/docs/customize/model-roles/embeddings.mdx index a58cd520d..ce5357792 100644 --- a/docs/docs/customize/model-roles/embeddings.mdx +++ b/docs/docs/customize/model-roles/embeddings.mdx @@ -100,6 +100,7 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc - name: Huggingface TEI Embedder provider: huggingface-tei apiBase: http://localhost:8080 + apiKey: roles: [embed] ``` @@ -108,7 +109,8 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc { "embeddingsProvider": { "provider": "huggingface-tei", - "apiBase": "http://localhost:8080" + "apiBase": "http://localhost:8080", + "apiKey": "" } } ``` diff --git a/docs/docs/edit/context-selection.md b/docs/docs/edit/context-selection.md index ebe12d8da..ceb2ea766 100644 --- a/docs/docs/edit/context-selection.md +++ b/docs/docs/edit/context-selection.md @@ -11,7 +11,7 @@ The input you provide is included in the prompt. ## Code to Edit -The **entire contents** of each file (the current file for Jetbrains inline Edit, each `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges. +The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges. ## Context Providers diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 620a18eda..84b4acb2c 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -20,7 +20,7 @@ Edit is recommended for small, targeted changes, such as ## Highlight code and activate -Highlight the block of code you would like to modify and press cmd/ctrl + i to active Edit mode. You can also enter Edit mode by pressing cmd/ctrl + i with no code highlighted. +Highlight the block of code you would like to modify and press cmd/ctrl + i to active Edit mode. You can also enter Edit mode by pressing cmd/ctrl + i with no code highlighted, which will default to editing the current file. ## Describe code changes @@ -48,32 +48,6 @@ You can also reject and accept diffs using the `Reject All` and `Accept All` but Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor. -**_Add file combobox_** - -![edit mode add file combobox](/img/edit-mode-add-files.png) - -**_Add all open files dropdown_** - -![edit mode add file combobox](/img/edit-mode-add-all-open-files.png) - -### Single File Edit - -If one file/range is present in `Code to Edit` on submission, Continue will prompt the Edit model and then automatically stream the diff into the editor. - -![Edit mode single file diffs](/img/edit-mode-single-file-diff.png) - -### Multi-File Edit - -If multiple files/ranges are present in `Code to Edit` on submission, Continue will prompt the Edit model to output codeblocks per-file, which the user can then choose to apply and accept/reject independently. - -**_Generated Content_** - -![Edit mode multi file generated content](/img/edit-mode-multi-file-generation.png) - -**_Diffs_** - -![Edit mode multi file diffs](/img/edit-mode-multi-file-diffs.png) - ## Jetbrains -In Jetbrains, Edit is implemented as an inline popup (see the header GIF example) for single-file edit. Multi-file edit mode is not currently implemented. +In Jetbrains, Edit is implemented as an inline popup. See the header GIF example. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 3b360b7c8..5600f524d 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -8,33 +8,44 @@ keywords: [config, yaml, configuration, customize, customization] ## Introduction -Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded from [the Hub](https://hub.continue.dev/explore/assistants) or locally +Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded +from [the Hub](https://hub.continue.dev/explore/assistants) or locally -- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to the extension +- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to + the extension - Locally - - in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`. The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml` + - in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`. + The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml` - in your workspace in a `/.continue/assistants` folder, with the same naming convention :::info -Config YAML replaces [`config.json`](./json-reference.md), which is deprecated. View the **[Migration Guide](./yaml-migration.md)**. +Config YAML replaces [`config.json`](./json-reference.md), which is deprecated. View the \* \*[Migration Guide](./yaml-migration.md)\*\*. ::: An assistant is made up of: 1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant -2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers. +2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as + models, docs, and context providers. -A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is. +A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In +`config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), +but only has **ONE** item under whichever block type it is. Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants). -Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks. +Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing +hub blocks. ### Using Blocks -Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev). +Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner +can be a user or organization (For example, if you want to use +the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks +are pulled from [https://hub.continue.dev](https://hub.continue.dev). -Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. +Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other +`uses` clauses or explicit blocks of that type. :::info Note that local assistants cannot use blocks that require organization-level secrets. @@ -51,7 +62,9 @@ models: ### Local Blocks -It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally). +It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of +your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home +directory at `~/.continue` (these will automatically be applied globally). Place your YAML files in the following folders: @@ -69,11 +82,13 @@ Blocks: - `.continue/data` - for data - `.continue/mcpServers` - for MCP Servers -You can find many examples of each of these block types on the [Continue Explore Page](https://hub.continue.dev/explore/models) +You can find many examples of each of these block types on +the [Continue Explore Page](https://hub.continue.dev/explore/models) ### Inputs -Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: +Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use +mustache templating as follows: ```yaml title="Block config.yaml" name: myprofile/custom-model @@ -157,7 +172,8 @@ The `schema` property specifies the schema version used for the `config.yaml`, e ### `models` -The `models` section defines the language models used in your configuration. Models are used for functionalities such as chat, editing, and summarizing. +The `models` section defines the language models used in your configuration. Models are used for functionalities such as +chat, editing, and summarizing. **Properties:** @@ -165,11 +181,19 @@ The `models` section defines the language models used in your configuration. Mod - `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`). - `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`). - `apiBase`: Can be used to override the default API base that is specified per model -- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. -- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. -- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are `chatTemplate`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [`autocomplete`](./customize/model-roles/autocomplete.md#prompt-templating). The `chatTemplate` property must be a valid template name, such as `llama3` or `anthropic`. +- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, + `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is + not currently used. +- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on + provider and model. Supported capabilities include `tool_use` and `image_input`. +- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are + `chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [ + `apply`](./customize/model-roles/apply.mdx#prompt-templating) and [ + `autocomplete`](./customize/model-roles/autocomplete.md#prompt-templating). The `chatTemplate` property must be a + valid template name, such as `llama3` or `anthropic`. - `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: - - `baseSystemMessage`: Can be used to override the default system prompt. + - `baseSystemMessage`: Can be used to override the default system prompt for **Chat** mode. + - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: - `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. - `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. @@ -233,7 +257,8 @@ models: ### `context` -The `context` section defines context providers, which supply additional information or context to the language models. Each context provider can be configured with specific parameters. +The `context` section defines context providers, which supply additional information or context to the language models. +Each context provider can be configured with specific parameters. More information about usage/params for each context provider can be found [here](/customize/context-providers.mdx) @@ -266,13 +291,17 @@ context: ### `rules` -List of rules that the LLM should follow. These are concatenated into the system message for all [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Agent](./agent/how-to-use-it.md) requests. See the [rules deep dive](./customize/deep-dives/rules.md) for details. +List of rules that the LLM should follow. These are concatenated into the system message for +all [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Agent](./agent/how-to-use-it.md) requests. +See the [rules deep dive](./customize/deep-dives/rules.md) for details. Explicit rules can either be simple text or an object with the following properties: - `name` (**required**): A display name/title for the rule - `rule` (**required**): The text content of the rule -- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). +- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This + can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., + `["src/**/*.ts", "tests/**/*.ts"]`). ```yaml title="config.yaml" rules: @@ -297,7 +326,8 @@ rules: ### `prompts` -A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. +A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual +prompt text. ```yaml title="config.yaml" prompts: @@ -320,7 +350,9 @@ List of documentation sites to index. - `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs + + - `maxDepth`: Maximum link depth for crawling. Default `4` - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). - `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. @@ -340,7 +372,8 @@ docs: -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. +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. **Properties:** @@ -373,7 +406,8 @@ Destinations to which [development data](./customize/deep-dives/development-data - a file URL to a directory in which events will be dumpted to `.jsonl` files - `schema` (**required**): the schema version of the JSON blobs to be sent - `events`: an array of event names to include. Defaults to all events if not specified. -- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file contents, prompts, and completions. Defaults to `all` +- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file + contents, prompts, and completions. Defaults to `all` - `apiKey`: api key to be sent with request (Bearer header) - `requestOptions`: Options for event POST requests. Same format as [model requestOptions](#models). diff --git a/docs/static/img/edit-mode-add-all-open-files.png b/docs/static/img/edit-mode-add-all-open-files.png deleted file mode 100644 index 9aa981347..000000000 Binary files a/docs/static/img/edit-mode-add-all-open-files.png and /dev/null differ diff --git a/docs/static/img/edit-mode-add-files.png b/docs/static/img/edit-mode-add-files.png deleted file mode 100644 index b2f97f314..000000000 Binary files a/docs/static/img/edit-mode-add-files.png and /dev/null differ diff --git a/docs/static/img/edit-mode-multi-file-diffs.png b/docs/static/img/edit-mode-multi-file-diffs.png deleted file mode 100644 index caa9f2d25..000000000 Binary files a/docs/static/img/edit-mode-multi-file-diffs.png and /dev/null differ diff --git a/docs/static/img/edit-mode-multi-file-generation.png b/docs/static/img/edit-mode-multi-file-generation.png deleted file mode 100644 index 20f3fe98e..000000000 Binary files a/docs/static/img/edit-mode-multi-file-generation.png and /dev/null differ diff --git a/docs/static/img/edit-mode-multi-file-output.png b/docs/static/img/edit-mode-multi-file-output.png deleted file mode 100644 index 1ceb00714..000000000 Binary files a/docs/static/img/edit-mode-multi-file-output.png and /dev/null differ diff --git a/extensions/vscode/.eslintrc.json b/extensions/vscode/.eslintrc.json index f4973fa87..e1e339ce7 100644 --- a/extensions/vscode/.eslintrc.json +++ b/extensions/vscode/.eslintrc.json @@ -5,6 +5,7 @@ }, "extends": ["../../.eslintrc.shared.json"], "rules": { - "@typescript-eslint/naming-convention": "off" + "@typescript-eslint/naming-convention": "off", + "@typescript-eslint/no-floating-promises": "warn" } } diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 64b65c525..583dbb60e 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -231,8 +231,9 @@ "function-network", "scaleway", "relace", + "morph", "ovhcloud", - "morph" + "venice" ], "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)", @@ -280,8 +281,9 @@ "### 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.", "### Scaleway\n Generative APIs are serverless endpoints for the most popular AI models.\nHosted in European data centers and priced competitively per million tokens used, models served by Scaleway are ideal for users requiring low latency, full data privacy, and 100% compliance with EU AI Act. To get access to the Scaleway Generative APIs, read the [Quickstart guide](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/) and get a [valid API key](https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/).", "### Relace\n Relace provides a fast apply model. To get started, obtain an API key from [here](https://app.relace.ai/settings/api-keys).", + "### Morph\nMorph provides a fast apply model. To get started, obtain an API key from [here](https://morphllm.com/dashboard).", "### OVHcloud AI Endpoints is a serverless inference API that provides access to a curated selection of models (e.g., Llama, Mistral, Qwen, Deepseek). It is designed with security and data privacy in mind and is compliant with GDPR. To get started, create an API key on the OVHcloud [AI Endpoints website](https://endpoints.ai.cloud.ovh.net/). For more information, including pricing, visit the OVHcloud [AI Endpoints product page](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/).", - "### Morph\nMorph provides a fast apply model. To get started, obtain an API key from [here](https://morphllm.com/dashboard)." + "### Venice\n Venice.AI is a privacy-focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data.\nHosted models support the OpenAI API standard, providing seamless integration for users seeking privacy and flexibility.\nTo get started with the Venice API, either purchase a pro account, stake $VVV for daily inference allotments, or fund your account with USD.\nVisit the [API settings page](https://venice.ai/settings/api) or learn more at the [Venice API documentation](https://venice.ai/api)." ], "type": "string" }, @@ -517,7 +519,8 @@ "xAI", "kindo", "scaleway", - "ovhcloud" + "ovhcloud", + "venice" ] } }, @@ -1764,6 +1767,30 @@ } } } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["venice"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "model": { + "anyOf": [ + { + "enum": ["AUTODETECT"] + }, + { + "type": "string" + } + ] + } + } + } } ] }, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 974ae46fa..2c1422e5a 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,14 +1,15 @@ { "name": "continue", - "version": "1.1.29", + "version": "1.1.30", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.29", + "version": "1.1.30", "license": "Apache-2.0", "dependencies": { + "@continuedev/config-types": "^1.0.14", "@continuedev/fetch": "^1.0.3", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", @@ -107,7 +108,7 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.4", + "@continuedev/fetch": "^1.0.6", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", @@ -693,9 +694,9 @@ } }, "node_modules/@continuedev/config-types": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.13.tgz", - "integrity": "sha512-5Qmy2x58uhW1GYknypFT/7iwxEJSbt8gMgfQReV7d6xjbJ09ISOTki3hIfCilKrTCo0gIY6pzKEfCoQkUTEi6Q==", + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", + "integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==", "dependencies": { "zod": "^3.23.8" } diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index f2f1fb54f..52715bdfd 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": "1.1.29", + "version": "1.1.30", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -383,11 +383,6 @@ "mac": "cmd+i", "key": "ctrl+i" }, - { - "command": "continue.focusEditWithoutClear", - "mac": "cmd+shift+i", - "key": "ctrl+shift+i" - }, { "command": "continue.exitEditMode", "mac": "escape", @@ -666,6 +661,7 @@ "vscode-extension-tester": "^8.10.0" }, "dependencies": { + "@continuedev/config-types": "^1.0.14", "@continuedev/fetch": "^1.0.3", "@electron/rebuild": "^3.2.10", "@reduxjs/toolkit": "^1.9.3", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 1e39374c1..c651f1eb2 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,12 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import * as os from "node:os"; +import * as fs from "node:fs"; -import { - ContextMenuConfig, - ILLM, - ModelInstaller, - RangeInFileWithContents, -} from "core"; +import { ContextMenuConfig, ILLM, ModelInstaller } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -17,10 +12,15 @@ import { walkDirAsync } from "core/indexing/walkDir"; import { isModelInstaller } from "core/llm"; import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { startLocalOllama } from "core/util/ollamaHelper"; -import { getDevDataFilePath } from "core/util/paths"; +import { + getConfigJsonPath, + getConfigYamlPath, + getDevDataFilePath, +} from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import readLastLines from "read-last-lines"; import * as vscode from "vscode"; +import * as YAML from "yaml"; import { getAutocompleteStatusBarDescription, @@ -40,7 +40,13 @@ import { Battery } from "./util/battery"; import { getMetaKeyLabel } from "./util/util"; import { VsCodeIde } from "./VsCodeIde"; -import type { VsCodeWebviewProtocol } from "./webviewProtocol"; +import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist"; +import { + addCodeToContextFromRange, + addEntireFileToContext, + addHighlightedCodeToContext, +} from "./util/addCode"; +import { openEditorAndRevealRange } from "./util/vscode"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -63,160 +69,6 @@ function captureCommandTelemetry( Telemetry.capture(commandName, { isCommandEvent: true, ...properties }); } -function addCodeToContextFromRange( - range: vscode.Range, - webviewProtocol: VsCodeWebviewProtocol, - prompt?: string, -) { - const document = vscode.window.activeTextEditor?.document; - - if (!document) { - return; - } - - const rangeInFileWithContents = { - filepath: document.uri.toString(), - contents: document.getText(range), - range: { - start: { - line: range.start.line, - character: range.start.character, - }, - end: { - line: range.end.line, - character: range.end.character, - }, - }, - }; - - webviewProtocol?.request("highlightedCode", { - rangeInFileWithContents, - prompt, - // Assume `true` since range selection is currently only used for quick actions/fixes - shouldRun: true, - }); -} - -function getRangeInFileWithContents( - allowEmpty?: boolean, - range?: vscode.Range, -): RangeInFileWithContents | null { - const editor = vscode.window.activeTextEditor; - - if (editor) { - const selection = editor.selection; - const filepath = editor.document.uri.toString(); - - if (range) { - const contents = editor.document.getText(range); - - return { - range: { - start: { - line: range.start.line, - character: range.start.character, - }, - end: { - line: range.end.line, - character: range.end.character, - }, - }, - filepath, - contents, - }; - } - - if (selection.isEmpty && !allowEmpty) { - return null; - } - - let selectionRange = new vscode.Range(selection.start, selection.end); - const document = editor.document; - // Select the context from the beginning of the selection start line to the selection start position - const beginningOfSelectionStartLine = selection.start.with(undefined, 0); - const textBeforeSelectionStart = document.getText( - new vscode.Range(beginningOfSelectionStartLine, selection.start), - ); - // If there are only whitespace before the start of the selection, include the indentation - if (textBeforeSelectionStart.trim().length === 0) { - selectionRange = selectionRange.with({ - start: beginningOfSelectionStartLine, - }); - } - - const contents = editor.document.getText(selectionRange); - - return { - filepath, - contents, - range: { - start: { - line: selection.start.line, - character: selection.start.character, - }, - end: { - line: selection.end.line, - character: selection.end.character, - }, - }, - }; - } - - return null; -} - -async function addHighlightedCodeToContext( - webviewProtocol: VsCodeWebviewProtocol | undefined, -) { - const rangeInFileWithContents = getRangeInFileWithContents(); - if (rangeInFileWithContents) { - webviewProtocol?.request("highlightedCode", { - rangeInFileWithContents, - }); - } -} - -async function addEntireFileToContext( - uri: vscode.Uri, - webviewProtocol: VsCodeWebviewProtocol | undefined, -) { - // If a directory, add all files in the directory - const stat = await vscode.workspace.fs.stat(uri); - if (stat.type === vscode.FileType.Directory) { - const files = await vscode.workspace.fs.readDirectory(uri); - for (const [filename, type] of files) { - if (type === vscode.FileType.File) { - addEntireFileToContext( - vscode.Uri.joinPath(uri, filename), - webviewProtocol, - ); - } - } - return; - } - - // Get the contents of the file - const contents = (await vscode.workspace.fs.readFile(uri)).toString(); - const rangeInFileWithContents = { - filepath: uri.toString(), - contents: contents, - range: { - start: { - line: 0, - character: 0, - }, - end: { - line: contents.split(os.EOL).length - 1, - character: 0, - }, - }, - }; - - webviewProtocol?.request("highlightedCode", { - rangeInFileWithContents, - }); -} - function focusGUI() { const fullScreenTab = getFullScreenTab(); if (fullScreenTab) { @@ -252,9 +104,10 @@ async function processDiff( ) { captureCommandTelemetry(`${action}Diff`); + const currentFile = await ide.getCurrentFile(); + let newOrCurrentUri = newFileUri; if (!newOrCurrentUri) { - const currentFile = await ide.getCurrentFile(); newOrCurrentUri = currentFile?.path; } if (!newOrCurrentUri) { @@ -269,10 +122,6 @@ async function processDiff( // Clear vertical diffs depending on action verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); - void sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - if (streamId) { const fileContent = await ide.readFile(newOrCurrentUri); @@ -286,8 +135,6 @@ async function processDiff( }); } - await sidebar.webviewProtocol.request("exitEditMode", undefined); - // Save the file await ide.saveFile(newOrCurrentUri); } @@ -538,102 +385,7 @@ const getCommandsMap: ( "continue.focusEdit": async (args?: QuickEditShowParams) => { captureCommandTelemetry("focusEdit"); focusGUI(); - sidebar.webviewProtocol?.request("focusEdit", undefined); - - const editor = vscode.window.activeTextEditor; - - if (!editor) { - return; - } - - const existingDiff = verticalDiffManager.getHandlerForFile( - editor.document.fileName, - ); - - // If there's a diff currently being applied, then we just toggle focus back to the input - if (existingDiff) { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - return; - } - - const startFromCharZero = editor.selection.start.with(undefined, 0); - const document = editor.document; - let lastLine, lastChar; - // If the user selected onto a trailing line but didn't actually include any characters in it - // they don't want to include that line, so trim it off. - if (editor.selection.end.character === 0) { - // This is to prevent the rare case that the previous line gets selected when user - // is selecting nothing and the cursor is at the beginning of the line - if (editor.selection.end.line === editor.selection.start.line) { - lastLine = editor.selection.start.line; - } else { - lastLine = editor.selection.end.line - 1; - } - } else { - lastLine = editor.selection.end.line; - } - lastChar = document.lineAt(lastLine).range.end.character; - const endAtCharLast = new vscode.Position(lastLine, lastChar); - const range = - args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast); - - editDecorationManager.addDecorations(editor, [range]); - - const rangeInFileWithContents = getRangeInFileWithContents(true, range); - - if (rangeInFileWithContents) { - sidebar.webviewProtocol?.request( - "addCodeToEdit", - rangeInFileWithContents, - ); - - // Un-select the current selection - editor.selection = new vscode.Selection( - editor.selection.anchor, - editor.selection.anchor, - ); - } - }, - "continue.focusEditWithoutClear": async () => { - captureCommandTelemetry("focusEditWithoutClear"); - focusGUI(); - - sidebar.webviewProtocol?.request("focusEditWithoutClear", undefined); - - const editor = vscode.window.activeTextEditor; - - if (!editor) { - return; - } - - const document = editor.document; - - const existingDiff = verticalDiffManager.getHandlerForFile( - document.fileName, - ); - - // If there's a diff currently being applied, then we just toggle focus back to the input - if (existingDiff) { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - return; - } - - const rangeInFileWithContents = getRangeInFileWithContents(false); - - if (rangeInFileWithContents) { - sidebar.webviewProtocol?.request( - "addCodeToEdit", - rangeInFileWithContents, - ); - } else { - const contents = document.getText(); - - sidebar.webviewProtocol?.request("addCodeToEdit", { - filepath: document.uri.toString(), - contents, - }); - } }, "continue.exitEditMode": async () => { captureCommandTelemetry("exitEditMode"); @@ -951,7 +703,7 @@ const getCommandsMap: ( if (core.configHandler.currentProfile?.profileDescription.id) { core.invoke("config/updateSelectedModel", { profileId: - core.configHandler.currentProfile?.profileDescription.id, + core.configHandler.currentProfile?.profileDescription.id, role: "autocomplete", title: selectedOption, }); @@ -1013,6 +765,35 @@ const getCommandsMap: ( ); } }, + "continue.convertConfigJsonToConfigYaml": async () => { + const configJson = fs.readFileSync(getConfigJsonPath(), "utf-8"); + const parsed = JSON.parse(configJson); + const configYaml = convertJsonToYamlConfig(parsed); + + const configYamlPath = getConfigYamlPath(); + fs.writeFileSync(configYamlPath, YAML.stringify(configYaml)); + + // Open config.yaml + await openEditorAndRevealRange( + vscode.Uri.file(configYamlPath), + undefined, + undefined, + false, + ); + + vscode.window + .showInformationMessage( + "Your config.json has been converted to the new config.yaml format. If you need to switch back to config.json, you can delete or rename config.yaml.", + "Read the docs", + ) + .then((selection) => { + if (selection === "Read the docs") { + vscode.env.openExternal( + vscode.Uri.parse("https://docs.continue.dev/yaml-migration"), + ); + } + }); + }, }; }; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 49de7f758..8b33a37fa 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -15,8 +15,10 @@ import { import { stripImages } from "core/util/messageContent"; import * as vscode from "vscode"; +import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { ApplyManager } from "../apply"; import { VerticalDiffManager } from "../diff/vertical/manager"; +import { addCurrentSelectionToEdit } from "../quickEdit/AddCurrentSelection"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { getControlPlaneSessionInfo, @@ -188,6 +190,15 @@ export class VsCodeMessenger { ); }); }); + this.onWebview("edit/addCurrentSelection", async (msg) => { + const verticalDiffManager = await this.verticalDiffManagerPromise; + await addCurrentSelectionToEdit({ + args: undefined, + editDecorationManager, + webviewProtocol: this.webviewProtocol, + verticalDiffManager, + }); + }); this.onWebview("edit/sendPrompt", async (msg) => { const prompt = msg.data.prompt; const { start, end } = msg.data.range.range; @@ -210,39 +221,28 @@ export class VsCodeMessenger { const fileAfterEdit = await verticalDiffManager.streamEdit({ input: stripImages(prompt), llm: model, - streamId: "edit", + streamId: EDIT_MODE_STREAM_ID, range: new vscode.Range( new vscode.Position(start.line, start.character), new vscode.Position(end.line, end.character), ), rules: config.rules, }); - - void this.webviewProtocol.request("setEditStatus", { - status: "accepting", - fileAfterEdit, - }); + return fileAfterEdit; }); - this.onWebview("edit/exit", async (msg) => { - if (msg.data.shouldFocusEditor) { - const activeEditor = vscode.window.activeTextEditor; - - if (activeEditor) { - vscode.window.showTextDocument(activeEditor.document); - } - } + this.onWebview("edit/clearDecorations", async (msg) => { editDecorationManager.clear(); }); /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/ WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => { this.onWebview(messageType, async (msg) => { - return await this.inProcessMessenger.externalRequest( - messageType, - msg.data, - msg.messageId, - ); + return await this.inProcessMessenger.externalRequest( + messageType, + msg.data, + msg.messageId, + ); }); }); diff --git a/extensions/vscode/src/lang-server/codeLens/providers/ConfigJsonConverterCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/ConfigJsonConverterCodeLensProvider.ts new file mode 100644 index 000000000..cb9bdfc6a --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/ConfigJsonConverterCodeLensProvider.ts @@ -0,0 +1,30 @@ +import { getConfigYamlPath } from "core/util/paths"; +import * as fs from "fs"; +import * as vscode from "vscode"; + +export class ConfigJsonConverterCodeLensProvider + implements vscode.CodeLensProvider +{ + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + if ( + !document.uri.fsPath.includes(".continue") || + !document.uri.fsPath.endsWith("config.json") + ) { + return []; + } + + if (fs.existsSync(getConfigYamlPath())) { + return []; + } + + return [ + new vscode.CodeLens(new vscode.Range(0, 0, 0, 0), { + title: "config.json is being deprecated. Convert to config.yaml", + command: "continue.convertConfigJsonToConfigYaml", + }), + ]; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/index.ts b/extensions/vscode/src/lang-server/codeLens/providers/index.ts index 03d89aa44..fc120d002 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/index.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/index.ts @@ -2,3 +2,5 @@ export { DownloadYamlExtensionCodeLensProvider } from "./DownloadYamlExtensionCo export { QuickActionsCodeLensProvider } from "./QuickActionsCodeLensProvider"; export { SuggestionsCodeLensProvider } from "./SuggestionsCodeLensProvider"; export { VerticalDiffCodeLensProvider as VerticalPerLineCodeLensProvider } from "./VerticalPerLineCodeLensProvider"; + +export { ConfigJsonConverterCodeLensProvider } from "./ConfigJsonConverterCodeLensProvider"; diff --git a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts index e17312fa0..0488aa61a 100644 --- a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts +++ b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts @@ -19,6 +19,8 @@ let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined; let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined; let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined; let quickActionsCodeLensDisposable: vscode.Disposable | undefined = undefined; +let configJsonConverterCodeLensDisposable: vscode.Disposable | undefined = + undefined; let downloadYamlExtensionCodeLensDisposable: vscode.Disposable | undefined = undefined; @@ -98,6 +100,10 @@ export function registerAllCodeLensProviders( tutorialCodeLensDisposable.dispose(); } + if (configJsonConverterCodeLensDisposable) { + configJsonConverterCodeLensDisposable.dispose(); + } + if (downloadYamlExtensionCodeLensDisposable) { downloadYamlExtensionCodeLensDisposable.dispose(); } @@ -116,6 +122,11 @@ export function registerAllCodeLensProviders( new providers.SuggestionsCodeLensProvider(), ); + configJsonConverterCodeLensDisposable = registerCodeLensProvider( + "*", + new providers.ConfigJsonConverterCodeLensProvider(), + ); + downloadYamlExtensionCodeLensDisposable = registerCodeLensProvider( "yaml", new providers.DownloadYamlExtensionCodeLensProvider(), @@ -131,6 +142,7 @@ export function registerAllCodeLensProviders( context.subscriptions.push(verticalPerLineCodeLensProvider); context.subscriptions.push(suggestionsCodeLensDisposable); + context.subscriptions.push(configJsonConverterCodeLensDisposable); return { verticalDiffCodeLens }; } diff --git a/extensions/vscode/src/quickEdit/AddCurrentSelection.ts b/extensions/vscode/src/quickEdit/AddCurrentSelection.ts new file mode 100644 index 000000000..7c0a8efef --- /dev/null +++ b/extensions/vscode/src/quickEdit/AddCurrentSelection.ts @@ -0,0 +1,70 @@ +import * as vscode from "vscode"; +import { VerticalDiffManager } from "../diff/vertical/manager"; +import { getRangeInFileWithContents } from "../util/addCode"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import EditDecorationManager from "./EditDecorationManager"; +import { QuickEditShowParams } from "./QuickEditQuickPick"; + +export async function addCurrentSelectionToEdit({ + webviewProtocol, + verticalDiffManager, + args, + editDecorationManager, +}: { + webviewProtocol: VsCodeWebviewProtocol; + verticalDiffManager: VerticalDiffManager; + args: QuickEditShowParams | undefined; + editDecorationManager: EditDecorationManager; +}) { + const editor = vscode.window.activeTextEditor; + + if (!editor) { + return; + } + + const existingDiff = verticalDiffManager.getHandlerForFile( + editor.document.fileName, + ); + + // If there's a diff currently being applied, then we just toggle focus back to the input + if (existingDiff) { + webviewProtocol?.request("focusContinueInput", undefined); + return; + } + + const startFromCharZero = editor.selection.start.with(undefined, 0); + const document = editor.document; + let lastLine, lastChar; + // If the user selected onto a trailing line but didn't actually include any characters in it + // they don't want to include that line, so trim it off. + if (editor.selection.end.character === 0) { + // This is to prevent the rare case that the previous line gets selected when user + // is selecting nothing and the cursor is at the beginning of the line + if (editor.selection.end.line === editor.selection.start.line) { + lastLine = editor.selection.start.line; + } else { + lastLine = editor.selection.end.line - 1; + } + } else { + lastLine = editor.selection.end.line; + } + lastChar = document.lineAt(lastLine).range.end.character; + const endAtCharLast = new vscode.Position(lastLine, lastChar); + const range = + args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast); + + editDecorationManager.clear(); + editDecorationManager.addDecorations(editor, [range]); + + const rangeInFileWithContents = getRangeInFileWithContents(true, range); + + if (rangeInFileWithContents) { + webviewProtocol?.request("setCodeToEdit", rangeInFileWithContents); + + // Un-select the current selection + editor.selection = new vscode.Selection( + editor.selection.anchor, + editor.selection.anchor, + ); + } +} diff --git a/extensions/vscode/src/util/addCode.ts b/extensions/vscode/src/util/addCode.ts new file mode 100644 index 000000000..a056cbfd2 --- /dev/null +++ b/extensions/vscode/src/util/addCode.ts @@ -0,0 +1,158 @@ +import { RangeInFileWithContents } from "core"; +import * as os from "node:os"; +import * as vscode from "vscode"; +import type { VsCodeWebviewProtocol } from "../webviewProtocol"; + +export function getRangeInFileWithContents( + allowEmpty?: boolean, + range?: vscode.Range, +): RangeInFileWithContents | null { + const editor = vscode.window.activeTextEditor; + + if (editor) { + const selection = editor.selection; + const filepath = editor.document.uri.toString(); + + if (range) { + const contents = editor.document.getText(range); + + return { + range: { + start: { + line: range.start.line, + character: range.start.character, + }, + end: { + line: range.end.line, + character: range.end.character, + }, + }, + filepath, + contents, + }; + } + + if (selection.isEmpty && !allowEmpty) { + return null; + } + + let selectionRange = new vscode.Range(selection.start, selection.end); + const document = editor.document; + // Select the context from the beginning of the selection start line to the selection start position + const beginningOfSelectionStartLine = selection.start.with(undefined, 0); + const textBeforeSelectionStart = document.getText( + new vscode.Range(beginningOfSelectionStartLine, selection.start), + ); + // If there are only whitespace before the start of the selection, include the indentation + if (textBeforeSelectionStart.trim().length === 0) { + selectionRange = selectionRange.with({ + start: beginningOfSelectionStartLine, + }); + } + + const contents = editor.document.getText(selectionRange); + + return { + filepath, + contents, + range: { + start: { + line: selection.start.line, + character: selection.start.character, + }, + end: { + line: selection.end.line, + character: selection.end.character, + }, + }, + }; + } + + return null; +} + +export async function addHighlightedCodeToContext( + webviewProtocol: VsCodeWebviewProtocol | undefined, +) { + const rangeInFileWithContents = getRangeInFileWithContents(); + if (rangeInFileWithContents) { + webviewProtocol?.request("highlightedCode", { + rangeInFileWithContents, + }); + } +} + +export async function addEntireFileToContext( + uri: vscode.Uri, + webviewProtocol: VsCodeWebviewProtocol | undefined, +) { + // If a directory, add all files in the directory + const stat = await vscode.workspace.fs.stat(uri); + if (stat.type === vscode.FileType.Directory) { + const files = await vscode.workspace.fs.readDirectory(uri); + for (const [filename, type] of files) { + if (type === vscode.FileType.File) { + addEntireFileToContext( + vscode.Uri.joinPath(uri, filename), + webviewProtocol, + ); + } + } + return; + } + + // Get the contents of the file + const contents = (await vscode.workspace.fs.readFile(uri)).toString(); + const rangeInFileWithContents = { + filepath: uri.toString(), + contents: contents, + range: { + start: { + line: 0, + character: 0, + }, + end: { + line: contents.split(os.EOL).length - 1, + character: 0, + }, + }, + }; + + webviewProtocol?.request("highlightedCode", { + rangeInFileWithContents, + }); +} + +export function addCodeToContextFromRange( + range: vscode.Range, + webviewProtocol: VsCodeWebviewProtocol, + prompt?: string, +) { + const document = vscode.window.activeTextEditor?.document; + + if (!document) { + return; + } + + const rangeInFileWithContents = { + filepath: document.uri.toString(), + contents: document.getText(range), + range: { + start: { + line: range.start.line, + character: range.start.character, + }, + end: { + line: range.end.line, + character: range.end.character, + }, + }, + }; + + webviewProtocol?.request("highlightedCode", { + rangeInFileWithContents, + prompt, + // Assume `true` since range selection is currently only used for quick actions/fixes + shouldRun: true, + }); +} diff --git a/gui/.eslintrc.json b/gui/.eslintrc.json index c902e379f..462fd5592 100644 --- a/gui/.eslintrc.json +++ b/gui/.eslintrc.json @@ -12,7 +12,8 @@ // "plugin:react/recommended" ], "rules": { - "@typescript-eslint/naming-convention": "off" + "@typescript-eslint/naming-convention": "off", + "@typescript-eslint/no-floating-promises": "warn" }, "overrides": [ { diff --git a/gui/package-lock.json b/gui/package-lock.json index e4a7c0b67..579d35a6a 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -94,7 +94,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^6.3.2", + "vite": "^6.3.4", "vitest": "^2.1.3" }, "engines": { @@ -111,7 +111,7 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.4", + "@continuedev/fetch": "^1.0.6", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", @@ -12374,17 +12374,18 @@ } }, "node_modules/vite": { - "version": "6.3.2", - "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.2.tgz", - "integrity": "sha512-ZSvGOXKGceizRQIZSz7TGJ0pS3QLlVY/9hwxVh17W3re67je1RKYzFHivZ/t0tubU78Vkyb9WnHPENSBCzbckg==", + "version": "6.3.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.4.tgz", + "integrity": "sha512-BiReIiMS2fyFqbqNT/Qqt4CVITDU9M9vE+DKcVAsB+ZV0wvTKd+3hMbkpxz1b+NmEDMegpVbisKiAZOnvO92Sw==", "dev": true, + "license": "MIT", "dependencies": { "esbuild": "^0.25.0", - "fdir": "^6.4.3", + "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", - "tinyglobby": "^0.2.12" + "tinyglobby": "^0.2.13" }, "bin": { "vite": "bin/vite.js" diff --git a/gui/package.json b/gui/package.json index 8b927add3..4710796ea 100644 --- a/gui/package.json +++ b/gui/package.json @@ -102,7 +102,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^6.3.2", + "vite": "^6.3.4", "vitest": "^2.1.3" }, "engine-strict": true, diff --git a/gui/public/logos/venice.png b/gui/public/logos/venice.png new file mode 100644 index 000000000..be0d8eb5f Binary files /dev/null and b/gui/public/logos/venice.png differ diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 2f3a94dd8..03b6fb05a 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -3,7 +3,7 @@ import Layout from "./components/Layout"; import { MainEditorProvider } from "./components/mainInput/TipTapEditor"; import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; -import useSetup from "./hooks/useSetup"; +import ParallelListeners from "./hooks/ParallelListeners"; import ConfigPage from "./pages/config"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; @@ -42,14 +42,9 @@ const router = createMemoryRouter([ ]); /* - Prevents entire app from rerendering continuously with useSetup in App - TODO - look into a more redux-esque way to do this + ParallelListeners prevents entire app from rerendering on any change in the listeners, + most of which interact with redux etc. */ -export function SetupListeners() { - useSetup(); - return <>; -} - function App() { return ( @@ -58,7 +53,7 @@ function App() { - + ); } diff --git a/gui/src/components/AcceptRejectAllButtons.tsx b/gui/src/components/AcceptRejectAllButtons.tsx index 7a9c28062..6f6147ad2 100644 --- a/gui/src/components/AcceptRejectAllButtons.tsx +++ b/gui/src/components/AcceptRejectAllButtons.tsx @@ -2,24 +2,26 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; import { useContext } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; -import { useAppSelector } from "../redux/hooks"; -import { selectIsSingleRangeEditOrInsertion } from "../redux/slices/sessionSlice"; import { getMetaKeyLabel } from "../util"; +import { useFontSize } from "./ui/font"; export interface AcceptRejectAllButtonsProps { - pendingApplyStates: ApplyState[]; + applyStates: ApplyState[]; onAcceptOrReject?: (outcome: AcceptOrRejectOutcome) => void; } export type AcceptOrRejectOutcome = "acceptDiff" | "rejectDiff"; export default function AcceptRejectAllButtons({ - pendingApplyStates, + applyStates, onAcceptOrReject, }: AcceptRejectAllButtonsProps) { + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); const ideMessenger = useContext(IdeMessengerContext); - const isSingleRangeEdit = useAppSelector(selectIsSingleRangeEditOrInsertion); + const tinyFont = useFontSize(-3); async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { for (const { filepath = "", streamId } of pendingApplyStates) { ideMessenger.post(status, { @@ -33,39 +35,50 @@ export default function AcceptRejectAllButtons({ } } + if (!pendingApplyStates.length) { + return null; + } + return ( -
+
); diff --git a/gui/src/components/CodeToEditCard/AddFileButton.tsx b/gui/src/components/CodeToEditCard/AddFileButton.tsx deleted file mode 100644 index d051f847f..000000000 --- a/gui/src/components/CodeToEditCard/AddFileButton.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; -import { useContext, useRef } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppDispatch } from "../../redux/hooks"; -import { addCodeToEdit } from "../../redux/slices/sessionSlice"; -import { - Listbox, - ListboxButton, - ListboxOption, - ListboxOptions, -} from "../ui/Listbox"; - -export interface AddFileButtonProps { - onClick: () => void; -} - -export default function AddFileButton({ onClick }: AddFileButtonProps) { - const buttonRef = useRef(null); - const ideMessenger = useContext(IdeMessengerContext); - const dispatch = useAppDispatch(); - - async function handleAddAllOpenFiles() { - const openFiles = await ideMessenger.ide.getOpenFiles(); - const filesData = await Promise.all( - openFiles.map(async (filepath) => { - const contents = await ideMessenger.ide.readFile(filepath); - return { filepath, contents }; - }), - ); - - dispatch(addCodeToEdit(filesData)); - } - - return ( - -
- -
{ - e.preventDefault(); - e.stopPropagation(); - onClick(); - }} - > - - - Add file - -
- -
- - - - - - Add all open files - -
- - ); -} diff --git a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx deleted file mode 100644 index 1d2e62942..000000000 --- a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx +++ /dev/null @@ -1,143 +0,0 @@ -import { ContextSubmenuItemWithProvider } from "core"; -import { useEffect, useRef, useState } from "react"; -import { - Combobox, - ComboboxButton, - ComboboxInput, - ComboboxOption, - ComboboxOptions, -} from "../../components/ui/Combobox"; -import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders"; -import { useAppSelector } from "../../redux/hooks"; -import FileIcon from "../FileIcon"; -export interface AddFileComboboxProps { - onSelect: (filepaths: string[]) => void | Promise; - onEscape: () => void | Promise; -} - -export default function AddFileCombobox({ - onSelect, - onEscape, -}: AddFileComboboxProps) { - const [query, setQuery] = useState(""); - const [selectedFiles, setSelectedFiles] = useState< - ContextSubmenuItemWithProvider[] - >([]); - - const inputRef = useRef(null); - const buttonRef = useRef(null); - const { getSubmenuContextItems } = useSubmenuContextProviders(); - const allFiles = getSubmenuContextItems("file", ""); - const codeToEdit = useAppSelector((state) => state.session.codeToEdit); - const remainingFiles = allFiles.filter( - (file) => !codeToEdit.find((code) => code.filepath === file.id), - ); - - useEffect(() => { - if (inputRef.current) { - inputRef.current.focus(); - } - }, []); - - useEffect(() => { - // update selectedFiles showing only the files that are in codeToEdit - setSelectedFiles( - (prevSelectedFiles) => - prevSelectedFiles.filter( - (file) => - codeToEdit.findIndex((code) => code.filepath === file.id) !== -1, - ), - ); - }, [codeToEdit]); - - const filteredFiles = - query === "" - ? remainingFiles - : remainingFiles.filter((file) => - file.title.toLowerCase().includes(query.toLowerCase()), - ); - - return ( -
- { - setSelectedFiles(files); - void onSelect(files.map((file) => file.id)); - buttonRef.current?.click(); - setQuery(""); - }} - > - {({ open }) => ( -
- - { - if (!open) { - buttonRef.current?.click(); - } - }} - onFocus={() => { - buttonRef.current?.click(); - }} - className="bg-vsc-background border-lightgray text-vsc-foreground box-border w-full rounded border border-solid py-0.5 pl-2 text-xs focus:outline-none" - onChange={(event) => setQuery(event.target.value)} - placeholder="Type to search files..." - onKeyDown={(e) => { - if (e.key === "Escape" && !open) { - void onEscape(); - } - }} - /> - - - {filteredFiles.length > 0 ? ( - filteredFiles.map((file) => ( - - `relative flex w-full cursor-pointer px-2 py-1 text-left text-xs ${ - active - ? "bg-list-active text-list-active-foreground" - : "" - }` - } - > - {({ active, selected }) => ( -
-
- - {file.title} -
- - - {file.description} - -
- )} -
- )) - ) : ( -
- No results -
- )} -
-
- )} -
-
- ); -} diff --git a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx deleted file mode 100644 index 6e16d4d4f..000000000 --- a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import type { CodeToEdit } from "core"; -import { useContext, useState } from "react"; -import { useDispatch } from "react-redux"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; -import { - addCodeToEdit, - removeCodeToEdit, -} from "../../redux/slices/sessionSlice"; -import AddFileButton from "./AddFileButton"; -import AddFileCombobox from "./AddFileCombobox"; -import CodeToEditListItem from "./CodeToEditListItem"; - -export default function CodeToEditCard() { - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const [showAddFileCombobox, setShowAddFileCombobox] = useState(false); - const codeToEdit = useAppSelector((state) => state.session.codeToEdit); - - const itemCount = - codeToEdit.length === 0 - ? "" - : codeToEdit.length === 1 - ? "(1 item)" - : `(${codeToEdit.length} items)`; - - function onDelete(rif: CodeToEdit) { - dispatch(removeCodeToEdit(rif)); - } - - async function onClickFilename(code: CodeToEdit) { - if ("range" in code) { - await ideMessenger.ide.showLines( - code.filepath, - code.range.start.line, - code.range.end.line, - ); - } else { - await ideMessenger.ide.openFile(code.filepath); - } - } - - async function onSelectFilesToAdd(uris: string[]) { - const filePromises = uris.map(async (uri) => { - const contents = await ideMessenger.ide.readFile(uri); - return { contents, filepath: uri }; - }); - - const fileResults = await Promise.all(filePromises); - - for (const file of fileResults) { - dispatch(addCodeToEdit(file)); - } - } - - return ( -
-
-
- Code to edit - {itemCount} -
- - setShowAddFileCombobox(true)} /> -
- - {codeToEdit.length > 0 ? ( -
    - {codeToEdit.map((code, i) => ( - - ))} -
- ) : ( - !showAddFileCombobox && ( -
setShowAddFileCombobox(true)} - > - - Add a file to get started -
- ) - )} - - {showAddFileCombobox && ( -
-
- setShowAddFileCombobox(false)} - /> -
- { - setShowAddFileCombobox(false); - }} - className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground mb-2 h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20" - /> -
- )} -
- ); -} diff --git a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx deleted file mode 100644 index 9651ec235..000000000 --- a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx +++ /dev/null @@ -1,142 +0,0 @@ -import { - ChevronDownIcon, - ChevronRightIcon, - XMarkIcon, -} from "@heroicons/react/24/outline"; -import { CodeToEdit } from "core"; -import { getMarkdownLanguageTagForFile } from "core/util"; -import { - getLastNUriRelativePathParts, - getUriPathBasename, -} from "core/util/uri"; -import { useState } from "react"; -import styled from "styled-components"; -import FileIcon from "../FileIcon"; -import StyledMarkdownPreview from "../StyledMarkdownPreview"; - -export interface CodeToEditListItemProps { - code: CodeToEdit; - onDelete: (codeToEdit: CodeToEdit) => void | Promise; - onClickFilename: (codeToEdit: CodeToEdit) => void | Promise; -} - -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 fileName = getUriPathBasename(code.filepath); - const last2Parts = getLastNUriRelativePathParts( - window.workspacePaths ?? [], - code.filepath, - 2, - ); - - let isInsertion = false; - let title = fileName; - - 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(); - void onClickFilename(code); - }} - > - {title} - - - {last2Parts} - -
    -
    - -
    -
    - {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(); - void 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 deleted file mode 100644 index 2e7d342eb..000000000 --- a/gui/src/components/CodeToEditCard/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from "./CodeToEditCard"; diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 8b7f3ba38..91854a274 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -6,6 +6,7 @@ import { useNavigate } from "react-router-dom"; import { Input } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { exitEditMode } from "../../redux/thunks/editMode"; import { deleteSession, getSession, @@ -68,6 +69,7 @@ export function HistoryTableRow({ data-testid={`history-row-${index}`} className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3" onClick={async () => { + await dispatch(exitEditMode({})); if (sessionMetadata.sessionId !== currentSessionId) { await dispatch( loadSession({ diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 0c5acda83..a6368eab4 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -1,21 +1,16 @@ -import { useEffect } from "react"; +import { useContext, useEffect } from "react"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; import { CustomScrollbarDiv, defaultBorderRadius } from "."; import { AuthProvider } from "../context/Auth"; +import { IdeMessengerContext } from "../context/IdeMessenger"; import { LocalStorageProvider } from "../context/LocalStorage"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; -import { focusEdit, setEditStatus } from "../redux/slices/editModeState"; -import { - addCodeToEdit, - newSession, - selectIsInEditMode, - setMode, -} from "../redux/slices/sessionSlice"; +import { setCodeToEdit } from "../redux/slices/editModeState"; import { setShowDialog } from "../redux/slices/uiSlice"; -import { exitEditMode } from "../redux/thunks"; -import { loadLastSession, saveCurrentSession } from "../redux/thunks/session"; +import { enterEditMode, exitEditMode } from "../redux/thunks/editMode"; +import { saveCurrentSession } from "../redux/thunks/session"; import { fontSize, isMetaEquivalentKeyPressed } from "../util"; import { incrementFreeTrialCount } from "../util/freeTrial"; import { ROUTES } from "../util/navigation"; @@ -23,6 +18,7 @@ import { FatalErrorIndicator } from "./config/FatalErrorNotice"; import TextDialog from "./dialogs"; import Footer from "./Footer"; import { LumpProvider } from "./mainInput/Lump/LumpContext"; +import { useMainEditor } from "./mainInput/TipTapEditor"; import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import OSRContextMenu from "./OSRContextMenu"; import PostHogPageView from "./PosthogPageView"; @@ -46,24 +42,30 @@ const Layout = () => { const location = useLocation(); const dispatch = useAppDispatch(); const onboardingCard = useOnboardingCard(); + const ideMessenger = useContext(IdeMessengerContext); + const { mainEditor } = useMainEditor(); const dialogMessage = useAppSelector((state) => state.ui.dialogMessage); const showDialog = useAppSelector((state) => state.ui.showDialog); + const mode = useAppSelector((state) => state.session.mode); useWebviewListener( "newSession", async () => { navigate(ROUTES.HOME); - await dispatch( - saveCurrentSession({ - openNewSession: true, - generateTitle: true, - }), - ); - dispatch(exitEditMode()); + if (mode === "edit") { + await dispatch(exitEditMode({})); + } else { + await dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: true, + }), + ); + } }, - [], + [mode], ); useWebviewListener( @@ -79,15 +81,22 @@ const Layout = () => { "focusContinueInputWithNewSession", async () => { navigate(ROUTES.HOME); - await dispatch( - saveCurrentSession({ - openNewSession: true, - generateTitle: true, - }), - ); - dispatch(exitEditMode()); + if (mode === "edit") { + await dispatch( + exitEditMode({ + openNewSession: true, + }), + ); + } else { + await dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: true, + }), + ); + } }, - [location.pathname], + [location.pathname, mode], location.pathname === ROUTES.HOME, ); @@ -138,66 +147,31 @@ const Layout = () => { useWebviewListener( "focusEdit", async () => { - await dispatch( - saveCurrentSession({ - openNewSession: false, - // Because this causes a lag before Edit mode is focused. TODO just have that happen in background - generateTitle: false, - }), - ); - dispatch(newSession()); - dispatch(focusEdit()); - dispatch(setMode("edit")); + await ideMessenger.request("edit/addCurrentSelection", undefined); + await dispatch(enterEditMode({})); + mainEditor?.commands.focus(); }, - [], + [ideMessenger, mainEditor], ); useWebviewListener( - "focusEditWithoutClear", - async () => { - await dispatch( - saveCurrentSession({ - openNewSession: true, - generateTitle: true, - }), - ); - dispatch(focusEdit()); - dispatch(setMode("edit")); - }, - [], - ); - - useWebviewListener( - "addCodeToEdit", + "setCodeToEdit", async (payload) => { - dispatch(addCodeToEdit(payload)); - }, - [navigate], - ); - - useWebviewListener( - "setEditStatus", - async ({ status, fileAfterEdit }) => { - dispatch(setEditStatus({ status, fileAfterEdit })); + dispatch( + setCodeToEdit({ + codeToEdit: payload, + }), + ); }, [], ); - const isInEditMode = useAppSelector(selectIsInEditMode); useWebviewListener( "exitEditMode", async () => { - if (!isInEditMode) { - return; - } - dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - dispatch(exitEditMode()); + await dispatch(exitEditMode({})); }, - [isInEditMode], + [], ); useEffect(() => { diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx similarity index 97% rename from gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx rename to gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx index 7e99f430d..b0cc6f179 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx @@ -12,9 +12,9 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch } from "../../../redux/hooks"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { updateSelectedModelByRole } from "../../../redux/thunks"; -import OllamaModelDownload from "../components/OllamaModelDownload"; -import { OllamaStatus } from "../components/OllamaStatus"; import { useSubmitOnboarding } from "../hooks"; +import OllamaModelDownload from "./OllamaModelDownload"; +import { OllamaStatus } from "./OllamaStatus"; const OLLAMA_CHECK_INTERVAL_MS = 3000; diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx index 69eed3ffb..883ea66d1 100644 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx @@ -5,8 +5,8 @@ import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; import Alert from "../../gui/Alert"; import { ReusableCard } from "../../ReusableCard"; import { TabTitle } from "../components/OnboardingCardTabs"; +import OnboardingLocalTab from "../components/OnboardingLocalTab"; import { useOnboardingCard } from "../hooks"; -import OnboardingLocalTab from "../tabs/OnboardingLocalTab"; import MainTab from "./tabs/main"; export interface OnboardingCardState { diff --git a/gui/src/components/OnboardingCard/tabs/index.ts b/gui/src/components/OnboardingCard/tabs/index.ts index 7e975a8ec..1e6aae37d 100644 --- a/gui/src/components/OnboardingCard/tabs/index.ts +++ b/gui/src/components/OnboardingCard/tabs/index.ts @@ -1,3 +1,3 @@ +export { default as Local } from "../components/OnboardingLocalTab"; export { default as Best } from "./OnboardingBestTab"; -export { default as Local } from "./OnboardingLocalTab"; export { default as Quickstart } from "./OnboardingQuickstartTab"; diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx deleted file mode 100644 index 08a61e2e3..000000000 --- a/gui/src/components/StepContainer/EditActions.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { ChatHistoryItem } from "core"; - -import { renderChatMessage } from "core/util/messageContent"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { exitEditMode } from "../../redux/thunks/exitEditMode"; -import { loadLastSession } from "../../redux/thunks/session"; -import AcceptRejectAllButtons from "../AcceptRejectAllButtons"; -import FeedbackButtons from "../FeedbackButtons"; -import { CopyIconButton } from "../gui/CopyIconButton"; - -export interface EditActionsProps { - index: number; - item: ChatHistoryItem; -} - -export default function EditActions({ index, item }: EditActionsProps) { - // const curCheckpointIndex = useSelector( - // (store: RootState) => store.state.curCheckpointIndex, - // ); - const dispatch = useAppDispatch(); - - const isStreaming = useAppSelector((state) => state.session.isStreaming); - - const applyStates = useAppSelector( - (state) => state.session.codeBlockApplyStates.states, - ); - - const pendingApplyStates = applyStates.filter( - (state) => state.status === "done", - ); - - const hasClosedAllStreams = applyStates.every( - (state) => state.status === "closed", - ); - - // const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; - const hasPendingApplies = pendingApplyStates.length > 0; - - if (isStreaming) return null; - - return ( -
    -
    - - {/* {isCurCheckpoint && ( -
    - {hasPendingApplies && ( - - )} - {hasClosedAllStreams && } -
    - )} */} - -
    - {hasPendingApplies && ( - { - if (outcome === "acceptDiff") { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - dispatch(exitEditMode()); - } - }} - /> - )} - {/* {hasClosedAllStreams && } */} -
    - -
    - - - -
    -
    - ); -} diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index dce39ea6f..5bd7f3a54 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -1,12 +1,9 @@ import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; import { renderChatMessage } from "core/util/messageContent"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsInEditMode } from "../../redux/slices/sessionSlice"; import FeedbackButtons from "../FeedbackButtons"; import { CopyIconButton } from "../gui/CopyIconButton"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import EditActions from "./EditActions"; export interface ResponseActionsProps { isTruncated: boolean; @@ -23,12 +20,6 @@ export default function ResponseActions({ isTruncated, onDelete, }: ResponseActionsProps) { - const isInEditMode = useAppSelector(selectIsInEditMode); - - if (isInEditMode) { - return ; - } - return (
    {isTruncated && ( diff --git a/gui/src/components/StepContainer/UndoAndRedoButtons.tsx b/gui/src/components/StepContainer/UndoAndRedoButtons.tsx deleted file mode 100644 index e0e57c3e1..000000000 --- a/gui/src/components/StepContainer/UndoAndRedoButtons.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import { useDispatch } from "react-redux"; -import { - ArrowUturnLeftIcon, - ArrowUturnRightIcon, -} from "@heroicons/react/24/outline"; -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 history = useAppSelector((store) => store.session.history); - - const curCheckpointIndex = useAppSelector( - (store) => store.session.curCheckpointIndex, - ); - - const shouldRenderRedo = false; // curCheckpointIndex !== checkpoints.length - 1; - - async function handleUndoOrRedo(type: "undo" | "redo") { - const checkpointIndex = Math.max( - 0, - type === "undo" ? curCheckpointIndex - 1 : curCheckpointIndex + 1, - ); - - const checkpoint = history[checkpointIndex]?.checkpoint ?? {}; - - for (const [filepath, cachedFileContent] of Object.entries(checkpoint)) { - ideMessenger.post("overwriteFile", { - filepath, - prevFileContent: cachedFileContent, - }); - } - - dispatch(setCurCheckpointIndex(checkpointIndex)); - } - - return ( -
    - - - {shouldRenderRedo && ( - - )} -
    - ); -} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 6b299db18..44977514f 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -11,10 +11,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useIdeMessengerRequest } from "../../../hooks"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppSelector } from "../../../redux/hooks"; -import { - selectApplyStateByStreamId, - selectIsInEditMode, -} from "../../../redux/slices/sessionSlice"; +import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice"; import { getFontSize } from "../../../util"; import { isTerminalCodeBlock } from "../utils"; import { ApplyActions } from "./ApplyActions"; @@ -74,10 +71,7 @@ export function StepContainerPreToolbar({ disableManualApply, }: StepContainerPreToolbarProps) { const ideMessenger = useContext(IdeMessengerContext); - const isInEditMode = useAppSelector(selectIsInEditMode); - const [isExpanded, setIsExpanded] = useState( - expanded ?? (isInEditMode ? false : true), - ); + const [isExpanded, setIsExpanded] = useState(expanded ?? true); const [relativeFilepathUri, setRelativeFilepathUri] = useState( null, diff --git a/gui/src/components/dialogs/FreeTrialOverDialog.tsx b/gui/src/components/dialogs/FreeTrialOverDialog.tsx index 107e351ce..a200b2f15 100644 --- a/gui/src/components/dialogs/FreeTrialOverDialog.tsx +++ b/gui/src/components/dialogs/FreeTrialOverDialog.tsx @@ -1,15 +1,12 @@ import { useEffect } from "react"; import { useDispatch } from "react-redux"; import { useAppSelector } from "../../redux/hooks"; -import { selectUseHub } from "../../redux/selectors"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { OnboardingCard } from "../OnboardingCard"; import { PlatformOnboardingCard } from "../OnboardingCard/platform/PlatformOnboardingCard"; function FreeTrialOverDialog() { const dispatch = useDispatch(); const history = useAppSelector((store) => store.session.history); - const usePlatform = useAppSelector(selectUseHub); useEffect(() => { if (history.length === 0) { @@ -20,11 +17,7 @@ function FreeTrialOverDialog() { return (
    - {usePlatform ? ( - - ) : ( - - )} +
    ); } diff --git a/gui/src/components/mainInput/CodeToEditCard.tsx b/gui/src/components/mainInput/CodeToEditCard.tsx new file mode 100644 index 000000000..ae31bb684 --- /dev/null +++ b/gui/src/components/mainInput/CodeToEditCard.tsx @@ -0,0 +1,180 @@ +import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { CodeToEdit } from "core"; +import { getMarkdownLanguageTagForFile } from "core/util"; +import { getUriPathBasename } from "core/util/uri"; +import { useContext, useMemo, useState } from "react"; +import { useDispatch } from "react-redux"; +import styled from "styled-components"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppSelector } from "../../redux/hooks"; +import { clearCodeToEdit } from "../../redux/slices/editModeState"; +import { getMetaKeyLabel } from "../../util"; +import FileIcon from "../FileIcon"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; +import { useFontSize } from "../ui/font"; + +const NoPaddingWrapper = styled.div` + > * { + margin: 0 !important; + padding: 0 !important; + } + + pre { + margin: 0 !important; + padding: 0px 0px 0px 10px !important; + } +`; + +interface CodeToEditItemProps { + code: CodeToEdit; +} + +function CodeToEditItem({ code }: CodeToEditItemProps) { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const [showCodeSnippet, setShowCodeSnippet] = useState(false); + + function onDelete() { + dispatch(clearCodeToEdit()); + ideMessenger.post("edit/clearDecorations", undefined); + } + + const fileName = getUriPathBasename(code.filepath); + + let isInsertion = false; + let title = fileName; + + 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" + + "```"; + + async function onClickFilename() { + if ("range" in code) { + await ideMessenger.ide.showLines( + code.filepath, + code.range.start.line, + code.range.end.line, + ); + } else { + await ideMessenger.ide.openFile(code.filepath); + } + } + + const smallFont = useFontSize(-3); + + const iconClass = + "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"; + + return ( +
    +
    + + Code to edit + + {/* */} +
    { + if (!isInsertion) { + setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet); + } + }} + > +
    + + { + e.stopPropagation(); + void onClickFilename(); + }} + > + {title} + +
    + +
    + { + e.stopPropagation(); + setShowCodeSnippet((val) => !val); + }} + 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 ? "rotate-90" : ""} ${isInsertion ? "hidden" : ""}`} + /> +
    + { + e.stopPropagation(); + void onDelete(); + }} + className={iconClass} + /> +
    +
    +
    +
    + {showCodeSnippet && ( +
    + + + +
    + )} +
    + ); +} +export default function CodeToEditCard() { + // Array from previous multi-file edit + const codeToEditArray = useAppSelector( + (state) => state.editModeState.codeToEdit, + ); + const codeToEdit = useMemo(() => { + return codeToEditArray[0]; + }, [codeToEditArray]); + + const metaKeyLabel = useMemo(() => { + return getMetaKeyLabel(); + }, []); + + const tinyFont = useFontSize(-3); + + return ( +
    + {codeToEdit ? ( + + ) : ( + <> + + {`To edit code, highlight it and press `} + {metaKeyLabel} I + + + )} +
    + ); +} diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 14d4816f4..c9a151079 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -11,7 +11,6 @@ import { Lump } from "./Lump"; import { TipTapEditor } from "./TipTapEditor"; interface ContinueInputBoxProps { - isEditMode?: boolean; isLastUserInput: boolean; isMainInput?: boolean; onEnter: ( @@ -82,36 +81,40 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const availableContextProviders = useAppSelector( (state) => state.config.config.contextProviders, ); + const mode = useAppSelector((store) => store.session.mode); const editModeState = useAppSelector((state) => state.editModeState); - const filteredSlashCommands = props.isEditMode ? [] : availableSlashCommands; + const filteredSlashCommands = useMemo(() => { + return mode === "edit" ? [] : availableSlashCommands; + }, [mode, availableSlashCommands]); + const filteredContextProviders = useMemo(() => { - if (!props.isEditMode) { - return availableContextProviders ?? []; + if (mode === "edit") { + return ( + availableContextProviders?.filter( + (provider) => + !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), + ) ?? [] + ); } - return ( - availableContextProviders?.filter( - (provider) => - !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), - ) ?? [] - ); - }, [availableContextProviders]); + return availableContextProviders ?? []; + }, [availableContextProviders, mode]); - const historyKey = props.isEditMode ? "edit" : "chat"; - const placeholder = props.isEditMode - ? "Describe changes, '#' to add files" - : undefined; + const historyKey = mode === "edit" ? "edit" : "chat"; + const placeholder = mode === "edit" ? "Describe changes" : undefined; - const toolbarOptions: ToolbarOptions = props.isEditMode - ? { - hideAddContext: false, - hideImageUpload: false, - hideUseCodebase: true, - hideSelectModel: false, - enterText: editModeState.editStatus === "accepting" ? "Retry" : "Edit", - } - : {}; + const toolbarOptions: ToolbarOptions = + mode === "edit" + ? { + hideAddContext: false, + hideImageUpload: false, + hideUseCodebase: true, + hideSelectModel: false, + enterText: + editModeState.applyState.status === "done" ? "Retry" : "Edit", + } + : {}; return (
    { + const isStreaming = useAppSelector((store) => store.session.isStreaming); + const mode = useAppSelector((store) => store.session.mode); + const dispatch = useAppDispatch(); + const editApplyState = useAppSelector( + (store) => store.editModeState.applyState, + ); + const { mainEditor } = useMainEditor(); + const ideMessenger = useContext(IdeMessengerContext); + + if (mode !== "edit") { + return null; + } + if (isStreaming) { + return null; + } + if (editApplyState.status === "done") { + const plural = editApplyState.numDiffs === 1 ? "" : "s"; + return ( + <> +
    + {`${editApplyState.numDiffs} diff${plural} remaining`} +
    + { + if (outcome === "acceptDiff") { + await dispatch(exitEditMode({})); + ideMessenger.post("focusEditor", undefined); + } else { + mainEditor?.commands.focus(); + } + }} + /> + + ); + } + + // Will only still show if not all accepted + if (editApplyState.status === "closed") { + return ( +
    + +
    + ); + } + + // Not started/streaming + return null; +}; + +export default EditModeDetails; diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 4690f683d..1dca2e6bc 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -1,7 +1,8 @@ import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline"; import { InputModifiers } from "core"; import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect"; -import { useRef } from "react"; +import { useContext, useRef } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseActiveFile } from "../../redux/selectors"; import { @@ -9,12 +10,7 @@ import { selectCurrentToolCallApplyState, } from "../../redux/selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; -import { - selectHasCodeToEdit, - selectIsInEditMode, -} from "../../redux/slices/sessionSlice"; -import { exitEditMode } from "../../redux/thunks"; -import { loadLastSession } from "../../redux/thunks/session"; +import { exitEditMode } from "../../redux/thunks/editMode"; import { getAltKeyLabel, getMetaKeyLabel, @@ -49,20 +45,20 @@ interface InputToolbarProps { function InputToolbar(props: InputToolbarProps) { const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); const fileInputRef = useRef(null); const defaultModel = useAppSelector(selectSelectedChatModel); const useActiveFile = useAppSelector(selectUseActiveFile); - const isInEditMode = useAppSelector(selectIsInEditMode); - const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); + const mode = useAppSelector((store) => store.session.mode); + const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit); const toolCallState = useAppSelector(selectCurrentToolCall); - const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; const currentToolCallApplyState = useAppSelector( selectCurrentToolCallApplyState, ); const isEnterDisabled = props.disabled || - isEditModeAndNoCodeToEdit || + (mode === "edit" && codeToEdit.length === 0) || toolCallState?.status === "generated" || (currentToolCallApplyState && currentToolCallApplyState.status !== "closed"); @@ -91,13 +87,13 @@ function InputToolbar(props: InputToolbarProps) { }} >
    - + Select Mode - + Select Model @@ -158,7 +154,7 @@ function InputToolbar(props: InputToolbarProps) { fontSize: tinyFont, }} > - {!props.toolbarOptions?.hideUseCodebase && !isInEditMode && ( + {!props.toolbarOptions?.hideUseCodebase && mode !== "edit" && ( )} - {isInEditMode && ( + {mode === "edit" && ( { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - dispatch(exitEditMode()); + onClick={async () => { + dispatch(exitEditMode({})); + ideMessenger.post("focusEditor", undefined); }} > diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index b9b27aa92..eaf3771f8 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -12,9 +12,9 @@ import { import { ReactNode } from "react"; import { vscBadgeForeground } from "../.."; import { useAppSelector } from "../../../redux/hooks"; -import { fontSize } from "../../../util"; import { ToolTip } from "../../gui/Tooltip"; import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; +import { useFontSize } from "../../ui/font"; import HoverItem from "../InputToolbar/HoverItem"; import { useLump } from "./LumpContext"; import { ErrorsSectionTooltip } from "./sections/errors/ErrorsSectionTooltip"; @@ -74,8 +74,9 @@ function BlockSettingsToolbarIcon( const isErrorSection = props.sectionId === "error"; const id = `block-settings-toolbar-icon-${props.sectionId}`; - return ( + const fontSize = useFontSize(-3); + return ( <>
    - {props.tooltip} @@ -156,7 +156,7 @@ export function BlockSettingsTopToolbar() { ); return ( -
    +
    - + Select Assistant diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 77b6c4bd9..1c661cf3e 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -18,6 +18,7 @@ import { setDialogMessage, setShowDialog, } from "../../../../redux/slices/uiSlice"; +import { getBaseSystemMessage } from "../../../../util"; import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; import { useFontSize } from "../../../ui/font"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; @@ -182,8 +183,7 @@ export function RulesSection() { } // Add a displayed rule for the base system chat message when in chat mode if (mode === "chat" || mode === "agent") { - const baseMessage = - config.selectedModelByRole.chat?.baseChatSystemMessage; + const baseMessage = getBaseSystemMessage(config.selectedModelByRole.chat, mode) if (baseMessage) { rules.unshift({ rule: baseMessage, diff --git a/gui/src/components/mainInput/Lump/sections/errors/ErrorsSectionTooltip.tsx b/gui/src/components/mainInput/Lump/sections/errors/ErrorsSectionTooltip.tsx index fd2199ede..02a69d517 100644 --- a/gui/src/components/mainInput/Lump/sections/errors/ErrorsSectionTooltip.tsx +++ b/gui/src/components/mainInput/Lump/sections/errors/ErrorsSectionTooltip.tsx @@ -4,7 +4,7 @@ export const ErrorsSectionTooltip = () => { const configError = useAppSelector((store) => store.config.configError); const numErrors = configError?.length ?? 0; - const plural = numErrors > 1 ? "s" : ""; + const plural = numErrors === 1 ? "" : "s"; return (
    diff --git a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx index f5d172dc2..e9222bcbc 100644 --- a/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor/TipTapEditor.tsx @@ -7,7 +7,6 @@ import useIsOSREnabled from "../../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../../hooks/useUpdatingRef"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; -import { selectIsInEditMode } from "../../../redux/slices/sessionSlice"; import InputToolbar, { ToolbarOptions } from "../InputToolbar"; import { ComboBoxItem } from "../types"; import { DragOverlay, InputBoxDiv } from "./components"; @@ -48,9 +47,9 @@ export function TipTapEditor(props: TipTapEditorProps) { const defaultModel = useAppSelector(selectSelectedChatModel); const isStreaming = useAppSelector((state) => state.session.isStreaming); - const isInEditMode = useAppSelector(selectIsInEditMode); const historyLength = useAppSelector((store) => store.session.history.length); + const mode = useAppSelector((store) => store.session.mode); const { editor, onEnterRef } = createEditorConfig({ props, ideMessenger, @@ -82,13 +81,16 @@ export function TipTapEditor(props: TipTapEditorProps) { }, [editor, props.placeholder, historyLength]); useEffect(() => { - if (isInEditMode) { - setShouldHideToolbar(false); - } if (props.isMainInput) { editor?.commands.clearContent(true); } - }, [editor, isInEditMode, props.isMainInput]); + }, [editor, props.isMainInput]); + + useEffect(() => { + if (mode === "edit") { + setShouldHideToolbar(false); + } + }, [mode]); const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]); @@ -148,7 +150,7 @@ export function TipTapEditor(props: TipTapEditorProps) { const handleBlur = useCallback( (e: React.FocusEvent) => { - if (isInEditMode) { + if (mode === "edit") { return; } // Check if the new focus target is within our InputBoxDiv @@ -163,7 +165,7 @@ export function TipTapEditor(props: TipTapEditorProps) { setShouldHideToolbar(true); }, 100); }, - [isInEditMode, blurTimeout], + [mode, blurTimeout], ); const handleFocus = useCallback(() => { diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts b/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts deleted file mode 100644 index 87b524435..000000000 --- a/gui/src/components/mainInput/TipTapEditor/extensions/AddCodeToEdit.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { mergeAttributes, Node } from "@tiptap/core"; -import { PluginKey } from "@tiptap/pm/state"; -import Suggestion from "@tiptap/suggestion"; -import { MentionOptions } from "./types"; - -export const AddCodeToEdit = Node.create({ - name: "add-code-to-edit", - - addOptions() { - return { - HTMLAttributes: { - class: "add-code-to-edit", - }, - renderHTML({ options, node }) { - return [ - "span", - this.HTMLAttributes, - `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`, - ]; - }, - suggestion: { - char: "#", - pluginKey: new PluginKey(this.name), - allow: ({ state, range }) => { - const $from = state.doc.resolve(range.from); - const type = state.schema.nodes[this.name]; - const allow = !!$from.parent.type.contentMatch.matchType(type); - - // Check if there's a space after the "#" - const textFrom = range.from; - const textTo = state.selection.$to.pos; - const text = state.doc.textBetween(textFrom, textTo); - const hasSpace = text.includes(" "); - - return allow && !hasSpace; - }, - }, - }; - }, - - group: "inline", - - inline: true, - - selectable: false, - - atom: true, - - addAttributes() { - return { - id: { - default: null, - parseHTML: (element) => element.getAttribute("data-id"), - renderHTML: (attributes) => { - if (!attributes.id) { - return {}; - } - - return { - "data-id": attributes.id, - }; - }, - }, - - label: { - default: null, - parseHTML: (element) => element.getAttribute("data-label"), - renderHTML: (attributes) => { - if (!attributes.label) { - return {}; - } - - return { - "data-label": attributes.label, - }; - }, - }, - - renderInlineAs: { - default: null, - parseHTML: (element) => element.getAttribute("data-renderInlineAs"), - renderHTML: (attributes) => { - if (typeof attributes.renderInlineAs !== "string") { - return {}; - } - - return { - "data-renderInlineAs": attributes.renderInlineAs, - }; - }, - }, - - query: { - default: null, - parseHTML: (element) => element.getAttribute("data-query"), - renderHTML: (attributes) => { - if (!attributes.query) { - return {}; - } - - return { - "data-query": attributes.query, - }; - }, - }, - - itemType: { - default: null, - parseHTML: (element) => element.getAttribute("data-itemType"), - renderHTML: (attributes) => { - if (!attributes.itemType) { - return {}; - } - - return { - "data-itemType": attributes.itemType, - }; - }, - }, - }; - }, - - parseHTML() { - return [ - { - tag: `span[data-type="${this.name}"]`, - }, - ]; - }, - - renderHTML({ node, HTMLAttributes }) { - const html = this.options.renderHTML({ - options: this.options, - node, - }); - - if (typeof html === "string") { - return [ - "span", - mergeAttributes( - { "data-type": this.name }, - this.options.HTMLAttributes, - HTMLAttributes, - ), - html, - ]; - } - return html; - }, - - addKeyboardShortcuts() { - return { - Backspace: () => - this.editor.commands.command(({ tr, state }) => { - let isMention = false; - const { selection } = state; - const { empty, anchor } = selection; - - if (!empty) { - return false; - } - - state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => { - if (node.type.name === this.name) { - isMention = true; - tr.insertText( - this.options.suggestion.char || "", - pos, - pos + node.nodeSize, - ); - - return false; - } - }); - - return isMention; - }), - }; - }, - - addProseMirrorPlugins() { - return [ - Suggestion({ - editor: this.editor, - ...this.options.suggestion, - }), - ]; - }, -}); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts index 06426b9c3..717557fdc 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/index.ts +++ b/gui/src/components/mainInput/TipTapEditor/extensions/index.ts @@ -1,4 +1,3 @@ -export * from "./AddCodeToEdit"; export * from "./CodeBlock"; export * from "./Mention"; export * from "./Prompt"; diff --git a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts index 400f08019..1e6651e5f 100644 --- a/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts +++ b/gui/src/components/mainInput/TipTapEditor/useMainEditorWebviewListeners.ts @@ -3,10 +3,8 @@ import { InputModifiers } from "core"; import { rifWithContentsToContextItem } from "core/commands/util"; import { MutableRefObject } from "react"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import { - clearCodeToEdit, - setNewestToolbarPreviewForInput, -} from "../../../redux/slices/sessionSlice"; +import { clearCodeToEdit } from "../../../redux/slices/editModeState"; +import { setNewestToolbarPreviewForInput } from "../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../redux/store"; import { loadSession, saveCurrentSession } from "../../../redux/thunks/session"; import { CodeBlock, PromptBlock } from "./extensions"; @@ -158,26 +156,6 @@ export function useMainEditorWebviewListeners({ [editor, inputId, onEnterRef.current], ); - useWebviewListener( - "focusEdit", - async () => { - setTimeout(() => { - editor?.commands.focus("end"); - }, 20); - }, - [editor], - ); - - useWebviewListener( - "focusEditWithoutClear", - async () => { - setTimeout(() => { - editor?.commands.focus("end"); - }, 2000); - }, - [editor], - ); - useWebviewListener( "isContinueInputFocused", async () => { diff --git a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts index c4a70bb51..3fea17ad4 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/editorConfig.ts @@ -22,14 +22,8 @@ import useUpdatingRef from "../../../../hooks/useUpdatingRef"; import { useAppSelector } from "../../../../redux/hooks"; import { selectUseActiveFile } from "../../../../redux/selectors"; import { selectSelectedChatModel } from "../../../../redux/slices/configSlice"; -import { - addCodeToEdit, - selectHasCodeToEdit, - selectIsInEditMode, -} from "../../../../redux/slices/sessionSlice"; import { AppDispatch } from "../../../../redux/store"; -import { exitEditMode } from "../../../../redux/thunks"; -import { loadLastSession } from "../../../../redux/thunks/session"; +import { exitEditMode } from "../../../../redux/thunks/editMode"; import { getFontSize, isJetBrains } from "../../../../util"; import * as ContinueExtensions from "../extensions"; import { TipTapEditorProps } from "../TipTapEditor"; @@ -87,15 +81,14 @@ export function createEditorConfig(options: { const isStreaming = useAppSelector((state) => state.session.isStreaming); const useActiveFile = useAppSelector(selectUseActiveFile); const historyLength = useAppSelector((store) => store.session.history.length); - const isInEditMode = useAppSelector(selectIsInEditMode); - const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); - const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; + const mode = useAppSelector((store) => store.session.mode); + const modeRef = useUpdatingRef(mode); + const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit); const inSubmenuRef = useRef(undefined); const inDropdownRef = useRef(false); const defaultModelRef = useUpdatingRef(defaultModel); const isStreamingRef = useUpdatingRef(isStreaming); - const isInEditModeRef = useUpdatingRef(isInEditMode); const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems); const availableContextProvidersRef = useUpdatingRef( props.availableContextProviders, @@ -267,24 +260,23 @@ export function createEditorConfig(options: { return false; }, Escape: () => { + if (inDropdownRef.current) { + return false; + } // In JetBrains, this is how we close the sidebar when the input box is focused if (isJetBrains()) { ideMessenger.post("closeSidebar", undefined); return true; } - if (inDropdownRef.current || !isInEditModeRef.current) { - ideMessenger.post("focusEditor", undefined); - return true; - } - (async () => { - await dispatch( - loadLastSession({ - saveCurrentSession: false, + if (modeRef.current === "edit") { + dispatch( + exitEditMode({ + openNewSession: false, }), ); - dispatch(exitEditMode()); - })(); + } + ideMessenger.post("focusEditor", undefined); return true; }, @@ -325,42 +317,6 @@ export function createEditorConfig(options: { ideMessenger, ), }), - ContinueExtensions.AddCodeToEdit.configure({ - suggestion: { - ...getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - allow: () => isInEditModeRef.current, - command: async ({ editor, range, props }) => { - editor.chain().focus().insertContentAt(range, "").run(); - const filepath = props.id; - const contents = await ideMessenger.ide.readFile(filepath); - dispatch( - addCodeToEdit({ - filepath, - contents, - }), - ); - }, - items: async ({ query }) => { - // Only display files in the dropdown - const results = getSubmenuContextItemsRef.current("file", query); - return results.map((result) => ({ - ...result, - label: result.title, - type: "file", - query: result.id, - icon: result.icon, - })); - }, - }, - }), ContinueExtensions.SlashCommand.configure({ suggestion: getSlashCommandDropdownOptions( availableSlashCommandsRef, @@ -389,7 +345,7 @@ export function createEditorConfig(options: { if (!editor) { return; } - if (isStreaming || isEditModeAndNoCodeToEdit) { + if (isStreaming || (codeToEdit.length === 0 && mode === "edit")) { return; } @@ -406,7 +362,7 @@ export function createEditorConfig(options: { props.onEnter(json, modifiers, editor); }, - [props.onEnter, editor, props.isMainInput], + [props.onEnter, editor, props.isMainInput, codeToEdit, mode], ); return { editor, onEnterRef }; diff --git a/gui/src/components/modelSelection/ModeSelect.tsx b/gui/src/components/modelSelection/ModeSelect.tsx index b4cb94545..c1f1552ef 100644 --- a/gui/src/components/modelSelection/ModeSelect.tsx +++ b/gui/src/components/modelSelection/ModeSelect.tsx @@ -8,23 +8,15 @@ import { } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; -import { useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo } from "react"; import styled from "styled-components"; import { lightGray } from ".."; -import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; -import { - cycleMode, - selectCurrentMode, - setMode, -} from "../../redux/slices/sessionSlice"; -import { exitEditMode } from "../../redux/thunks"; -import { - loadLastSession, - saveCurrentSession, -} from "../../redux/thunks/session"; +import { setMode } from "../../redux/slices/sessionSlice"; +import { enterEditMode, exitEditMode } from "../../redux/thunks/editMode"; import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util"; +import { useMainEditor } from "../mainInput/TipTapEditor"; import { Listbox, ListboxButton, @@ -40,12 +32,12 @@ const ShortcutText = styled.span` function ModeSelect() { const dispatch = useAppDispatch(); - const mode = useAppSelector(selectCurrentMode); + const mode = useAppSelector((store) => store.session.mode); const selectedModel = useAppSelector(selectSelectedChatModel); - const currentSession = useAppSelector((state) => state.session); - const [newSessionInitialized, setNewSessionInitialized] = useState(false); - const agentModeSupported = selectedModel && modelSupportsTools(selectedModel); - + const agentModeSupported = useMemo(() => { + return selectedModel && modelSupportsTools(selectedModel); + }, [selectedModel]); + const { mainEditor } = useMainEditor(); const jetbrains = useMemo(() => { return isJetBrains(); }, []); @@ -74,59 +66,79 @@ function ModeSelect() { } }, [mode, agentModeSupported, dispatch, selectedModel]); + const cycleMode = useCallback(async () => { + const modes: MessageModes[] = jetbrains + ? ["chat", "agent"] + : ["chat", "agent", "edit"]; + const currentIndex = modes.indexOf(mode); + const nextMode = modes[(currentIndex + 1) % modes.length]; + + if (mode === "edit") { + await dispatch( + exitEditMode({ + goToMode: nextMode, + }), + ); + } else { + if (nextMode === "edit") { + await dispatch( + enterEditMode({ + returnToMode: mode, + }), + ); + } else { + dispatch(setMode(nextMode)); + } + } + mainEditor?.commands.focus(); + }, [jetbrains, mode, mainEditor]); + + const selectMode = useCallback( + async (newMode: MessageModes) => { + if (newMode === mode) { + return; + } + if (newMode === "edit") { + await dispatch( + enterEditMode({ + returnToMode: mode, + }), + ); + } else { + if (mode === "edit") { + await dispatch( + exitEditMode({ + goToMode: newMode, + }), + ); + } else { + dispatch(setMode(newMode)); + } + } + + mainEditor?.commands.focus(); + }, + [mode, mainEditor], + ); + useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { if (e.key === "." && (e.metaKey || e.ctrlKey)) { e.preventDefault(); - dispatch(cycleMode({ isJetBrains: jetbrains })); + void cycleMode(); } }; document.addEventListener("keydown", handleKeyDown); return () => document.removeEventListener("keydown", handleKeyDown); - }, [dispatch, mode, jetbrains]); - - useWebviewListener("newSession", async () => { - setNewSessionInitialized(true); - }); - - useEffect(() => { - if (currentSession.history.length > 0) { - setNewSessionInitialized(false); - } - }, [currentSession.history]); + }, [cycleMode]); return ( - { - if (newMode === mode) { - return; - } - dispatch(setMode(newMode)); - if (newMode === "edit" || newSessionInitialized) { - // generate a new session for edit mode and if user opened a new session explicitly - await dispatch( - saveCurrentSession({ - generateTitle: false, - openNewSession: true, - }), - ); - } else if (mode === "edit") { - // load last session if the previous mode was edit - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - dispatch(exitEditMode()); - } - }} - > +
    - -
    - - Agent -
    - {mode === "agent" && } - {!agentModeSupported && (Not supported)} -
    - - -
    - - Chat - {getMetaKeyLabel()}L -
    - {mode === "chat" && } -
    - {!jetbrains && (
    @@ -170,6 +164,23 @@ function ModeSelect() { {mode === "edit" && } )} + +
    + + Chat + {getMetaKeyLabel()}L +
    + {mode === "chat" && } +
    + + +
    + + Agent +
    + {mode === "agent" && } + {!agentModeSupported && (Not supported)} +
    {metaKeyLabel}. for next mode diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 88e1e6829..3523a7d9f 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -12,9 +12,6 @@ import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { - selectIsInEditMode, -} from "../../redux/slices/sessionSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { updateSelectedModelByRole } from "../../redux/thunks"; import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; @@ -123,12 +120,12 @@ function ModelOption({ function ModelSelect() { const dispatch = useAppDispatch(); - const isInEditMode = useAppSelector(selectIsInEditMode); + const mode = useAppSelector((store) => store.session.mode); const config = useAppSelector((state) => state.config.config); let selectedModel = null; let allModels = null; - if (isInEditMode) { + if (mode === "edit") { allModels = config.modelsByRole.edit; selectedModel = config.selectedModelByRole.edit; } @@ -158,14 +155,14 @@ function ModelSelect() { useEffect(() => { setOptions( allModels.map((model) => { - return { - value: model.title, - title: modelSelectTitle(model), - apiKey: model.apiKey, - }; - }), + return { + value: model.title, + title: modelSelectTitle(model), + apiKey: model.apiKey, + }; + }), ); - }, [isInEditMode, config]); + }, [config]); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { @@ -225,7 +222,7 @@ function ModelSelect() { dispatch( updateSelectedModelByRole({ selectedProfile, - role: isInEditMode ? "edit" : "chat", + role: mode === "edit" ? "edit" : "chat", modelTitle: val, }), ); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/ParallelListeners.tsx similarity index 83% rename from gui/src/hooks/useSetup.ts rename to gui/src/hooks/ParallelListeners.tsx index 98ba3c5cf..1b609ce39 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/ParallelListeners.tsx @@ -2,6 +2,7 @@ import { useCallback, useContext, useEffect, useRef } from "react"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; +import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { FromCoreProtocol } from "core/protocol"; import { initializeProfilePreferences, @@ -11,10 +12,11 @@ import { } from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; +import { setConfigResult } from "../redux/slices/configSlice"; import { - selectSelectedChatModel, - setConfigResult, -} from "../redux/slices/configSlice"; + setLastNonEditSessionEmpty, + updateEditStateApplyState, +} from "../redux/slices/editModeState"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { acceptToolCall, @@ -31,11 +33,11 @@ import { isJetBrains } from "../util"; import { setLocalStorage } from "../util/localStorage"; import { useWebviewListener } from "./useWebviewListener"; -function useSetup() { +function ParallelListeners() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const history = useAppSelector((store) => store.session.history); - const defaultModel = useAppSelector(selectSelectedChatModel); + const selectedProfileId = useAppSelector( (store) => store.profiles.selectedProfileId, ); @@ -81,10 +83,6 @@ function useSetup() { const initialLoadAuthAndConfig = useCallback( async (initial: boolean) => { - // const authResult = await ideMessenger.request( - // "auth/getState", - // undefined - // ) const result = await ideMessenger.request( "config/getSerializedProfileInfo", undefined, @@ -259,34 +257,47 @@ function useSetup() { useWebviewListener( "updateApplyState", async (state) => { - dispatch(updateApplyState(state)); + if (state.streamId === EDIT_MODE_STREAM_ID) { + dispatch(updateEditStateApplyState(state)); + } else { + // chat or agent + dispatch(updateApplyState(state)); - // Handle apply status updates that are associated with current tool call - if ( - state.status === "closed" && - currentToolCallApplyState && - currentToolCallApplyState.streamId === state.streamId - ) { - // const output: ContextItem = { - // name: "Edit tool output", - // content: "Completed edit", - // description: "", - // }; - dispatch( - acceptToolCall({ - toolCallId: currentToolCallApplyState.toolCallId!, - }), - ); - // dispatch(setToolCallOutput([])); - dispatch( - streamResponseAfterToolCall({ - toolCallId: currentToolCallApplyState.toolCallId!, - }), - ); + // Handle apply status updates that are associated with current tool call + if ( + state.status === "closed" && + currentToolCallApplyState && + currentToolCallApplyState.streamId === state.streamId + ) { + // const output: ContextItem = { + // name: "Edit tool output", + // content: "Completed edit", + // description: "", + // }; + dispatch( + acceptToolCall({ + toolCallId: currentToolCallApplyState.toolCallId!, + }), + ); + // dispatch(setToolCallOutput([])); + dispatch( + streamResponseAfterToolCall({ + toolCallId: currentToolCallApplyState.toolCallId!, + }), + ); + } } }, [currentToolCallApplyState, history], ); + + const mode = useAppSelector((store) => store.session.mode); + useEffect(() => { + if (mode !== "edit") { + dispatch(setLastNonEditSessionEmpty(history.length === 0)); + } + }, [mode, history]); + return <>; } -export default useSetup; +export default ParallelListeners; diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 5f0dc75b4..f56a6b210 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -996,4 +996,24 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ], apiKeyUrl: "https://cloud.siliconflow.cn/account/ak", }, + venice: { + title: "Venice", + provider: "venice", + icon: "venice.png", + description: "Venice.", + tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource], + collectInputFor: [ + { + inputType: "text", + key: "apiKey", + label: "API Key", + placeholder: "Enter your Venice API key", + required: true, + }, + ], + packages: [ + {...models.AUTODETECT} + ], + apiKeyUrl: "https://venice.ai/chat" + } }; diff --git a/gui/src/pages/error.tsx b/gui/src/pages/error.tsx index 92c064019..0738696a6 100644 --- a/gui/src/pages/error.tsx +++ b/gui/src/pages/error.tsx @@ -1,13 +1,13 @@ -import { useDispatch } from "react-redux"; -import { useNavigate, useRouteError } from "react-router-dom"; -import { newSession } from "../redux/slices/sessionSlice"; -import { GithubIcon } from "../components/svg/GithubIcon"; -import { DiscordIcon } from "../components/svg/DiscordIcon"; -import { useContext, useEffect, useState } from "react"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { Button, SecondaryButton } from "../components"; import { ArrowPathIcon, FlagIcon } from "@heroicons/react/24/outline"; import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; +import { useContext, useEffect, useState } from "react"; +import { useDispatch } from "react-redux"; +import { useNavigate, useRouteError } from "react-router-dom"; +import { Button, SecondaryButton } from "../components"; +import { DiscordIcon } from "../components/svg/DiscordIcon"; +import { GithubIcon } from "../components/svg/GithubIcon"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { newSession } from "../redux/slices/sessionSlice"; const ErrorPage: React.FC = () => { const error: any = useRouteError(); @@ -61,16 +61,16 @@ const ErrorPage: React.FC = () => { Report the issue on GitHub or Discord:

    -
    +
    openUrl(GITHUB_LINK)} - className="flex w-full items-center justify-center space-x-2 rounded-lg px-4 py-2 text-base text-white" + className="flex items-center justify-center space-x-2 rounded-lg px-4 py-2 text-base text-white" > GitHub openUrl(DISCORD_LINK)} - className="flex w-full items-center justify-center rounded-lg text-base" + className="flex items-center justify-center rounded-lg text-base" > Discord diff --git a/gui/src/pages/gui/Chat.test.tsx b/gui/src/pages/gui/Chat.test.tsx index 5339f831b..90b90f943 100644 --- a/gui/src/pages/gui/Chat.test.tsx +++ b/gui/src/pages/gui/Chat.test.tsx @@ -1,6 +1,6 @@ -import { renderWithProviders } from "../../util/test/render"; import { screen, waitFor } from "@testing-library/dom"; -import { act, fireEvent } from "@testing-library/react"; +import { act } from "@testing-library/react"; +import { renderWithProviders } from "../../util/test/render"; import { Chat } from "./Chat"; describe("Chat page test", () => { @@ -23,8 +23,8 @@ describe("Chat page test", () => { ); }); - // Check that it switched to Edit mode - expect(await screen.findByText("Edit")).toBeInTheDocument(); + // Check that it switched to Agent mode + expect(await screen.findByText("Agent")).toBeInTheDocument(); act(() => { document.dispatchEvent( @@ -35,8 +35,8 @@ describe("Chat page test", () => { ); }); - // Check that it switched to Agent mode - expect(await screen.findByText("Agent")).toBeInTheDocument(); + // Check that it switched to Edit mode + expect(await screen.findByText("Edit")).toBeInTheDocument(); }); it.skip("should send a message and receive a response", async () => { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 4350ff56d..3c3abaf47 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -5,16 +5,22 @@ import { ExclamationTriangleIcon, } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/react"; -import { InputModifiers, RangeInFileWithContents } from "core"; +import { InputModifiers } from "core"; import { streamResponse } from "core/llm/stream"; -import { renderChatMessage, stripImages } from "core/util/messageContent"; +import { renderChatMessage } from "core/util/messageContent"; import { usePostHog } from "posthog-js/react"; -import { useCallback, useContext, useEffect, useRef, useState } from "react"; +import { + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; import { ErrorBoundary } from "react-error-boundary"; import styled from "styled-components"; import { Button, lightGray, vscBackground } from "../../components"; import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons"; -import CodeToEditCard from "../../components/CodeToEditCard"; import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; import { useFindWidget } from "../../components/find/FindWidget"; @@ -22,24 +28,18 @@ import TimelineItem from "../../components/gui/TimelineItem"; import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton"; import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; -import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { useOnboardingCard } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; import { TabBar } from "../../components/TabBar/TabBar"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectUseHub } from "../../redux/selectors"; import { selectCurrentToolCall, selectCurrentToolCallApplyState, } from "../../redux/selectors/selectCurrentToolCall"; -import { selectSelectedChatModel } from "../../redux/slices/configSlice"; -import { submitEdit } from "../../redux/slices/editModeState"; import { newSession, - selectIsInEditMode, - selectIsSingleRangeEditOrInsertion, updateToolCallOutput, } from "../../redux/slices/sessionSlice"; import { @@ -48,7 +48,7 @@ import { setShowDialog, } from "../../redux/slices/uiSlice"; import { cancelStream } from "../../redux/thunks/cancelStream"; -import { exitEditMode } from "../../redux/thunks/exitEditMode"; +import { streamEditThunk } from "../../redux/thunks/editMode"; import { loadLastSession } from "../../redux/thunks/session"; import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; @@ -56,7 +56,9 @@ import { FREE_TRIAL_LIMIT_REQUESTS, incrementFreeTrialCount, } from "../../util/freeTrial"; -import getMultifileEditPrompt from "../../util/getMultifileEditPrompt"; + +import CodeToEditCard from "../../components/mainInput/CodeToEditCard"; +import EditModeDetails from "../../components/mainInput/EditModeDetails"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; @@ -106,7 +108,9 @@ export function Chat() { const showSessionTabs = useAppSelector( (store) => store.config.config.ui?.showSessionTabs, ); - const selectedChatModel = useAppSelector(selectSelectedChatModel); + const selectedModels = useAppSelector( + (store) => store.config?.config.selectedModelByRole, + ); const isStreaming = useAppSelector((state) => state.session.isStreaming); const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); const mainTextInputRef = useRef(null); @@ -115,25 +119,20 @@ export function Chat() { const showChatScrollbar = useAppSelector( (state) => state.config.config.ui?.showChatScrollbar, ); - const codeToEdit = useAppSelector((state) => state.session.codeToEdit); + const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit); const toolCallState = useAppSelector(selectCurrentToolCall); + const mode = useAppSelector((store) => store.session.mode); 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 lastSessionId = useAppSelector((state) => state.session.lastSessionId); - const useHub = useAppSelector(selectUseHub); const hasDismissedExploreDialog = useAppSelector( (state) => state.ui.hasDismissedExploreDialog, ); - const jetbrains = isJetBrains(); + const jetbrains = useMemo(() => { + return isJetBrains(); + }, []); useEffect(() => { // Cmd + Backspace to delete current step @@ -151,7 +150,7 @@ export function Chat() { return () => { window.removeEventListener("keydown", listener); }; - }, [isStreaming]); + }, [isStreaming, jetbrains]); const { widget, highlights } = useFindWidget(stepsDivRef); @@ -179,7 +178,20 @@ export function Chat() { "Cannot submit message while awaiting tool call apply", ); } - if (selectedChatModel?.provider === "free-trial") { + + const model = + mode === "edit" + ? (selectedModels?.edit ?? selectedModels?.chat) + : selectedModels?.chat; + if (!model) { + return; + } + + if (mode === "edit" && codeToEdit.length === 0) { + return; + } + + if (model.provider === "free-trial") { const newCount = incrementFreeTrialCount(); if (newCount === FREE_TRIAL_LIMIT_REQUESTS) { @@ -206,21 +218,19 @@ export function Chat() { } } - if (isSingleRangeEditOrInsertion) { - handleSingleRangeEditOrInsertion(editorState); - return; - } + if (mode === "edit") { + dispatch( + streamEditThunk({ + editorState, + codeToEdit, + }), + ); + } else { + dispatch(streamResponseThunk({ editorState, modifiers, index })); - const promptPreamble = isInEditMode - ? getMultifileEditPrompt(codeToEdit) - : undefined; - - dispatch( - streamResponseThunk({ editorState, modifiers, promptPreamble, index }), - ); - - if (editorToClearOnSend) { - editorToClearOnSend.commands.clearContent(); + if (editorToClearOnSend) { + editorToClearOnSend.commands.clearContent(); + } } // Increment localstorage counter for popup @@ -236,47 +246,9 @@ export function Chat() { setLocalStorage("mainTextEntryCounter", 1); } }, - [ - history, - selectedChatModel, - streamResponse, - isSingleRangeEditOrInsertion, - codeToEdit, - toolCallState, - ], + [history, selectedModels, streamResponse, mode, codeToEdit, toolCallState], ); - async function handleSingleRangeEditOrInsertion(editorState: JSONContent) { - if (!selectedChatModel) { - console.error("No selected chat model"); - return; - } - - const [contextItems, __, userInstructions, _] = await resolveEditorContent({ - editorState, - modifiers: { - noContext: true, - useCodebase: false, - }, - ideMessenger, - defaultContextProviders: [], - availableSlashCommands: [], - 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 () => { @@ -314,8 +286,6 @@ export function Chat() { useAutoScroll(stepsDivRef, history); - const showPageHeader = isInEditMode || useHub; - return ( <> {widget} @@ -324,7 +294,7 @@ export function Chat() { 0 ? "flex-1" : ""}`} + className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`} > {highlights} {history.map((item, index: number) => ( @@ -342,9 +312,7 @@ export function Chat() { > {item.message.role === "user" ? ( <> - {isInEditMode && index === 0 && } sendInput(editorState, modifiers, index) } @@ -421,19 +389,24 @@ export function Chat() { ))}
    - {isInEditMode && history.length === 0 && } - - {isInEditMode && history.length > 0 ? null : ( + <> + {!isStreaming && mode !== "edit" && ( + {}} + /> + )} + {mode === "edit" && } sendInput(editorState, modifiers, undefined, editor) } inputId={MAIN_EDITOR_INPUT_ID} /> - )} + +
    - {history.length === 0 && lastSessionId && !isInEditMode && ( + {history.length === 0 && lastSessionId && mode !== "edit" && (
    { @@ -461,30 +434,9 @@ export function Chat() { )}
    - - {hasPendingApplies && isSingleRangeEditOrInsertion && ( - { - if (outcome === "acceptDiff") { - await dispatch( - loadLastSession({ - saveCurrentSession: false, - }), - ); - dispatch(exitEditMode()); - } - }} - /> - )} - {!hasDismissedExploreDialog && } - {history.length === 0 && ( - + )}
    diff --git a/gui/src/pages/gui/EmptyChatBody.tsx b/gui/src/pages/gui/EmptyChatBody.tsx index dce70cdd5..ac8ba7631 100644 --- a/gui/src/pages/gui/EmptyChatBody.tsx +++ b/gui/src/pages/gui/EmptyChatBody.tsx @@ -4,18 +4,15 @@ import { OnboardingCard } from "../../components/OnboardingCard"; import { PlatformOnboardingCard } from "../../components/OnboardingCard/platform/PlatformOnboardingCard"; export interface EmptyChatBodyProps { - useHub: boolean; showOnboardingCard?: boolean; } -export function EmptyChatBody({ - useHub, - showOnboardingCard, -}: EmptyChatBodyProps) { +export function EmptyChatBody({ showOnboardingCard }: EmptyChatBodyProps) { if (showOnboardingCard) { return (
    - {useHub ? ( + {true ? ( + // For now we are excluding local onboarding options other than ollama ) : ( diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index d098d2bc4..c6fcc703f 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -11,7 +11,6 @@ import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { selectSelectedProfile } from "../../redux/"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectUseHub } from "../../redux/selectors"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { isLocalProfile } from "../../util"; @@ -26,7 +25,7 @@ function parseErrorMessage(fullErrMsg: string): string { const msg = fullErrMsg.split("\n\n").slice(1).join("\n\n"); try { const parsed = JSON.parse(msg); - return parsed.error ?? parsed.message ?? msg; + return JSON.stringify(parsed.error ?? parsed.message ?? msg); } catch (e) { return msg; } @@ -36,7 +35,6 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); const selectedModel = useAppSelector(selectSelectedChatModel); - const hubEnabled = useAppSelector(selectUseHub); const selectedProfile = useAppSelector(selectSelectedProfile); const { session, refreshProfiles } = useAuth(); @@ -180,17 +178,14 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { if (statusCode === 401) { errorContent = (
    - {hubEnabled && - session && - selectedProfile && - !isLocalProfile(selectedProfile) && ( -
    - {`If your hub secret values may have changed, refresh your assistants`} - - Refresh assistant secrets - -
    - )} + {session && selectedProfile && !isLocalProfile(selectedProfile) && ( +
    + {`If your hub secret values may have changed, refresh your assistants`} + + Refresh assistant secrets + +
    + )} {`It's possible that your API key is invalid.`}
    {checkKeysButton} diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 35b9d1a5f..0c27ecee8 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,7 +1,6 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { useEffect } from "react"; import { v4 as uuidv4 } from "uuid"; -import AcceptRejectAllButtons from "../../../components/AcceptRejectAllButtons"; import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { @@ -41,29 +40,13 @@ export function EditFile(props: EditToolCallProps) { } return ( - <> - - {/* TODO better indicator of generation at bottom */} - {/* {isStreaming && applyState?.status === "streaming" && ( -
    - Generating... -
    - )} */} - {!isStreaming && applyState?.status === "done" && ( -
    - {}} - /> -
    - )} - + ); } diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index bbfea5364..aa24f87b3 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -46,6 +46,3 @@ export const selectUseActiveFile = createSelector( [(state: RootState) => state.config.config.experimental?.defaultContext], (defaultContext) => defaultContext?.includes("activeFile" as any), ); - -export const selectUseHub = (state: RootState) => - state.config.config.usePlatform; diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index b0283a0ab..52a05a97e 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -1,82 +1,76 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { EditStatus, MessageContent } from "core"; - +import { ApplyState, CodeToEdit, MessageModes } from "core"; +import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; export interface EditModeState { - editStatus: EditStatus; - previousInputs: MessageContent[]; - fileAfterEdit?: string; + // Array because of previous multi-file edit functionality + // Keeping array to not break persisted redux for now + codeToEdit: CodeToEdit[]; + applyState: ApplyState; + returnToMode: MessageModes; + lastNonEditSessionWasEmpty: boolean; } +export const INITIAL_EDIT_APPLY_STATE: ApplyState = { + streamId: EDIT_MODE_STREAM_ID, + status: "not-started", +}; + const initialState: EditModeState = { - editStatus: "not-started", - previousInputs: [], + applyState: INITIAL_EDIT_APPLY_STATE, + codeToEdit: [], + returnToMode: "chat", + lastNonEditSessionWasEmpty: false, }; export const editModeStateSlice = createSlice({ name: "editModeState", initialState, reducers: { - focusEdit: (state) => { - state.editStatus = "not-started"; - state.previousInputs = []; - state.fileAfterEdit = undefined; + setReturnToModeAfterEdit: ( + state, + { payload }: PayloadAction, + ) => { + state.returnToMode = payload; }, - submitEdit: (state, { payload }: PayloadAction) => { - state.previousInputs.push(payload); - state.editStatus = "streaming"; + updateEditStateApplyState: ( + state, + { payload }: PayloadAction, + ) => { + state.applyState = { + ...state.applyState, + ...payload, + }; }, - setEditStatus: ( + setCodeToEdit: ( state, { payload, - }: PayloadAction<{ status: EditStatus; fileAfterEdit?: string }>, + }: PayloadAction<{ + codeToEdit: CodeToEdit | CodeToEdit[]; + }>, ) => { - // Only allow valid transitions - const currentStatus = state.editStatus; - if (currentStatus === "not-started" && payload.status === "streaming") { - state.editStatus = payload.status; - } else if ( - currentStatus === "streaming" && - payload.status === "accepting" - ) { - state.editStatus = payload.status; - state.fileAfterEdit = payload.fileAfterEdit; - } else if (currentStatus === "accepting" && payload.status === "done") { - state.editStatus = payload.status; - } else if ( - currentStatus === "accepting:full-diff" && - payload.status === "done" - ) { - state.editStatus = payload.status; - } else if ( - currentStatus === "accepting" && - payload.status === "accepting:full-diff" - ) { - state.editStatus = payload.status; - } else if ( - currentStatus === "accepting:full-diff" && - payload.status === "accepting" - ) { - state.editStatus = payload.status; - } else if (currentStatus === "done" && payload.status === "not-started") { - state.editStatus = payload.status; - } + state.codeToEdit = Array.isArray(payload.codeToEdit) + ? payload.codeToEdit + : [payload.codeToEdit]; }, - addPreviousInput: (state, { payload }: PayloadAction) => { - state.previousInputs.push(payload); + clearCodeToEdit: (state) => { + state.codeToEdit = []; }, - setEditDone: (state) => { - state.editStatus = "done"; - state.previousInputs = []; + setLastNonEditSessionEmpty: ( + state, + { payload }: PayloadAction, + ) => { + state.lastNonEditSessionWasEmpty = payload; }, }, + selectors: {}, }); export const { - setEditStatus, - addPreviousInput, - setEditDone, - submitEdit, - focusEdit, + setReturnToModeAfterEdit, + clearCodeToEdit, + setCodeToEdit, + updateEditStateApplyState, + setLastNonEditSessionEmpty, } = editModeStateSlice.actions; export default editModeStateSlice.reducer; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 5f74e0c50..e81545d8b 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -10,7 +10,6 @@ import { ApplyState, ChatHistoryItem, ChatMessage, - CodeToEdit, ContextItem, ContextItemWithId, FileSymbolMap, @@ -44,8 +43,6 @@ type SessionState = { title: string; id: string; streamAborter: AbortController; - codeToEdit: CodeToEdit[]; - curCheckpointIndex: number; mainEditorContentTrigger?: JSONContent | undefined; symbols: FileSymbolMap; mode: MessageModes; @@ -56,34 +53,13 @@ type SessionState = { newestToolbarPreviewForInput: Record; }; -function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { - if (a.filepath !== b.filepath || a.contents !== b.contents) { - return false; - } - - if ("range" in a && "range" in b) { - const rangeA = a.range; - const rangeB = b.range; - - return ( - rangeA.start.line === rangeB.start.line && - rangeA.end.line === rangeB.end.line - ); - } - - // If neither has a range, they are considered equal in this context - return !("range" in a) && !("range" in b); -} - const initialState: SessionState = { allSessionMetadata: [], history: [], isStreaming: false, title: NEW_SESSION_TITLE, id: uuidv4(), - curCheckpointIndex: 0, streamAborter: new AbortController(), - codeToEdit: [], symbols: {}, mode: "chat", codeBlockApplyStates: { @@ -200,8 +176,6 @@ export const sessionSlice = createSlice({ }, contextItems: [], }); - - state.curCheckpointIndex = Math.floor(index / 2); } else { // New input/response messages state.history = state.history.concat([ @@ -223,8 +197,6 @@ export const sessionSlice = createSlice({ contextItems: [], }, ]); - - state.curCheckpointIndex = Math.floor((state.history.length - 1) / 2); // TODO this feels really fragile } state.isStreaming = true; @@ -454,12 +426,10 @@ export const sessionSlice = createSlice({ state.history = payload.history as any; state.title = payload.title; state.id = payload.sessionId; - state.curCheckpointIndex = 0; } else { state.history = []; state.title = NEW_SESSION_TITLE; state.id = uuidv4(); - state.curCheckpointIndex = 0; } }, updateSessionTitle: (state, { payload }: PayloadAction) => { @@ -551,19 +521,6 @@ export const sessionSlice = createSlice({ state.history[state.history.length - 1].contextItems = contextItems; }, - - updateCurCheckpoint: ( - state, - { payload }: PayloadAction<{ filepath: string; content: string }>, - ) => { - const checkpoint = state.history[state.curCheckpointIndex].checkpoint; - if (checkpoint) { - checkpoint[payload.filepath] = payload.content; - } - }, - setCurCheckpointIndex: (state, { payload }: PayloadAction) => { - state.curCheckpointIndex = payload; - }, updateApplyState: (state, { payload }: PayloadAction) => { const applyState = state.codeBlockApplyStates.states.find( (state) => state.streamId === payload.streamId, @@ -584,31 +541,7 @@ export const sessionSlice = createSlice({ resetNextCodeBlockToApplyIndex: (state) => { state.codeBlockApplyStates.curIndex = 0; }, - addCodeToEdit: ( - state, - { payload }: PayloadAction, - ) => { - const entries = Array.isArray(payload) ? payload : [payload]; - const newEntries = entries.filter( - (entry) => - !state.codeToEdit.some((existingEntry) => - isCodeToEditEqual(existingEntry, entry), - ), - ); - - if (newEntries.length > 0) { - state.codeToEdit.push(...newEntries); - } - }, - removeCodeToEdit: (state, { payload }: PayloadAction) => { - state.codeToEdit = state.codeToEdit.filter( - (entry) => !isCodeToEditEqual(entry, payload), - ); - }, - clearCodeToEdit: (state) => { - state.codeToEdit = []; - }, // TOOL CALL STATE setToolGenerated: ( state, @@ -698,14 +631,6 @@ export const sessionSlice = createSlice({ setMode: (state, action: PayloadAction) => { state.mode = action.payload; }, - cycleMode: (state, action: PayloadAction<{ isJetBrains: boolean }>) => { - const modes = action.payload.isJetBrains - ? ["chat", "agent"] - : ["chat", "edit", "agent"]; - const currentIndex = modes.indexOf(state.mode); - const nextIndex = (currentIndex + 1) % modes.length; - state.mode = modes[nextIndex] as MessageModes; - }, setNewestToolbarPreviewForInput: ( state, { @@ -724,26 +649,6 @@ export const sessionSlice = createSlice({ const curHistoryItem = state.history.at(-1); return curHistoryItem?.isGatheringContext || false; }, - selectIsInEditMode: (state) => { - return state.mode === "edit"; - }, - selectCurrentMode: (state) => { - return state.mode; - }, - selectIsSingleRangeEditOrInsertion: (state) => { - if (state.mode !== "edit") { - return false; - } - - const isInsertion = state.codeToEdit.length === 0; - const selectIsSingleRangeEdit = - state.codeToEdit.length === 1 && "range" in state.codeToEdit[0]; - - return selectIsSingleRangeEdit || isInsertion; - }, - selectHasCodeToEdit: (state) => { - return state.codeToEdit.length > 0; - }, }, extraReducers: (builder) => { addPassthroughCases(builder, [streamResponseThunk]); @@ -806,14 +711,9 @@ export const { setMainEditorContentTrigger, deleteMessage, setIsGatheringContext, - updateCurCheckpoint, - setCurCheckpointIndex, resetNextCodeBlockToApplyIndex, updateApplyState, abortStream, - clearCodeToEdit, - addCodeToEdit, - removeCodeToEdit, setToolCallCalling, cancelToolCall, errorToolCall, @@ -826,15 +726,8 @@ export const { updateSessionMetadata, deleteSessionMetadata, setNewestToolbarPreviewForInput, - cycleMode, } = sessionSlice.actions; -export const { - selectIsGatheringContext, - selectIsInEditMode, - selectCurrentMode, - selectIsSingleRangeEditOrInsertion, - selectHasCodeToEdit, -} = sessionSlice.selectors; +export const { selectIsGatheringContext } = sessionSlice.selectors; export default sessionSlice.reducer; diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index aa7c2bb5c..983f7bb6c 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -47,15 +47,16 @@ const saveSubsetFilters = [ // Persist edit mode in case closes in middle "mode", - "codeToEdit", // higher risk to persist // codeBlockApplyStates // symbols - // curCheckpointIndex ]), - // Don't persist any of the edit state for now - createFilter("editModeState", []), + createFilter("editModeState", [ + "returnToMode", + "lastNonEditSessionWasEmpty", + "codeToEdit", + ]), createFilter("config", ["defaultModelTitle"]), createFilter("ui", ["toolSettings", "toolGroupSettings"]), createFilter("indexing", []), diff --git a/gui/src/redux/thunks/editMode.ts b/gui/src/redux/thunks/editMode.ts new file mode 100644 index 000000000..4341b14a4 --- /dev/null +++ b/gui/src/redux/thunks/editMode.ts @@ -0,0 +1,126 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { JSONContent } from "@tiptap/core"; +import { CodeToEdit, MessageModes, RangeInFileWithContents } from "core"; +import { stripImages } from "core/util/messageContent"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor"; +import { + clearCodeToEdit, + INITIAL_EDIT_APPLY_STATE, + setReturnToModeAfterEdit, + updateEditStateApplyState, +} from "../slices/editModeState"; +import { newSession, setActive, setMode } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; +import { loadLastSession, saveCurrentSession } from "./session"; +import { streamThunkWrapper } from "./streamThunkWrapper"; + +export const streamEditThunk = createAsyncThunk< + void, + { + editorState: JSONContent; + codeToEdit: CodeToEdit[]; + }, + ThunkApiType +>( + "chat/streamResponse", + async ({ editorState, codeToEdit }, { dispatch, extra, getState }) => { + await dispatch( + streamThunkWrapper(async () => { + dispatch(setActive()); + const [contextItems, __, userInstructions, _] = + await resolveEditorContent({ + editorState, + modifiers: { + noContext: true, + useCodebase: false, + }, + ideMessenger: extra.ideMessenger, + defaultContextProviders: [], + availableSlashCommands: [], + dispatch, + }); + + const prompt = [ + ...contextItems.map((item) => item.content), + stripImages(userInstructions), + ].join("\n\n"); + + const response = await extra.ideMessenger.request("edit/sendPrompt", { + prompt, + range: codeToEdit[0] as RangeInFileWithContents, + }); + + if (response.status === "error") { + throw new Error(response.error); + } + }), + ); + }, +); + +export const exitEditMode = createAsyncThunk< + void, + { goToMode?: MessageModes; openNewSession?: boolean }, + ThunkApiType +>( + "edit/exitMode", + async ({ goToMode, openNewSession }, { dispatch, extra, getState }) => { + const state = getState(); + const codeToEdit = state.editModeState.codeToEdit; + + if (state.session.mode !== "edit") { + return; + } + + if (codeToEdit[0] && state.editModeState.applyState.numDiffs) { + extra.ideMessenger.post("rejectDiff", { + filepath: codeToEdit[0].filepath, + }); + } + + extra.ideMessenger.post("edit/clearDecorations", undefined); + + dispatch(clearCodeToEdit()); + dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE)); + + if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) { + dispatch(newSession()); + } else { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + } + + dispatch(setMode(goToMode ?? state.editModeState.returnToMode)); + }, +); + +export const enterEditMode = createAsyncThunk< + void, + { returnToMode?: MessageModes }, + ThunkApiType +>("edit/enterMode", async ({ returnToMode }, { dispatch, extra, getState }) => { + const state = getState(); + + if (state.session.mode === "edit") { + return; + } + + dispatch(setReturnToModeAfterEdit(returnToMode ?? state.session.mode)); + + await dispatch( + saveCurrentSession({ + openNewSession: true, + // Because this causes a lag before Edit mode is focused. TODO just have that happen in background + generateTitle: false, + }), + ); + dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE)); + dispatch(setMode("edit")); + + if (!state.editModeState.codeToEdit[0]) { + extra.ideMessenger.post("edit/addCurrentSelection", undefined); + } +}); diff --git a/gui/src/redux/thunks/exitEditMode.ts b/gui/src/redux/thunks/exitEditMode.ts deleted file mode 100644 index 438783499..000000000 --- a/gui/src/redux/thunks/exitEditMode.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import { - clearCodeToEdit, - selectIsInEditMode, - selectIsSingleRangeEditOrInsertion, - setMainEditorContentTrigger, - setMode, -} from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; -import { setEditDone } from "../slices/editModeState"; - -export const exitEditMode = createAsyncThunk( - "edit/complete", - async (_, { dispatch, extra, getState }) => { - const state = getState(); - const isInEditMode = selectIsInEditMode(state); - const codeToEdit = state.session.codeToEdit; - const isSingleRangeEditOrInsertion = - selectIsSingleRangeEditOrInsertion(state); - - if (!isInEditMode) { - return; - } - - dispatch(setMode("chat")); - - for (const code of codeToEdit) { - extra.ideMessenger.post("rejectDiff", { - filepath: code.filepath, - }); - } - - dispatch(clearCodeToEdit()); - dispatch(setEditDone()); - dispatch(setMainEditorContentTrigger(undefined)); - - extra.ideMessenger.post("edit/exit", { - shouldFocusEditor: isSingleRangeEditOrInsertion, - }); - }, -); diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts index ad987fafa..7fe098e70 100644 --- a/gui/src/redux/thunks/index.ts +++ b/gui/src/redux/thunks/index.ts @@ -1,4 +1,3 @@ -export { exitEditMode } from "./exitEditMode"; export { gatherContext } from "./gatherContext"; export { resetStateForNewMessage } from "./resetStateForNewMessage"; export { streamNormalInput } from "./streamNormalInput"; diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index dd00b86fb..6c406f868 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -4,6 +4,7 @@ import { InputModifiers } from "core"; import { constructMessages } from "core/llm/constructMessages"; import posthog from "posthog-js"; import { v4 as uuidv4 } from "uuid"; +import { getBaseSystemMessage } from "../../util"; import { selectSelectedChatModel } from "../slices/configSlice"; import { submitEditorAndInitAtIndex, @@ -85,9 +86,13 @@ export const streamResponseThunk = createAsyncThunk< // Construct messages from updated history const updatedHistory = getState().session.history; + const messageMode = getState().session.mode + + const baseChatOrAgentSystemMessage = getBaseSystemMessage(selectedChatModel, messageMode) + const messages = constructMessages( [...updatedHistory], - selectedChatModel?.baseChatSystemMessage, + baseChatOrAgentSystemMessage, state.config.config.rules, ); diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 7ff0ee47e..2b4ada0c1 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -2,6 +2,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; +import { getBaseSystemMessage } from "../../util"; import { selectSelectedChatModel } from "../slices/configSlice"; import { addContextItemsAtIndex, @@ -64,10 +65,15 @@ export const streamResponseAfterToolCall = createAsyncThunk< dispatch(setActive()); + const updatedHistory = getState().session.history; + const messageMode = getState().session.mode + + const baseChatOrAgentSystemMessage = getBaseSystemMessage(selectedChatModel, messageMode) + const messages = constructMessages( [...updatedHistory], - selectedChatModel?.baseChatSystemMessage, + baseChatOrAgentSystemMessage, state.config.config.rules, ); diff --git a/gui/src/util/getMultifileEditPrompt.ts b/gui/src/util/getMultifileEditPrompt.ts deleted file mode 100644 index 13ee8ac78..000000000 --- a/gui/src/util/getMultifileEditPrompt.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { CodeToEdit, IDE } from "core"; -import { findUriInDirs } from "core/util/uri"; - -export default function getMultifileEditPrompt( - codeToEdit: CodeToEdit[], - dirs?: string[], -): string { - const codeToEditStr = codeToEdit - .map((code) => { - const { relativePathOrBasename } = findUriInDirs( - code.filepath, - dirs ?? window.workspacePaths ?? [], - ); - return ` -\`\`\` ${relativePathOrBasename} -${code.contents} -\`\`\` - `; - }) - .join("\n"); - - return ` -You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: - -1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!" -2. When providing instructions, if a user needs to interact with a CLI, walk them through each step -2. Perform file edits in a logical, sequential ordering -3. For each file edit, provide a brief explanation of the changes -4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. - a. When creating new files, also inlcude the filname in the language specifier of the code block. -6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits - -Remember to be concise and focus on the code changes and their impact. - -Here's an example of how your response should be structured: - - -I'll make the following changes to implement feature X: - -1. First, I'll modify file1.js to add a new function: -\`\`\`javascript /path/to/file1.js -// Entire content of file1.js or changes to be made -\`\`\` - -2. Next, let's create a new test file: -\`\`\`javascript /path/to/file1.test.js -# Entire content of file2.py or changes to be made -\`\`\` - -Summary: -- [Sequential overview of the most important 3-5 edits] - - -Here are the files to base your edits on: - - -${codeToEditStr} - - -Please provide the multi-file edit details based on the engineer's request below: - `; -} diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index f2b18105b..511dd1a64 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -1,3 +1,4 @@ +import { MessageModes, ModelDescription } from "core"; import { ProfileDescription } from "core/config/ProfileLifecycleManager"; import _ from "lodash"; import { KeyboardEvent } from "react"; @@ -114,3 +115,16 @@ export function updatedObj(old: any, pathToValue: { [key: string]: any }) { export function isLocalProfile(profile: ProfileDescription): boolean { return profile.profileType === "local"; } + +/** + * Get the base system message for the agent or chat mode from the model description. + */ +export function getBaseSystemMessage(modelDetails: ModelDescription | null, mode: MessageModes) { + let baseChatOrAgentSystemMessage: string|undefined + if(mode === 'agent') { + baseChatOrAgentSystemMessage = modelDetails?.baseAgentSystemMessage ?? modelDetails?.baseChatSystemMessage // fallback to chat system message if agent system message is unavailable + } else { + baseChatOrAgentSystemMessage = modelDetails?.baseChatSystemMessage + } + return baseChatOrAgentSystemMessage +} \ No newline at end of file diff --git a/gui/src/util/test/render.tsx b/gui/src/util/test/render.tsx index 2b9ae5b29..21a7d7e67 100644 --- a/gui/src/util/test/render.tsx +++ b/gui/src/util/test/render.tsx @@ -1,17 +1,16 @@ import type { RenderOptions, RenderResult } from "@testing-library/react"; -import { render } from "@testing-library/react"; +import { act, render } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { PropsWithChildren } from "react"; import { Provider } from "react-redux"; import { MemoryRouter, RouterProps } from "react-router-dom"; +import { LumpProvider } from "../../components/mainInput/Lump/LumpContext"; +import { MainEditorProvider } from "../../components/mainInput/TipTapEditor"; import { AuthProvider } from "../../context/Auth"; import { IdeMessengerProvider } from "../../context/IdeMessenger"; import { MockIdeMessenger } from "../../context/MockIdeMessenger"; +import ParallelListeners from "../../hooks/ParallelListeners"; import { setupStore } from "../../redux/store"; -import { SetupListeners } from "../../App"; -import { act } from "@testing-library/react"; -import { LumpProvider } from "../../components/mainInput/Lump/LumpContext"; -import { MainEditorProvider } from "../../components/mainInput/TipTapEditor"; // As a basic setup, import your same slice reducers // This type interface extends the default options for render from RTL, as well @@ -55,7 +54,7 @@ export async function renderWithProviders( {children} - + diff --git a/packages/config-yaml/src/converter.ts b/packages/config-yaml/src/converter.ts index 84786c880..40e1f226a 100644 --- a/packages/config-yaml/src/converter.ts +++ b/packages/config-yaml/src/converter.ts @@ -46,11 +46,69 @@ function convertReranker(m: NonNullable): ModelYaml { }; } +function withFromContextProvider( + contextProvider: NonNullable[number], +): Record | undefined { + const { name, params } = contextProvider; + + switch (name) { + case "greptile": + return { + GITHUB_TOKEN: params?.GithubToken ?? "", + GREPTILE_TOKEN: params?.GreptileToken ?? "", + }; + case "jira": + return { + JIRA_TOKEN: params?.JiraToken ?? "", + JIRA_API_VERSION: params?.JiraEmail, + JIRA_DOMAIN: params?.JiraDomain ?? "", + }; + case "postgres": + return { + POSTGRES_HOST: params?.host, + POSTGRES_PORT: params?.port, + POSTGRES_USER: params?.user, + POSTGRES_PASSWORD: params?.password, + POSTGRES_DATABASE: params?.database, + POSTGRES_SCHEMA: params?.schema, + }; + case "gitlab-mr": + return { + GITLAB_TOKEN: params?.token, + DOMAIN: params?.domain, + }; + case "discord": + return { + DISCORD_KEY: params?.discordKey, + DISCORD_GUILD_ID: params?.guildId, + DISCORD_CHANNELS: params?.channels, + }; + case "commits": + return { + DEPTH: params?.Depth, + LAST_N_COMMITS_DEPTH: params?.LastXCommitsDepth, + }; + default: + return undefined; + } +} + function convertContext(configJson: ConfigJson): ContextYaml[] { const context: ContextYaml[] = configJson.contextProviders?.map((ctx) => { + // ctx providers that weren't given official blocks + if ( + ["web", "debugger", "issue", "database", "google", "http"].includes( + ctx.name, + ) + ) { + return { + provider: ctx.name, + params: ctx.params, + }; + } return { - uses: `builtin/${ctx.name}`, + uses: `continuedev/${ctx.name === "open" ? "open-files" : ctx.name}-context`, with: ctx.params, }; }) ?? []; diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 1d2d075f4..abc0c50c4 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -55,7 +55,7 @@ export type CompletionOptions = z.infer; export const cacheBehaviorSchema = z.object({ cacheSystemMessage: z.boolean().optional(), cacheConversation: z.boolean().optional(), -}) +}); export type CacheBehavior = z.infer; export const embedOptionsSchema = z.object({ @@ -66,6 +66,7 @@ export type EmbedOptions = z.infer; export const chatOptionsSchema = z.object({ baseSystemMessage: z.string().optional(), + baseAgentSystemMessage: z.string().optional() }); export type ChatOptions = z.infer; @@ -92,9 +93,9 @@ const templateSchema = z.enum([ /** Prompt templates use Handlebars syntax */ const promptTemplatesSchema = z.object({ apply: z.string().optional(), - chatTemplate: templateSchema.optional(), + chat: templateSchema.optional(), edit: z.string().optional(), - autocomplete: z.string().optional() + autocomplete: z.string().optional(), }); export type PromptTemplates = z.infer; diff --git a/packages/fetch/package-lock.json b/packages/fetch/package-lock.json index 9c923a4ad..bb318db1f 100644 --- a/packages/fetch/package-lock.json +++ b/packages/fetch/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/fetch", - "version": "1.0.4", + "version": "1.0.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/fetch", - "version": "1.0.4", + "version": "1.0.6", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", diff --git a/packages/fetch/package.json b/packages/fetch/package.json index e0a924706..9531fb128 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.5", + "version": "1.0.6", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index d4e8145d0..4f9c60b10 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -10,7 +10,7 @@ import fetch, { RequestInit, Response } from "node-fetch"; const { http, https } = (followRedirects as any).default; -export function fetchwithRequestOptions( +export async function fetchwithRequestOptions( url_: URL | string, init?: RequestInit, requestOptions?: RequestOptions, @@ -107,12 +107,19 @@ export function fetchwithRequestOptions( } // fetch the request with the provided options - const resp = fetch(url, { + const resp = await fetch(url, { ...init, body: updatedBody ?? init?.body, headers: headers, agent: agent, }); + if (!resp.ok) { + const requestId = resp.headers.get("x-request-id"); + if (requestId) { + console.log(`Request ID: ${requestId}, Status: ${resp.status}`); + } + } + return resp; }