diff --git a/core/core.ts b/core/core.ts index 68aa605ac..e0446c3b0 100644 --- a/core/core.ts +++ b/core/core.ts @@ -257,9 +257,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, @@ -337,7 +335,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) => { @@ -534,10 +538,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) { @@ -613,7 +615,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); @@ -667,10 +668,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"); } @@ -679,7 +677,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/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/protocol/core.ts b/core/protocol/core.ts index 7f29c2e25..de73cac23 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -72,7 +72,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 ecfb2493c..032ba9b69 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -242,7 +242,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 @@ -250,9 +256,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/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/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx index 2c4e286c7..e645e68c9 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx @@ -1,7 +1,6 @@ import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; import { useEffect, useState } from "react"; -import { lightGray, vscForeground } from "../.."; import { getMetaKeyLabel } from "../../../util"; import Spinner from "../../gui/Spinner"; import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; @@ -14,7 +13,7 @@ interface ApplyActionsProps { onClickApply: () => 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 index 7b204190b..550d1fd28 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx @@ -1,25 +1,42 @@ import { getLastNPathParts } from "core/util/uri"; import FileIcon from "../../FileIcon"; +import { ToolTip } from "../../gui/Tooltip"; export interface FileInfoProps { filepath: string; - onClick: () => void; + onClick?: () => void; range?: string; } +const TOOLTIP_ID = "file-info-tooltip"; + export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => { return ( -
-
- + <> +
+
+ +
+ + {getLastNPathParts(filepath, 1)} + {range && ` ${range}`} +
- - {getLastNPathParts(filepath, 1)} - {range && ` ${range}`} - -
+ + ); }; diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx index c430c8d62..b730b30e5 100644 --- a/gui/src/components/StyledMarkdownPreview/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 index 7d56e012b..b8784dd07 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx @@ -1,5 +1,4 @@ import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline"; -import { lightGray } from "../.."; /** * Button that inserts code at the current cursor position @@ -8,17 +7,14 @@ interface InsertButtonProps { onInsert: () => void; } -export default function InsertButton({ onInsert }: InsertButtonProps) { +export function InsertButton({ onInsert }: InsertButtonProps) { return (
-
- +
+
); diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx index 35bc54349..07da9e7da 100644 --- a/gui/src/components/StyledMarkdownPreview/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/StyledMarkdownPreview/StepContainerPreToolbar/index.ts b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.ts deleted file mode 100644 index ee0cda3f4..000000000 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./StepContainerPreToolbar"; diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx similarity index 59% rename from gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/StepContainerPreToolbar.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 6da63b36b..111359fc8 100644 --- a/gui/src/components/StyledMarkdownPreview/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; @@ -77,11 +79,21 @@ export 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 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 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 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 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 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 function StepContainerPreToolbar({ ) : ( - {language} + + {language} + )}
@@ -219,20 +279,12 @@ export function StepContainerPreToolbar({ /> ) : ( <> - - +
+ + +
- {isTerminalCodeBlock(language, codeBlockContent) ? ( - - ) : ( - handleDiffAction("accept")} - onClickReject={() => handleDiffAction("reject")} - /> - )} + {renderActionButtons()} )}
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/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/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; }