diff --git a/core/core.ts b/core/core.ts index 03e81971c..0093db568 100644 --- a/core/core.ts +++ b/core/core.ts @@ -261,9 +261,7 @@ export class Core { stack: err.stack, }); - // Again, specifically for jetbrains to prevent duplicate error messages - // The same logic can currently be found in the webview protocol - // bc streaming errors are handled in the GUI + // just to prevent duplicate error messages in jetbrains (same logic in webview protocol) if ( ["llm/streamChat", "chatDescriber/describe"].includes( message.messageType, @@ -346,7 +344,13 @@ export class Core { }); on("config/refreshProfiles", async (msg) => { + const { selectOrgId, selectProfileId } = msg.data ?? {}; await this.configHandler.refreshAll(); + if (selectOrgId) { + await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId); + } else if (selectProfileId) { + await this.configHandler.setSelectedProfileId(selectProfileId); + } }); on("config/updateSharedConfig", async (msg) => { @@ -543,10 +547,8 @@ export class Core { } }); - // File changes - // TODO - remove remaining logic for these from IDEs where possible + // File changes - TODO - remove remaining logic for these from IDEs where possible on("files/changed", this.handleFilesChanged); - const refreshIfNotIgnored = async (uris: string[]) => { const toRefresh: string[] = []; for (const uri of uris) { @@ -622,7 +624,6 @@ export class Core { on("docs/getDetails", async (msg) => { return await this.docsService.getDetails(msg.data.startUrl); }); - // on("didChangeSelectedProfile", async (msg) => { await this.configHandler.setSelectedProfileId(msg.data.id); @@ -676,10 +677,7 @@ export class Core { throw new Error(`Tool ${toolCall.function.name} not found`); } - const llm = (await this.configHandler.loadConfig()).config - ?.selectedModelByRole.chat; - - if (!llm) { + if (!config.selectedModelByRole.chat) { throw new Error("No chat model selected"); } @@ -688,7 +686,7 @@ export class Core { JSON.parse(toolCall.function.arguments || "{}"), { ide: this.ide, - llm, + llm: config.selectedModelByRole.chat, fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), tool, diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index d2323aca3..8ca9a8154 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -2,7 +2,7 @@ import { DiffLine, ILLM } from "../.."; import { generateLines } from "../../diff/util"; import { supportedLanguages } from "../../util/treeSitter"; import { getUriFileExtension } from "../../util/uri"; - +import { deterministicApplyLazyEdit } from "./deterministic"; import { streamLazyApply } from "./streamLazyApply"; import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply"; @@ -13,35 +13,44 @@ function canUseInstantApply(filename: string) { export async function applyCodeBlock( oldFile: string, - newFile: string, + newLazyFile: string, filename: string, llm: ILLM, -): Promise<[boolean, AsyncGenerator]> { - // This was buggy, removed for now, maybe forever - // if (canUseInstantApply(filename)) { - // const diffLines = await deterministicApplyLazyEdit( - // oldFile, - // newFile, - // filename, - // ); +): Promise<{ + isInstantApply: boolean; + diffLinesGenerator: AsyncGenerator; +}> { + if (canUseInstantApply(filename)) { + const diffLines = await deterministicApplyLazyEdit({ + oldFile, + newLazyFile, + filename, + onlyFullFileRewrite: true, + }); - // // Fall back to LLM method if we couldn't apply deterministically - // if (diffLines !== undefined) { - // const diffGenerator = generateLines(diffLines!); - // return [true, diffGenerator]; - // } - // } + if (diffLines !== undefined) { + return { + isInstantApply: true, + diffLinesGenerator: generateLines(diffLines!), + }; + } + } // If the code block is a diff - if (isUnifiedDiffFormat(newFile)) { + if (isUnifiedDiffFormat(newLazyFile)) { try { - const diffLines = applyUnifiedDiff(oldFile, newFile); - const diffGenerator = generateLines(diffLines!); - return [true, diffGenerator]; + const diffLines = applyUnifiedDiff(oldFile, newLazyFile); + return { + isInstantApply: true, + diffLinesGenerator: generateLines(diffLines!), + }; } catch (e) { console.error("Failed to apply unified diff", e); } } - return [false, streamLazyApply(oldFile, filename, newFile, llm)]; + return { + isInstantApply: false, + diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm), + }; } diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts index 7590e5025..adfaafa5e 100644 --- a/core/edit/lazy/deterministic.test.ts +++ b/core/edit/lazy/deterministic.test.ts @@ -21,11 +21,11 @@ async function collectDiffs( ): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> { const ourDiffs: DiffLine[] = []; - for (const diffLine of (await deterministicApplyLazyEdit( + for (const diffLine of (await deterministicApplyLazyEdit({ oldFile, - newFile, + newLazyFile: newFile, filename, - )) ?? []) { + })) ?? []) { ourDiffs.push(diffLine); } diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index 1e3a0ec4e..947f628e4 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -15,6 +15,11 @@ type AstReplacements = Array<{ replacementNodes: Parser.SyntaxNode[]; }>; +const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/; +export function isLazyText(text: string): boolean { + return LAZY_COMMENT_REGEX.test(text); +} + function reconstructNewFile( oldFile: string, newFile: string, @@ -121,11 +126,23 @@ function nodeSurroundedInLazyBlocks( } // TODO: If we don't have high confidence, return undefined to fall back to slower methods -export async function deterministicApplyLazyEdit( - oldFile: string, - newLazyFile: string, - filename: string, -): Promise { +export async function deterministicApplyLazyEdit({ + oldFile, + newLazyFile, + filename, + /** + * Using this as a flag to slowly reintroduce lazy applies. + * With this set, we will only attempt to deterministically apply + * when there are no lazy blocks and then just replace the whole file, + * and otherwise never use instant apply + */ + onlyFullFileRewrite = false, +}: { + oldFile: string; + newLazyFile: string; + filename: string; + onlyFullFileRewrite?: boolean; +}): Promise { const parser = await getParserForFile(filename); if (!parser) { return undefined; @@ -135,6 +152,14 @@ export async function deterministicApplyLazyEdit( let newTree = parser.parse(newLazyFile); let reconstructedNewFile: string | undefined = undefined; + if (onlyFullFileRewrite) { + if (!isLazyText(newTree.rootNode.text)) { + return myersDiff(oldFile, newLazyFile); + } else { + return undefined; + } + } + // If there is no lazy block anywhere, we add our own to the outsides // so that large chunks of the file don't get removed if (!findInAst(newTree.rootNode, isLazyBlock)) { @@ -198,11 +223,6 @@ export async function deterministicApplyLazyEdit( return diff; } -const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/; -export function isLazyLine(text: string): boolean { - return LAZY_COMMENT_REGEX.test(text); -} - function isLazyBlock(node: Parser.SyntaxNode): boolean { // Special case for "{/* ... existing code ... */}" if ( @@ -213,7 +233,7 @@ function isLazyBlock(node: Parser.SyntaxNode): boolean { return true; } - return node.type.includes("comment") && isLazyLine(node.text); + return node.type.includes("comment") && isLazyText(node.text); } function stringsWithinLevDistThreshold( diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 139d033ab..6ac50795a 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -288,7 +288,10 @@ class OpenAI extends BaseLLM { // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' - body.parallel_tool_calls = false; + // o3 does not support this + if (!body.model.startsWith("o3")) { + body.parallel_tool_calls = false; + } } return body; diff --git a/core/package-lock.json b/core/package-lock.json index 494992220..d06bd61f5 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -126,7 +126,8 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } }, "node_modules/@75lb/deep-merge": { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index d8f262d52..3cbed1ad0 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -74,7 +74,16 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "config/deleteModel": [{ title: string }, void]; "config/reload": [undefined, ConfigResult]; - "config/refreshProfiles": [undefined, void]; + "config/refreshProfiles": [ + ( + | undefined + | { + selectOrgId?: string; + selectProfileId?: string; + } + ), + void, + ]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; "config/updateSelectedModel": [ diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index 59f816c15..3143b12cf 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -5,15 +5,49 @@ keywords: [rules, .continuerules, system, prompt, message] # Rules -Rules are used to provide instructions to **chat** models. They are inserted into the system message for all chat requests. Rules are _only_ used during Chat, they are not used for autocomplete or other roles. +Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests. -## Hub `rules` blocks +Rules are **_NOT_** included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). + +You can view the current rules by clicking the pen icon above the main toolbar: + +![rules input toolbar section](/img/notch-rules.png) + +To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#chat-system-message)). + +## `rules` blocks Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. +These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally. Rules blocks can be simple text, or have the following properties: + +- `name` (**required**): A display name/title for the rule +- `rule` (**required**): The text content of the rule + +Examples: + +```yaml title="config.yaml" +rules: + - uses: myprofile/my-mood-setter + with: + TONE: consise + - Always annotate Python functions with their parameter and return types + - Always write Google style docstrings for functions and classes + - name: Server-side components + rule: When writing Next.js React components, use server-side components where possible instead of client components. +``` + +## Chat System Message + +Continue includes a simple default system message for [Chat](../../chat/how-to-use-it.md) and [Agent](../../agent/how-to-use-it.md) requests, to help the model provide reliable codeblock formats in its output. + +This can be viewed in the rules section of the toolbar (see above), or visit the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4) + +Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](../../reference.md#models). + ## `.continuerules` -You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules. +You can create project-specific rules by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules. ### Simple Examples diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index 78574b096..040cdaa2e 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -10,9 +10,15 @@ import Tabs from "@theme/Tabs"; When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file. -Generally speaking, models proficient in chat and edit can also be used for applying code. +## Recommended Apply models -Explore apply models in [the hub](https://hub.continue.dev/explore/models?roles=apply). +We recommend [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can get an API key [here](https://app.relace.ai/settings/api-keys). + +However, most Chat models can also be used for applying code changes. We recommend smaller/cheaper models for the task, such as Claude 3.5 Haiku. + +:::info +Explore all apply models in [the Hub](https://hub.continue.dev/explore/models?roles=apply) +::: ## Prompt templating diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 6269a1bb7..73e4fc1c0 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -237,7 +237,13 @@ context: ### `rules` -List of rules that the LLM should follow. These are inserted into the system message for all chat requests. +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 + Example @@ -245,9 +251,11 @@ Example rules: - uses: myprofile/my-mood-setter with: - MOOD: happy + TONE: concise - Always annotate Python functions with their parameter and return types - Always write Google style docstrings for functions and classes + - name: Server-side components + rule: When writing Next.js React components, use server-side components where possible instead of client components. ``` --- diff --git a/docs/static/img/notch-rules.png b/docs/static/img/notch-rules.png new file mode 100644 index 000000000..02a175817 Binary files /dev/null and b/docs/static/img/notch-rules.png differ diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index aa99f752c..e4f2af902 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -25,4 +25,6 @@ e2e/vsix e2e/test-continue/* !e2e/test-continue/config.json e2e/test-continue-yaml/* -!e2e/test-continue-yaml/config.yaml \ No newline at end of file +!e2e/test-continue-yaml/config.yaml + +config-yaml-schema.json \ No newline at end of file diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 088ac0001..79b03de94 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -588,6 +588,10 @@ { "fileMatch": ".continuerc.json", "url": "./continue_rc_schema.json" + }, + { + "fileMatch": "**/config.yaml", + "url": "./config-yaml-schema.json" } ] }, diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index fbec94f6c..c16e627c3 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -10,7 +10,11 @@ const { autodetectPlatformAndArch, } = require("../../../scripts/util/index"); -const { copyConfigSchema, writeBuildTimestamp } = require("./utils"); +const { + copyConfigSchema, + writeBuildTimestamp, + generateConfigYamlSchema, +} = require("./utils"); // Clear folders that will be packaged to ensure clean slate rimrafSync(path.join(__dirname, "..", "bin")); @@ -63,6 +67,9 @@ const isMacTarget = target?.startsWith("darwin"); (async () => { console.log("[info] Packaging extension for target ", target); + // Generate and copy over config-yaml-schema.json + generateConfigYamlSchema(); + // Copy config schemas to intellij copyConfigSchema(); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 8a144731f..7023b6372 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -10,7 +10,20 @@ const { const continueDir = path.join(__dirname, "..", "..", ".."); +function generateConfigYamlSchema() { + process.chdir(path.join(continueDir, "packages", "config-yaml")); + execCmdSync("npm install"); + execCmdSync("npm run build"); + execCmdSync("npm run generate-schema"); + fs.copyFileSync( + path.join("schema", "config-yaml-schema.json"), + path.join(continueDir, "extensions", "vscode", "config-yaml-schema.json"), + ); + console.log("[info] Generated config.yaml schema"); +} + function copyConfigSchema() { + process.chdir(path.join(continueDir, "extensions", "vscode")); // Modify and copy for .continuerc.json const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8")); schema.$defs.SerializedContinueConfig.properties.mergeBehavior = { @@ -526,6 +539,7 @@ function writeBuildTimestamp() { } module.exports = { + generateConfigYamlSchema, copyConfigSchema, installNodeModules, buildGui, diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 1bd22c7f4..bfc344b06 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -2,6 +2,7 @@ import { getContinueRcPath, getTsConfigPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; +import * as path from "path"; import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; @@ -32,6 +33,22 @@ export async function activateExtension(context: vscode.ExtensionContext) { ); } + // Only set the YAML schema configuration if it hasn't been set before + if (!context.globalState.get("yamlSchemaConfigured")) { + vscode.workspace.getConfiguration("yaml").update( + "schemas", + { + [path.join( + context.extension.extensionUri.fsPath, + "config-yaml-schema.json", + )]: [".continue/**/*.yaml"], + }, + vscode.ConfigurationTarget.Global, + ); + // Mark that we've configured the YAML schema + context.globalState.update("yamlSchemaConfigured", true); + } + const api = new VsCodeContinueApi(vscodeExtension); const continuePublicApi = { registerCustomContextProvider: api.registerCustomContextProvider.bind(api), diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index 4942cb0c1..2741fea0b 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -116,17 +116,17 @@ export class ApplyManager { return; } - const [instant, diffLines] = await applyCodeBlock( + const { isInstantApply, diffLinesGenerator } = await applyCodeBlock( editor.document.getText(), text, getUriPathBasename(editor.document.uri.toString()), llm, ); - if (instant) { + if (isInstantApply) { await this.verticalDiffManager.streamDiffLines( - diffLines, - instant, + diffLinesGenerator, + isInstantApply, streamId, toolCallId, ); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index c955f8d51..bcdb88edd 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -193,24 +193,11 @@ export class VsCodeExtension { let profileId = queryParams.get("profile_id"); let orgId = queryParams.get("org_id"); - if (orgId && orgId !== "null") { - // In case org id is passed with profile id - // Make sure org is updated before profile is set - if (profileId && profileId !== "null") { - this.core.invoke("didChangeSelectedOrg", { - id: orgId, - profileId, - }); - } else { - this.core.invoke("didChangeSelectedOrg", { - id: orgId, - }); - } - } else if (profileId && profileId !== "null") { - this.core.invoke("didChangeSelectedProfile", { - id: profileId, - }); - } + this.core.invoke("config/refreshProfiles", { + selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined), + selectProfileId: + profileId === "null" ? undefined : (profileId ?? undefined), + }); }); // Battery diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts new file mode 100644 index 000000000..dd46ad401 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts @@ -0,0 +1,34 @@ +import * as vscode from "vscode"; + +export class DownloadYamlExtensionCodeLensProvider + implements vscode.CodeLensProvider +{ + private yamlExtensionDownloaded(): boolean { + const yamlExtension = vscode.extensions.getExtension("redhat.vscode-yaml"); + return yamlExtension !== undefined; + } + + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + if (!document.uri.fsPath.includes(".continue")) { + return []; + } + if (this.yamlExtensionDownloaded()) { + return []; + } + + const codeLens: vscode.CodeLens = { + range: new vscode.Range(0, 0, 0, 0), + command: { + title: "Download YAML extension for Intellisense", + command: "workbench.extensions.installExtension", + arguments: ["redhat.vscode-yaml"], + }, + isResolved: true, + }; + + return [codeLens]; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/index.ts b/extensions/vscode/src/lang-server/codeLens/providers/index.ts index 00a309e62..03d89aa44 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/index.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/index.ts @@ -1,3 +1,4 @@ +export { DownloadYamlExtensionCodeLensProvider } from "./DownloadYamlExtensionCodeLensProvider"; export { QuickActionsCodeLensProvider } from "./QuickActionsCodeLensProvider"; export { SuggestionsCodeLensProvider } from "./SuggestionsCodeLensProvider"; export { VerticalDiffCodeLensProvider as VerticalPerLineCodeLensProvider } from "./VerticalPerLineCodeLensProvider"; diff --git a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts index 9138fba8b..e17312fa0 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 downloadYamlExtensionCodeLensDisposable: vscode.Disposable | undefined = + undefined; /** * Registers the Quick Actions CodeLens provider if Quick Actions are enabled. @@ -96,6 +98,10 @@ export function registerAllCodeLensProviders( tutorialCodeLensDisposable.dispose(); } + if (downloadYamlExtensionCodeLensDisposable) { + downloadYamlExtensionCodeLensDisposable.dispose(); + } + const verticalDiffCodeLens = new providers.VerticalPerLineCodeLensProvider( editorToVerticalDiffCodeLens, ); @@ -110,6 +116,11 @@ export function registerAllCodeLensProviders( new providers.SuggestionsCodeLensProvider(), ); + downloadYamlExtensionCodeLensDisposable = registerCodeLensProvider( + "yaml", + new providers.DownloadYamlExtensionCodeLensProvider(), + ); + if (config) { registerQuickActionsProvider(config, context); diff --git a/gui/package-lock.json b/gui/package-lock.json index 2105fc59b..ef66ddbcc 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -222,7 +222,8 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } }, "node_modules/@adobe/css-tools": { diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/AcceptRejectAllButtons.tsx similarity index 90% rename from gui/src/components/StepContainer/AcceptRejectAllButtons.tsx rename to gui/src/components/AcceptRejectAllButtons.tsx index 8d2e59dd3..7a9c28062 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/AcceptRejectAllButtons.tsx @@ -1,10 +1,10 @@ -import { useContext } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; -import { getMetaKeyLabel } from "../../util"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsSingleRangeEditOrInsertion } from "../../redux/slices/sessionSlice"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppSelector } from "../redux/hooks"; +import { selectIsSingleRangeEditOrInsertion } from "../redux/slices/sessionSlice"; +import { getMetaKeyLabel } from "../util"; export interface AcceptRejectAllButtonsProps { pendingApplyStates: ApplyState[]; diff --git a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx index 3d59ac239..9651ec235 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx @@ -1,18 +1,18 @@ -import FileIcon from "../FileIcon"; import { ChevronDownIcon, ChevronRightIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { useState } from "react"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; -import { getMarkdownLanguageTagForFile } from "core/util"; -import styled from "styled-components"; 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; diff --git a/gui/src/components/StepContainer/FeedbackButtons.tsx b/gui/src/components/FeedbackButtons.tsx similarity index 86% rename from gui/src/components/StepContainer/FeedbackButtons.tsx rename to gui/src/components/FeedbackButtons.tsx index 4ef09a833..6ad0992df 100644 --- a/gui/src/components/StepContainer/FeedbackButtons.tsx +++ b/gui/src/components/FeedbackButtons.tsx @@ -1,12 +1,12 @@ import { - HandThumbUpIcon, HandThumbDownIcon, + HandThumbUpIcon, } from "@heroicons/react/24/outline"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { ChatHistoryItem } from "core"; -import { useState, useContext } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; +import { useContext, useState } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppSelector } from "../redux/hooks"; +import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip"; export interface FeedbackButtonsProps { item: ChatHistoryItem; diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx index d40ed72b9..08a61e2e3 100644 --- a/gui/src/components/StepContainer/EditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -1,12 +1,12 @@ import { ChatHistoryItem } from "core"; -import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; -import FeedbackButtons from "./FeedbackButtons"; import { renderChatMessage } from "core/util/messageContent"; -import { CopyIconButton } from "../gui/CopyIconButton"; 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; diff --git a/gui/src/components/StepContainer/Reasoning.tsx b/gui/src/components/StepContainer/Reasoning.tsx index d5537c82b..b2c7ec19e 100644 --- a/gui/src/components/StepContainer/Reasoning.tsx +++ b/gui/src/components/StepContainer/Reasoning.tsx @@ -10,7 +10,7 @@ import { vscQuickInputBackground, } from ".."; import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; interface ReasoningProps { item: ChatHistoryItem; diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index f016b3474..dce39ea6f 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -1,12 +1,12 @@ import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; import { 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"; -import FeedbackButtons from "./FeedbackButtons"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsInEditMode } from "../../redux/slices/sessionSlice"; export interface ResponseActionsProps { isTruncated: boolean; diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 01560e595..aac4b877a 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -8,7 +8,7 @@ import { useAppSelector } from "../../redux/hooks"; import { selectUIConfig } from "../../redux/slices/configSlice"; import { deleteMessage } from "../../redux/slices/sessionSlice"; import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; import Reasoning from "./Reasoning"; import ResponseActions from "./ResponseActions"; import ThinkingIndicator from "./ThinkingIndicator"; @@ -43,9 +43,6 @@ export default function StepContainer(props: StepContainerProps) { historyItemAfterThis?.message.role === "thinking"; const hideActions = hideActionSpace || (isStreaming && props.isLast); - // const isStepAheadOfCurCheckpoint = - // isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex; - useEffect(() => { if (!isStreaming) { const content = renderChatMessage(props.item.message).trim(); @@ -83,9 +80,7 @@ export default function StepContainer(props: StepContainerProps) { } return ( -
+
{uiConfig?.displayRawMarkdown ? (
 void;
 }
 
-export default function ApplyActions(props: ApplyActionsProps) {
+export function ApplyActions(props: ApplyActionsProps) {
   const [hasRejected, setHasRejected] = useState(false);
   const [showApplied, setShowApplied] = useState(false);
   const isClosed = props.applyState?.status === "closed";
@@ -37,11 +36,10 @@ export default function ApplyActions(props: ApplyActionsProps) {
 
   const applyButton = (text: string) => (
     
+    
+  );
+}
diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx
new file mode 100644
index 000000000..550d1fd28
--- /dev/null
+++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx
@@ -0,0 +1,42 @@
+import { getLastNPathParts } from "core/util/uri";
+import FileIcon from "../../FileIcon";
+import { ToolTip } from "../../gui/Tooltip";
+
+export interface FileInfoProps {
+  filepath: string;
+  onClick?: () => void;
+  range?: string;
+}
+
+const TOOLTIP_ID = "file-info-tooltip";
+
+export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => {
+  return (
+    <>
+      
+
+ +
+ + {getLastNPathParts(filepath, 1)} + {range && ` ${range}`} + +
+ + + ); +}; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx similarity index 81% rename from gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx index c430c8d62..b730b30e5 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx @@ -5,7 +5,7 @@ export interface GeneratingCodeLoaderProps { codeBlockContent: string; } -export default function GeneratingCodeLoader({ +export function GeneratingCodeLoader({ showLineCount, codeBlockContent, }: GeneratingCodeLoaderProps) { @@ -16,7 +16,7 @@ export default function GeneratingCodeLoader({ : `${numLinesCodeBlock} lines generated`; return ( - + {showLineCount ? linesGeneratedText : "Generating"} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx new file mode 100644 index 000000000..b8784dd07 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx @@ -0,0 +1,21 @@ +import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline"; + +/** + * Button that inserts code at the current cursor position + */ +interface InsertButtonProps { + onInsert: () => void; +} + +export function InsertButton({ onInsert }: InsertButtonProps) { + return ( +
+
+ +
+
+ ); +} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx similarity index 71% rename from gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx index 35bc54349..07da9e7da 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -7,9 +7,7 @@ interface RunInTerminalButtonProps { command: string; } -export default function RunInTerminalButton({ - command, -}: RunInTerminalButtonProps) { +export function RunInTerminalButton({ command }: RunInTerminalButtonProps) { const ideMessenger = useContext(IdeMessengerContext); function runInTerminal() { @@ -18,7 +16,7 @@ export default function RunInTerminalButton({ return (
<> - Run + Run
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx similarity index 100% rename from gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx index 9ffed883c..b60691d7b 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx @@ -1,7 +1,7 @@ import { ReactNode, useMemo } from "react"; import { Tooltip } from "react-tooltip"; -import { lightGray, vscForeground } from "../.."; import styled from "styled-components"; +import { lightGray, vscForeground } from "../.."; import { getFontSize } from "../../../util"; export const ToolbarButton = styled.button` diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx similarity index 59% rename from gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 0397603f3..111359fc8 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -1,6 +1,6 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; -import { useContext, useState } from "react"; +import { useContext, useEffect, useMemo, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, @@ -8,6 +8,7 @@ import { vscEditorBackground, } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useIdeMessengerRequest } from "../../../hooks"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppSelector } from "../../../redux/hooks"; import { @@ -16,12 +17,13 @@ import { } from "../../../redux/slices/sessionSlice"; import { getFontSize } from "../../../util"; import { isTerminalCodeBlock } from "../utils"; -import ApplyActions from "./ApplyActions"; -import CopyButton from "./CopyButton"; +import { ApplyActions } from "./ApplyActions"; +import { CopyButton } from "./CopyButton"; +import { CreateFileButton } from "./CreateFileButton"; import { FileInfo } from "./FileInfo"; -import GeneratingCodeLoader from "./GeneratingCodeLoader"; -import InsertButton from "./InsertButton"; -import RunInTerminalButton from "./RunInTerminalButton"; +import { GeneratingCodeLoader } from "./GeneratingCodeLoader"; +import { InsertButton } from "./InsertButton"; +import { RunInTerminalButton } from "./RunInTerminalButton"; const TopDiv = styled.div` display: flex; @@ -59,7 +61,7 @@ export interface StepContainerPreToolbarProps { disableManualApply?: boolean; } -export default function StepContainerPreToolbar({ +export function StepContainerPreToolbar({ codeBlockContent, language, relativeFilepath, @@ -77,11 +79,21 @@ export default function StepContainerPreToolbar({ expanded ?? (isInEditMode ? false : true), ); - // We store the resolved file URI to ensure we use the same file when - // accepting/rejecting diffs, even if no `relativeFilepath` is provided - const [resolvedFileUri, setResolvedFileUri] = useState( - undefined, + const [relativeFilepathUri, setRelativeFilepathUri] = useState( + null, ); + + const fileExistsInput = useMemo( + () => (relativeFilepathUri ? { filepath: relativeFilepathUri } : null), + [relativeFilepathUri], + ); + + const { + result: fileExists, + refresh: refreshFileExists, + isLoading: isLoadingFileExists, + } = useIdeMessengerRequest("fileExists", fileExistsInput); + const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, ); @@ -90,24 +102,54 @@ export default function StepContainerPreToolbar({ selectApplyStateByStreamId(state, codeBlockStreamId), ); + /** + * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`. + * However, if no `relativeFilepath` is defined, then this will + * be the URI of the currently open file at the time the user clicks "Apply". + */ + const [appliedFileUri, setAppliedFileUri] = useState( + undefined, + ); + const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; const hasFileExtension = relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); - const displayFilepath = relativeFilepath ?? resolvedFileUri; + // If we are creating a file, we already render that in the button + // so we don't want to dispaly it twice here + const displayFilepath = relativeFilepath ?? appliedFileUri; - async function getFileUri() { + // TODO: This logic should be moved to a thunk + // Handle apply keyboard shortcut + useWebviewListener( + "applyCodeFromChat", + async () => onClickApply(), + [isNextCodeBlock, codeBlockContent], + !isNextCodeBlock, + ); + + useEffect(() => { + const getRelativeFilepathUri = async () => { + if (relativeFilepath) { + const resolvedUri = await inferResolvedUriFromRelativePath( + relativeFilepath, + ideMessenger.ide, + ); + setRelativeFilepathUri(resolvedUri); + } + }; + getRelativeFilepathUri(); + }, [relativeFilepath, ideMessenger.ide]); + + async function getFileUriToApplyTo() { // If we've already resolved a file URI (from clicking apply), use that - if (resolvedFileUri) { - return resolvedFileUri; + if (appliedFileUri) { + return appliedFileUri; } - // If a relative filepath was provided, try to resolve it - if (relativeFilepath) { - return await inferResolvedUriFromRelativePath( - relativeFilepath, - ideMessenger.ide, - ); + // If we have the `relativeFilepathUri`, use that + if (relativeFilepathUri) { + return relativeFilepathUri; } // If no filepath was provided, get the current file @@ -120,40 +162,32 @@ export default function StepContainerPreToolbar({ } async function onClickApply() { - const fileUri = await getFileUri(); + const fileUri = await getFileUriToApplyTo(); if (!fileUri) { ideMessenger.ide.showToast( "error", "Could not resolve filepath to apply changes", ); - return; } - setResolvedFileUri(fileUri); - + // applyToFile will create the file if it doesn't exist ideMessenger.post("applyToFile", { streamId: codeBlockStreamId, filepath: fileUri, text: codeBlockContent, }); + + setAppliedFileUri(fileUri); + refreshFileExists(); } function onClickInsertAtCursor() { ideMessenger.post("insertAtCursor", { text: codeBlockContent }); } - // TODO: This logic should be moved to a thunk - // Handle apply keyboard shortcut - useWebviewListener( - "applyCodeFromChat", - async () => onClickApply(), - [isNextCodeBlock, codeBlockContent], - !isNextCodeBlock, - ); - async function handleDiffAction(action: "accept" | "reject") { - const filepath = await getFileUri(); + const filepath = await getFileUriToApplyTo(); if (!filepath) { ideMessenger.ide.showToast( "error", @@ -167,13 +201,13 @@ export default function StepContainerPreToolbar({ streamId: codeBlockStreamId, }); - setResolvedFileUri(undefined); + setAppliedFileUri(undefined); } function onClickFilename() { - if (resolvedFileUri) { + if (appliedFileUri) { ideMessenger.post("showFile", { - filepath: resolvedFileUri, + filepath: appliedFileUri, }); } @@ -184,8 +218,32 @@ export default function StepContainerPreToolbar({ } } - // We want until there is an extension in the filepath to avoid rendering - // an incomplete filepath + const renderActionButtons = () => { + if (isTerminalCodeBlock(language, codeBlockContent)) { + return ; + } + + if (isLoadingFileExists) { + return null; + } + + if (fileExists) { + return ( + handleDiffAction("accept")} + onClickReject={() => handleDiffAction("reject")} + /> + ); + } + + return ; + }; + + // We wait until there is an extension in the filepath to avoid rendering + // an incomplete filepath if (relativeFilepath && !hasFileExtension) { return children; } @@ -196,7 +254,7 @@ export default function StepContainerPreToolbar({
setIsExpanded(!isExpanded)} - className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${ + className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${ isExpanded ? "rotate-0" : "-rotate-90" }`} /> @@ -204,10 +262,12 @@ export default function StepContainerPreToolbar({ ) : ( - {language} + + {language} + )}
@@ -219,20 +279,12 @@ export default function StepContainerPreToolbar({ /> ) : ( <> - - +
+ + +
- {isTerminalCodeBlock(language, codeBlockContent) ? ( - - ) : ( - handleDiffAction("accept")} - onClickReject={() => handleDiffAction("reject")} - /> - )} + {renderActionButtons()} )}
diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/StyledMarkdownPreview/SymbolLink.tsx similarity index 100% rename from gui/src/components/markdown/SymbolLink.tsx rename to gui/src/components/StyledMarkdownPreview/SymbolLink.tsx diff --git a/gui/src/components/markdown/SyntaxHighlightedPre.tsx b/gui/src/components/StyledMarkdownPreview/SyntaxHighlightedPre.tsx similarity index 100% rename from gui/src/components/markdown/SyntaxHighlightedPre.tsx rename to gui/src/components/StyledMarkdownPreview/SyntaxHighlightedPre.tsx diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx similarity index 99% rename from gui/src/components/markdown/StyledMarkdownPreview.tsx rename to gui/src/components/StyledMarkdownPreview/index.tsx index 3f7c82bca..40494ee6c 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -22,7 +22,7 @@ import { ToolTip } from "../gui/Tooltip"; import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; -import StepContainerPreToolbar from "./StepContainerPreToolbar"; +import { StepContainerPreToolbar } from "./StepContainerPreToolbar"; import SymbolLink from "./SymbolLink"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import { isSymbolNotRif, matchCodeToSymbolOrFile } from "./utils"; diff --git a/gui/src/components/markdown/katex.css b/gui/src/components/StyledMarkdownPreview/katex.css similarity index 100% rename from gui/src/components/markdown/katex.css rename to gui/src/components/StyledMarkdownPreview/katex.css diff --git a/gui/src/components/markdown/markdown.css b/gui/src/components/StyledMarkdownPreview/markdown.css similarity index 100% rename from gui/src/components/markdown/markdown.css rename to gui/src/components/StyledMarkdownPreview/markdown.css diff --git a/gui/src/components/markdown/utils.ts b/gui/src/components/StyledMarkdownPreview/utils.ts similarity index 94% rename from gui/src/components/markdown/utils.ts rename to gui/src/components/StyledMarkdownPreview/utils.ts index 3961f11d0..8b2af26c8 100644 --- a/gui/src/components/markdown/utils.ts +++ b/gui/src/components/StyledMarkdownPreview/utils.ts @@ -23,10 +23,6 @@ const commonTerminalCommands = [ "bundle", ]; -export function getTerminalCommand(text: string): string { - return text.startsWith("$ ") ? text.slice(2) : text; -} - export function isTerminalCodeBlock( language: string | undefined | null, text: string, diff --git a/gui/src/components/markdown/utils/fixDoubleDollarLatex.ts b/gui/src/components/StyledMarkdownPreview/utils/fixDoubleDollarLatex.ts similarity index 100% rename from gui/src/components/markdown/utils/fixDoubleDollarLatex.ts rename to gui/src/components/StyledMarkdownPreview/utils/fixDoubleDollarLatex.ts diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts similarity index 100% rename from gui/src/components/markdown/utils/patchNestedMarkdown.ts rename to gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts diff --git a/gui/src/components/markdown/utils/remarkTables.tsx b/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx similarity index 100% rename from gui/src/components/markdown/utils/remarkTables.tsx rename to gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx diff --git a/gui/src/components/gui/Tooltip.tsx b/gui/src/components/gui/Tooltip.tsx index cf934f750..1eae5b77b 100644 --- a/gui/src/components/gui/Tooltip.tsx +++ b/gui/src/components/gui/Tooltip.tsx @@ -1,9 +1,10 @@ +import { CSSProperties } from "react"; import ReactDOM from "react-dom"; -import { Tooltip } from "react-tooltip"; +import { ITooltip, Tooltip } from "react-tooltip"; import { vscBackground, vscForeground, vscInputBorder } from ".."; import { fontSize } from "../../util"; -const TooltipStyles = { +const TooltipStyles: CSSProperties = { fontSize: fontSize(-2), backgroundColor: vscBackground, outline: `0.5px solid ${vscInputBorder}`, @@ -14,7 +15,7 @@ const TooltipStyles = { textAlign: "center", }; -export function ToolTip(props: any) { +export function ToolTip(props: ITooltip) { const combinedStyles = { ...TooltipStyles, ...props.style, diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 252126425..f243f5ac4 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -158,7 +158,7 @@ function InputToolbar(props: InputToolbarProps) { fileInputRef.current?.click(); }} /> - + Attach an image @@ -171,7 +171,7 @@ function InputToolbar(props: InputToolbarProps) { className="h-3 w-3 hover:brightness-125" /> - + Add context (files, docs, urls, etc.) diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index 4ecf299b7..f7464e793 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -116,7 +116,7 @@ export function BlockSettingsTopToolbar() { ); return ( -
+
-
+
diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx index c414d7f1c..8055e7fa9 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx @@ -6,7 +6,7 @@ import { useContext, useMemo } from "react"; import { vscBadgeBackground } from "../../../.."; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import FileIcon from "../../../../FileIcon"; -import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../../../StyledMarkdownPreview"; import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview"; import { NodeViewWrapper } from "../../components/NodeViewWrapper"; diff --git a/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx index a89ba2e6a..40e3c8d2b 100644 --- a/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx @@ -6,7 +6,7 @@ import { useEffect, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscBackground } from "../.."; import { getFontSize } from "../../../util"; -import StyledMarkdownPreview from "../../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../StyledMarkdownPreview"; const SpoilerButton = styled.div` background-color: ${vscBackground}; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx deleted file mode 100644 index 7b204190b..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { getLastNPathParts } from "core/util/uri"; -import FileIcon from "../../FileIcon"; - -export interface FileInfoProps { - filepath: string; - onClick: () => void; - range?: string; -} - -export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => { - return ( -
-
- -
- - {getLastNPathParts(filepath, 1)} - {range && ` ${range}`} - -
- ); -}; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx deleted file mode 100644 index 7d56e012b..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline"; -import { lightGray } from "../.."; - -/** - * Button that inserts code at the current cursor position - */ -interface InsertButtonProps { - onInsert: () => void; -} - -export default function InsertButton({ onInsert }: InsertButtonProps) { - return ( -
-
- -
-
- ); -} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/index.ts b/gui/src/components/markdown/StepContainerPreToolbar/index.ts deleted file mode 100644 index 6e974689a..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from "./StepContainerPreToolbar"; diff --git a/gui/src/hooks/index.ts b/gui/src/hooks/index.ts new file mode 100644 index 000000000..8688c91e5 --- /dev/null +++ b/gui/src/hooks/index.ts @@ -0,0 +1 @@ +export * from "./useIdeMessengerRequest"; diff --git a/gui/src/hooks/useIdeMessengerRequest.ts b/gui/src/hooks/useIdeMessengerRequest.ts new file mode 100644 index 000000000..f03a17571 --- /dev/null +++ b/gui/src/hooks/useIdeMessengerRequest.ts @@ -0,0 +1,44 @@ +import type { FromWebviewProtocol } from "core/protocol"; +import type { SuccessWebviewSingleMessage } from "core/protocol/util"; +import { useContext, useEffect, useState } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; + +/** + * Generic hook for making IDE messenger requests with automatic error handling and refresh capability + */ +export function useIdeMessengerRequest( + messageType: T, + data: FromWebviewProtocol[T][0] | null, +) { + const ideMessenger = useContext(IdeMessengerContext); + const [result, setResult] = useState< + SuccessWebviewSingleMessage["content"] | null + >(null); + const [isLoading, setIsLoading] = useState(false); + + async function makeRequest() { + if (!data) { + setResult(null); + return; + } + + setIsLoading(true); + try { + const response = await ideMessenger.request(messageType, data); + if (response.status === "success") { + setResult(response.content); + } else { + console.error(`Error in ${messageType} request:`, response.error); + setResult(null); + } + } finally { + setIsLoading(false); + } + } + + useEffect(() => { + makeRequest(); + }, [data, messageType]); + + return { result, isLoading, refresh: makeRequest }; +} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 40db6fd8c..751398410 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -13,6 +13,7 @@ import { useCallback, useContext, useEffect, 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"; @@ -24,7 +25,6 @@ import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { useOnboardingCard } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; -import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import { TabBar } from "../../components/TabBar/TabBar"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index e3b0002e1..7e50b7305 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -1,5 +1,5 @@ import { getMarkdownLanguageTagForFile } from "core/util"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; interface CreateFileToolCallProps { relativeFilepath: string; diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index f1592a7fe..304dcb4c7 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,7 +1,7 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { useMemo } from "react"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; -import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; +import AcceptRejectAllButtons from "../../../components/AcceptRejectAllButtons"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; import { useAppSelector } from "../../../redux/hooks"; type EditToolCallProps = { diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index 4bb104cce..e8c9772a9 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,5 +1,5 @@ import { ToolCallState } from "core"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; interface RunTerminalCommandToolCallProps { command: string; diff --git a/packages/config-yaml/.gitignore b/packages/config-yaml/.gitignore new file mode 100644 index 000000000..b73759d7b --- /dev/null +++ b/packages/config-yaml/.gitignore @@ -0,0 +1 @@ +schema/ \ No newline at end of file diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 4e5b8df05..7af4afcc8 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -22,7 +22,8 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } }, "node_modules/@ampproject/remapping": { @@ -3823,6 +3824,16 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zod-to-json-schema": { + "version": "3.24.5", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.5.tgz", + "integrity": "sha512-/AuWwMP+YqiPbsJx5D6TfgRTc4kTLjsh5SOcd4bLsfUg2RcEXrFMJl1DGgdHy2aCfsIA/cr/1JM0xcB2GZji8g==", + "dev": true, + "license": "ISC", + "peerDependencies": { + "zod": "^3.24.1" + } } } } diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index f32235580..c2dfb6362 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -10,7 +10,8 @@ }, "scripts": { "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", - "build": "tsc" + "build": "tsc", + "generate-schema": "tsc && node dist/scripts/generateJsonSchema.js" }, "author": "Continue Dev, Inc.", "license": "Apache-2.0", @@ -25,6 +26,7 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } } diff --git a/packages/config-yaml/src/schemas/commonSlugs.ts b/packages/config-yaml/src/schemas/commonSlugs.ts new file mode 100644 index 000000000..3ba10bbd5 --- /dev/null +++ b/packages/config-yaml/src/schemas/commonSlugs.ts @@ -0,0 +1,30 @@ +export const commonModelSlugs = [ + "anthropic/claude-3-7-sonnet", + "togetherai/llama-4-maverick-instruct-17bx128e", + "google/gemini-2.5-pro", + "mistral/codestral", + "voyageai/voyage-code-3", + "relace/instant-apply", + "xai/grok-2", + "openai/gpt-4o", + "togetherai/llama-4-scout-instruct-17bx16e", + "anthropic/claude-3-5-sonnet", + "google/gemini-2.0-flash", + "voyageai/rerank-2", + "ollama/deepseek-r1", + "morphllm/morph-v0", + "anthropic/claude-3-5-haiku", + "lmstudio/deepseek-r1", + "openai/o3-mini", + "voyageai/voyage-code-2", + "ollama/qwen2.5-coder-1.5b", + "openai/gpt-4o-mini", + "openai/o1", + "mistral/mistral-embed", + "ollama/nomic-embed-text-latest", + "lmstudio/deepseek-r1-8b", + "mistral/mistral-large", + "lmstudio/qwen2.5-coder-1.5b", + "ollama/deepseek-r1-8b", + "openai/text-embedding-3-large", +]; diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 2b2ba0461..add4c38e7 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,4 +1,5 @@ import * as z from "zod"; +import { commonModelSlugs } from "./commonSlugs.js"; import { dataSchema } from "./data/index.js"; import { modelSchema, partialModelSchema } from "./models.js"; @@ -38,15 +39,22 @@ const ruleSchema = z.union([z.string(), ruleObjectSchema]); export type Rule = z.infer; -export const blockItemWrapperSchema = (schema: T) => +const defaultUsesSchema = z.string(); + +export const blockItemWrapperSchema = ( + schema: T, + usesSchema: z.ZodTypeAny = defaultUsesSchema, +) => z.object({ - uses: z.string(), + uses: usesSchema, with: z.record(z.string()).optional(), override: schema.partial().optional(), }); -export const blockOrSchema = (schema: T) => - z.union([schema, blockItemWrapperSchema(schema)]); +export const blockOrSchema = ( + schema: T, + usesSchema: z.ZodTypeAny = defaultUsesSchema, +) => z.union([schema, blockItemWrapperSchema(schema, usesSchema)]); export const commonMetadataSchema = z.object({ tags: z.string().optional(), @@ -64,13 +72,17 @@ export const baseConfigYamlSchema = z.object({ metadata: z.record(z.string()).and(commonMetadataSchema.partial()).optional(), }); +const modelsUsesSchema = z + .string() + .or(z.enum(commonModelSlugs as [string, ...string[]])); + export const configYamlSchema = baseConfigYamlSchema.extend({ models: z .array( z.union([ modelSchema, z.object({ - uses: z.string(), + uses: modelsUsesSchema, with: z.record(z.string()).optional(), override: partialModelSchema.optional(), }), @@ -85,7 +97,7 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ z.union([ ruleSchema, z.object({ - uses: z.string(), + uses: defaultUsesSchema, with: z.record(z.string()).optional(), }), ]), diff --git a/packages/config-yaml/src/scripts/generateJsonSchema.ts b/packages/config-yaml/src/scripts/generateJsonSchema.ts new file mode 100644 index 000000000..308dcf951 --- /dev/null +++ b/packages/config-yaml/src/scripts/generateJsonSchema.ts @@ -0,0 +1,28 @@ +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { zodToJsonSchema } from 'zod-to-json-schema'; +import { configYamlSchema } from '../schemas/index.js'; + +// Get the directory name of the current module +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +// Convert Zod schema to JSON schema +const jsonSchema = zodToJsonSchema(configYamlSchema, { + $refStrategy: 'none', + name: 'ConfigYaml', +}); + +// Output directory and file path +const outDir = path.resolve(__dirname, '../../schema'); +const outFile = path.join(outDir, 'config-yaml-schema.json'); + +// Ensure output directory exists +if (!fs.existsSync(outDir)) { + fs.mkdirSync(outDir, { recursive: true }); +} + +// Write the JSON schema to file +fs.writeFileSync(outFile, JSON.stringify(jsonSchema, null, 2)); + +console.log(`JSON schema has been written to ${outFile}`); \ No newline at end of file diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index ab72a85b1..745b94186 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -37,18 +37,23 @@ export class OpenAIApi implements BaseLlmApi { modifyChatBody(body: T): T { // o-series models - only apply for official OpenAI API const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; - if (isOfficialOpenAIAPI && body.model.startsWith("o")) { - // a) use max_completion_tokens instead of max_tokens - body.max_completion_tokens = body.max_tokens; - body.max_tokens = undefined; + if (isOfficialOpenAIAPI) { + if (body.model.startsWith("o")) { + // a) use max_completion_tokens instead of max_tokens + body.max_completion_tokens = body.max_tokens; + body.max_tokens = undefined; - // b) use "developer" message role rather than "system" - body.messages = body.messages.map((message) => { - if (message.role === "system") { - return { ...message, role: "developer" } as any; - } - return message; - }); + // b) use "developer" message role rather than "system" + body.messages = body.messages.map((message) => { + if (message.role === "system") { + return { ...message, role: "developer" } as any; + } + return message; + }); + } + if (body.tools?.length && !body.model.startsWith("o3")) { + body.parallel_tool_calls = false; + } } return body; }