From 155525db20877fdc1ec99cbc5dfd07a91f96e2e3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 26 Jun 2025 14:52:40 -0700 Subject: [PATCH 01/25] add resubmit button to simple tool UI --- gui/src/components/mainInput/icons.ts | 2 + gui/src/pages/gui/Chat.tsx | 1 - .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 43 ++++++++++++------- gui/src/pages/gui/ToolCallDiv/index.tsx | 9 +--- .../ToolCallDiv/toolCallStateToContextItem.ts | 15 +++++++ 5 files changed, 45 insertions(+), 25 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts diff --git a/gui/src/components/mainInput/icons.ts b/gui/src/components/mainInput/icons.ts index d8d04cc83..62d69e65b 100644 --- a/gui/src/components/mainInput/icons.ts +++ b/gui/src/components/mainInput/icons.ts @@ -18,6 +18,7 @@ import { PlusIcon, SparklesIcon, TrashIcon, + WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { DiscordIcon } from "../svg/DiscordIcon"; import { GithubIcon } from "../svg/GithubIcon"; @@ -55,4 +56,5 @@ export const NAMED_ICONS: { [key: string]: any } = { "gitlab-mr": GitlabIcon, http: GlobeAltIcon, trash: TrashIcon, + toolCall: WrenchScrewdriverIcon, }; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 4a6d33849..5ba60e7e9 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -330,7 +330,6 @@ export function Chat() { key={i} toolCallState={item.toolCallState!} toolCall={toolCall} - output={history[index + 1]?.contextItems} historyIndex={index} /> ); diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 07b7838a7..e8af9569a 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -1,26 +1,27 @@ -import { ChevronRightIcon } from "@heroicons/react/24/outline"; -import { ContextItemWithId, Tool, ToolCallState } from "core"; +import { ArrowPathIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; +import { Tool, ToolCallState } from "core"; import { ComponentType, useMemo, useState } from "react"; import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; +import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; +import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; interface SimpleToolCallUIProps { toolCallState: ToolCallState; tool: Tool | undefined; - contextItems: ContextItemWithId[]; icon?: ComponentType>; } export function SimpleToolCallUI({ - contextItems, icon: Icon, toolCallState, tool, }: SimpleToolCallUIProps) { - const ctxItems = useMemo(() => { - return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; - }, [contextItems]); + const shownContextItems = useMemo(() => { + const contextItems = toolCallStateToContextItems(toolCallState); + return contextItems.filter((item) => !item.hidden); + }, [toolCallState]); const [open, setOpen] = useState(false); const [isHovered, setIsHovered] = useState(false); @@ -54,13 +55,23 @@ export function SimpleToolCallUI({ - {args.length > 0 ? ( - - ) : null} +
+ { + console.log("Resubmit clicked"); + }} + > + + + {args.length > 0 ? ( + + ) : null} +
- {ctxItems.length ? ( - ctxItems.map((contextItem, idx) => ( + {shownContextItems.length ? ( + shownContextItems.map((contextItem, idx) => ( )) ) : ( diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 9f867356e..b9614f250 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -12,12 +12,7 @@ import { PencilIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { - ContextItemWithId, - ToolCallDelta, - ToolCallState, - ToolStatus, -} from "core"; +import { ToolCallDelta, ToolCallState, ToolStatus } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { ComponentType, useMemo } from "react"; import { vscButtonBackground } from "../../../components"; @@ -30,7 +25,6 @@ import { ToolCallDisplay } from "./ToolCall"; interface ToolCallDivProps { toolCall: ToolCallDelta; toolCallState: ToolCallState; - output?: ContextItemWithId[]; historyIndex: number; } @@ -86,7 +80,6 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={ props.toolCallState.status === "generated" ? ArrowRightIcon : icon } - contextItems={props.output ?? []} /> ); } diff --git a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts new file mode 100644 index 000000000..ccb8a7976 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts @@ -0,0 +1,15 @@ +import { ContextItemWithId, ToolCallState } from "core"; + +export function toolCallStateToContextItems( + toolCallState: ToolCallState, +): ContextItemWithId[] { + return ( + toolCallState.output?.map((item) => ({ + ...item, + id: { + providerTitle: "toolCall", + itemId: toolCallState.toolCallId, + }, + })) ?? [] + ); +} From ec7c497faf0ab75c31a7620d9307076b38d35bfb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 19:18:09 -0700 Subject: [PATCH 02/25] truncate history icon on non-last tool messages --- .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 20 ++++++------ gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 20 +++++++----- .../gui/ToolCallDiv/TruncateHistoryIcon.tsx | 31 +++++++++++++++++++ gui/src/pages/gui/ToolCallDiv/index.tsx | 2 ++ gui/src/redux/slices/sessionSlice.ts | 22 +++++++++++++ 5 files changed, 77 insertions(+), 18 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/TruncateHistoryIcon.tsx diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index e8af9569a..1f19ea438 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -1,23 +1,28 @@ -import { ArrowPathIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; +import { ChevronRightIcon } from "@heroicons/react/24/outline"; import { Tool, ToolCallState } from "core"; import { ComponentType, useMemo, useState } from "react"; import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; -import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; +import { TruncateHistoryIcon } from "./TruncateHistoryIcon"; interface SimpleToolCallUIProps { toolCallState: ToolCallState; tool: Tool | undefined; icon?: ComponentType>; + historyIndex: number; } export function SimpleToolCallUI({ icon: Icon, toolCallState, tool, + historyIndex, }: SimpleToolCallUIProps) { + const history = useAppSelector((state) => state.session.history); + const dispatch = useAppDispatch(); const shownContextItems = useMemo(() => { const contextItems = toolCallStateToContextItems(toolCallState); return contextItems.filter((item) => !item.hidden); @@ -55,15 +60,8 @@ export function SimpleToolCallUI({
-
- { - console.log("Resubmit clicked"); - }} - > - - +
+ {args.length > 0 ? (
- {!!args.length ? ( - - ) : null} +
+ + {!!args.length ? ( + + ) : null} +
{argsExpanded && !!args.length && ( diff --git a/gui/src/pages/gui/ToolCallDiv/TruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/TruncateHistoryIcon.tsx new file mode 100644 index 000000000..296cbc4e4 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/TruncateHistoryIcon.tsx @@ -0,0 +1,31 @@ +import { ArrowUpTrayIcon } from "@heroicons/react/24/outline"; +import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { truncateHistoryToMessage } from "../../../redux/slices/sessionSlice"; + +export function TruncateHistoryIcon({ + historyIndex, +}: { + historyIndex: number; +}) { + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const history = useAppSelector((state) => state.session.history); + const dispatch = useAppDispatch(); + if (isStreaming || historyIndex === history.length - 1) { + return null; + } + return ( + { + dispatch( + truncateHistoryToMessage({ + index: historyIndex, + }), + ); + }} + > + + + ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index b9614f250..4141631bb 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -80,6 +80,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={ props.toolCallState.status === "generated" ? ArrowRightIcon : icon } + historyIndex={props.historyIndex} /> ); } @@ -89,6 +90,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={getStatusIcon(props.toolCallState.status)} tool={tool} toolCallState={props.toolCallState} + historyIndex={props.historyIndex} > , + ) => { + const { index } = payload; + + if (state.history.length && index < state.history.length) { + state.history = state.history.slice(0, index + 1).concat({ + message: { + id: uuidv4(), + role: "assistant", + content: "", // IMPORTANT - this is subsequently updated by response streaming + }, + contextItems: [], + }); + } + }, submitEditorAndInitAtIndex: ( state, { @@ -676,6 +697,7 @@ export const { addPromptCompletionPair, setActive, submitEditorAndInitAtIndex, + truncateHistoryToMessage, updateHistoryItemAtIndex, clearLastEmptyResponse, setMainEditorContentTrigger, From 62381e87907820dcff83801a6ac11c59932641e1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 19:30:01 -0700 Subject: [PATCH 03/25] don't focus main editor if another editor is focused --- gui/src/components/ModeSelect/ModeSelect.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index a5792d721..8989583ff 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -34,7 +34,9 @@ export function ModeSelect() { const cycleMode = useCallback(() => { dispatch(setMode(mode === "chat" ? "agent" : "chat")); - mainEditor?.commands.focus(); + if (!document.activeElement?.classList.contains("ProseMirror")) { + mainEditor?.commands.focus(); + } }, [mode, mainEditor]); const selectMode = useCallback( From c28f70a9f0f9603a2e52925ef4f2317e20f899da Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 20:23:03 -0700 Subject: [PATCH 04/25] context peek formatting and fix last index logic for tool truncation logic --- core/util/findLast.ts | 6 +- .../belowMainInput/ContextItemsPeek.tsx | 58 +++++++++---------- .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 6 +- gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 6 +- ...ryIcon.tsx => ToolTruncateHistoryIcon.tsx} | 18 ++++-- 5 files changed, 52 insertions(+), 42 deletions(-) rename gui/src/pages/gui/ToolCallDiv/{TruncateHistoryIcon.tsx => ToolTruncateHistoryIcon.tsx} (54%) diff --git a/core/util/findLast.ts b/core/util/findLast.ts index 9e99fd473..256d6e09d 100644 --- a/core/util/findLast.ts +++ b/core/util/findLast.ts @@ -1,6 +1,6 @@ -export function findLastIndex( - arr: any[], - criterion: (item: any) => boolean, +export function findLastIndex( + arr: T[], + criterion: (item: T) => boolean, ): number { let lastIndex = -1; diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 3c7ce9390..cb3009675 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -117,40 +117,36 @@ export function ContextItemsPeekItem({ return (
-
- {getContextItemIcon()} -
-
- {contextItem.name} -
-
{ - if (contextItem.uri?.value) { - e.stopPropagation(); - ideMessenger.post("openUrl", contextItem.uri.value); - } else { - console.error("Couldn't open url", contextItem.uri); - } - } - : undefined - } - > - {contextItem.uri?.type === "file" - ? getUriPathBasename(contextItem.description) - : contextItem.description} -
-
- + {getContextItemIcon()} + + {contextItem.name} + +
{ + if (contextItem.uri?.value) { + e.stopPropagation(); + ideMessenger.post("openUrl", contextItem.uri.value); + } else { + console.error("Couldn't open url", contextItem.uri); + } + } + : undefined + } + > + + {contextItem.uri?.type === "file" + ? getUriPathBasename(contextItem.description) + : contextItem.description} + adsfasdfasdjk; asdfl;kjasdl;fkjasdlk;fja asdfklj;asdl;fkjasdf + {isUrl && ( - + )}
diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 1f19ea438..9ba9ae60d 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -6,7 +6,7 @@ import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; -import { TruncateHistoryIcon } from "./TruncateHistoryIcon"; +import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon"; interface SimpleToolCallUIProps { toolCallState: ToolCallState; @@ -61,7 +61,9 @@ export function SimpleToolCallUI({
- + {!!toolCallState.output?.length && ( + + )} {args.length > 0 ? (
- + {!!toolCallState.output && ( + + )} {!!args.length ? ( state.session.isStreaming); const history = useAppSelector((state) => state.session.history); + const lastMessageIndex = useMemo(() => { + return findLastIndex(history, (item) => !chatMessageIsEmpty(item.message)); + }, [history]); const dispatch = useAppDispatch(); - if (isStreaming || historyIndex === history.length - 1) { + const { mainEditor } = useMainEditor(); + if (isStreaming || lastMessageIndex) { return null; } return ( @@ -23,9 +31,11 @@ export function TruncateHistoryIcon({ index: historyIndex, }), ); + mainEditor?.commands.focus(); }} > - + {historyIndex}/{history.length - 1} + ); } From 9700a10e50ea4bbdbecea64dacf39932b781535e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 27 Jun 2025 21:34:21 -0700 Subject: [PATCH 05/25] WIP: only add tool messages in construct messages --- core/llm/constructMessages.ts | 82 +++++++++++++++---- .../belowMainInput/ContextItemsPeek.tsx | 1 - .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 3 - .../ToolCallDiv/ToolTruncateHistoryIcon.tsx | 5 +- gui/src/redux/slices/sessionSlice.ts | 1 + gui/src/redux/thunks/streamResponse.ts | 7 ++ .../thunks/streamResponseAfterToolCall.ts | 7 ++ 7 files changed, 82 insertions(+), 24 deletions(-) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 49115cb6f..5a3967361 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -4,11 +4,15 @@ import { ContextItemWithId, RuleWithSource, TextMessagePart, + Tool, ToolResultChatMessage, UserChatMessage, } from "../"; import { findLast } from "../util/findLast"; -import { normalizeToMessageParts } from "../util/messageContent"; +import { + normalizeToMessageParts, + renderContextItems, +} from "../util/messageContent"; import { isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; import { RulePolicies } from "./rules/types"; @@ -109,30 +113,38 @@ export function constructMessages( history: ChatHistoryItem[], baseChatOrAgentSystemMessage: string | undefined, rules: RuleWithSource[], + tools: Tool[], rulePolicies?: RulePolicies, ): ChatMessage[] { + const validTools = new Set(tools.map((tool) => tool.function.name)); + const filteredHistory = history.filter( (item) => item.message.role !== "system", ); const msgs: ChatMessage[] = []; - for (let i = 0; i < filteredHistory.length; i++) { - const historyItem = filteredHistory[i]; - - if (messageMode === "chat") { - const toolMessage: ToolResultChatMessage = - historyItem.message as ToolResultChatMessage; - if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { - // remove all tool calls from the history - continue; - } + for (const item of filteredHistory) { + if (item.message.role === "tool") { + continue; // Tool messages will be re-inserted } - if (historyItem.message.role === "user") { - // Gather context items for user messages - let content = normalizeToMessageParts(historyItem.message); + // This was implemented for APIs that require all tool calls to have + // A corresponsing tool sent, which means if a user excluded a tool + // Then sessions with that tool call in the history would fail + // if (messageMode === "chat") { + // const toolMessage: ToolResultChatMessage = + // historyItem.message as ToolResultChatMessage; + // if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { + // // remove all tool calls from the history + // continue; + // } + // } - const ctxItems = historyItem.contextItems + if (item.message.role === "user") { + // Gather context items for user messages + let content = normalizeToMessageParts(item.message); + + const ctxItems = item.contextItems .map((ctxItem) => { return { type: "text", @@ -143,11 +155,47 @@ export function constructMessages( content = [...ctxItems, ...content]; msgs.push({ - ...historyItem.message, + ...item.message, content, }); } else { - msgs.push(historyItem.message); + msgs.push(item.message); + } + + if (item.message.role === "assistant") { + // First, push a version of the message with any valid tools calls + const validToolCalls = item.message.toolCalls?.filter( + (toolCall) => + toolCall.function?.name && + toolCall.id && + validTools.has(toolCall.function.name), + ); + + // Case where no valid tool calls or content are present + msgs.push({ + ...item.message, + toolCalls: validToolCalls, + }); + + // Then push a tool message for each valid tool call + if (validToolCalls?.length) { + // If the assistant message has tool calls, we need to insert tool messages + for (const toolCall of validToolCalls) { + let content: string = "No tool output"; + // TODO toolCallState only supports one tool call per message for now + if ( + item.toolCallState?.toolCallId === toolCall.id && + item.toolCallState?.output + ) { + content = renderContextItems(item.toolCallState.output); + } + msgs.push({ + role: "tool", + content, + toolCallId: toolCall.id!, + }); + } + } } } diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index cb3009675..31c392bf1 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -143,7 +143,6 @@ export function ContextItemsPeekItem({ {contextItem.uri?.type === "file" ? getUriPathBasename(contextItem.description) : contextItem.description} - adsfasdfasdjk; asdfl;kjasdl;fkjasdlk;fja asdfklj;asdl;fkjasdf {isUrl && ( diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 9ba9ae60d..51af15c77 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -2,7 +2,6 @@ import { ChevronRightIcon } from "@heroicons/react/24/outline"; import { Tool, ToolCallState } from "core"; import { ComponentType, useMemo, useState } from "react"; import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; @@ -21,8 +20,6 @@ export function SimpleToolCallUI({ tool, historyIndex, }: SimpleToolCallUIProps) { - const history = useAppSelector((state) => state.session.history); - const dispatch = useAppDispatch(); const shownContextItems = useMemo(() => { const contextItems = toolCallStateToContextItems(toolCallState); return contextItems.filter((item) => !item.hidden); diff --git a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx index cf57a6c08..e4f0a1cc8 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx @@ -19,7 +19,7 @@ export function ToolTruncateHistoryIcon({ }, [history]); const dispatch = useAppDispatch(); const { mainEditor } = useMainEditor(); - if (isStreaming || lastMessageIndex) { + if (isStreaming || historyIndex === lastMessageIndex) { return null; } return ( @@ -34,8 +34,7 @@ export function ToolTruncateHistoryIcon({ mainEditor?.commands.focus(); }} > - {historyIndex}/{history.length - 1} - + ); } diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 80c88dc54..339369cd9 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -157,6 +157,7 @@ export const sessionSlice = createSlice({ const { index } = payload; if (state.history.length && index < state.history.length) { + state.codeBlockApplyStates.curIndex = 0; state.history = state.history.slice(0, index + 1).concat({ message: { id: uuidv4(), diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index caeded723..facc987c7 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,11 +1,13 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core"; +import { modelSupportsTools } from "core/llm/autodetect"; import { constructMessages } from "core/llm/constructMessages"; import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; import posthog from "posthog-js"; import { v4 as uuidv4 } from "uuid"; import { getBaseSystemMessage } from "../../util"; +import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectSelectedChatModel } from "../slices/configSlice"; import { setAppliedRulesAtIndex, @@ -119,11 +121,16 @@ export const streamResponseThunk = createAsyncThunk< messageMode, ); + const activeTools = selectActiveTools(state); + const toolsSupported = modelSupportsTools(selectedChatModel); + const availableTools = toolsSupported ? activeTools : []; + const messages = constructMessages( messageMode, [...updatedHistory], baseChatOrAgentSystemMessage, applicableRules, + availableTools, rulePolicies, ); diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 3a29491c5..75134b951 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,8 +1,10 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; +import { modelSupportsTools } from "core/llm/autodetect"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; import { getBaseSystemMessage } from "../../util"; +import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectSelectedChatModel } from "../slices/configSlice"; import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -67,11 +69,16 @@ export const streamResponseAfterToolCall = createAsyncThunk< messageMode, ); + const activeTools = selectActiveTools(state); + const toolsSupported = modelSupportsTools(selectedChatModel); + const availableTools = toolsSupported ? activeTools : []; + const messages = constructMessages( messageMode, [...updatedHistory], baseChatOrAgentSystemMessage, state.config.config.rules, + availableTools, ); unwrapResult(await dispatch(streamNormalInput({ messages }))); From fc618652aac26ca84dd2579c44a626521ccae5d4 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 29 Jun 2025 19:16:35 -0700 Subject: [PATCH 06/25] WIP - broken tool message progress --- core/llm/constructMessages.ts | 51 ++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 5a3967361..eb33cb413 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,4 +1,5 @@ import { + AssistantChatMessage, ChatHistoryItem, ChatMessage, ContextItemWithId, @@ -13,7 +14,7 @@ import { normalizeToMessageParts, renderContextItems, } from "../util/messageContent"; -import { isUserOrToolMsg } from "./messages"; +import { chatMessageIsEmpty, isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; import { RulePolicies } from "./rules/types"; @@ -118,28 +119,17 @@ export function constructMessages( ): ChatMessage[] { const validTools = new Set(tools.map((tool) => tool.function.name)); - const filteredHistory = history.filter( - (item) => item.message.role !== "system", - ); const msgs: ChatMessage[] = []; - - for (const item of filteredHistory) { - if (item.message.role === "tool") { - continue; // Tool messages will be re-inserted + for (const item of history) { + if ( + item.message.role === "system" || + item.message.role === "tool" || + chatMessageIsEmpty(item.message) + ) { + continue; + // Tool messages will be re-inserted } - // This was implemented for APIs that require all tool calls to have - // A corresponsing tool sent, which means if a user excluded a tool - // Then sessions with that tool call in the history would fail - // if (messageMode === "chat") { - // const toolMessage: ToolResultChatMessage = - // historyItem.message as ToolResultChatMessage; - // if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { - // // remove all tool calls from the history - // continue; - // } - // } - if (item.message.role === "user") { // Gather context items for user messages let content = normalizeToMessageParts(item.message); @@ -171,13 +161,26 @@ export function constructMessages( validTools.has(toolCall.function.name), ); - // Case where no valid tool calls or content are present - msgs.push({ + const msgWithValidToolCalls: AssistantChatMessage = { ...item.message, toolCalls: validToolCalls, - }); + }; - // Then push a tool message for each valid tool call + if (chatMessageIsEmpty(msgWithValidToolCalls)) { + msgs.push({ + role: "assistant", + content: "Message redacted", // TODO this might be confusing, edge case situation where tools are excluded + }); + } + + // This was implemented for APIs that require all tool calls to have + // A corresponsing tool sent, which means if a user excluded a tool + // Then sessions with that tool call in the history would fail + + // Case where no valid tool calls or content are present + msgs.push(msgWithValidToolCalls); + + // Add a tool message for each valid tool call if (validToolCalls?.length) { // If the assistant message has tool calls, we need to insert tool messages for (const toolCall of validToolCalls) { From bebc8bc71e20b2a231ef30c4cb8ff2c52394f566 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 11:15:48 -0700 Subject: [PATCH 07/25] construct message: tool messages --- core/edit/streamDiffLines.ts | 4 +- core/llm/constructMessages.ts | 104 +++++++++--------- core/llm/rules/getSystemMessageWithRules.ts | 20 ++-- gui/src/redux/slices/sessionSlice.ts | 24 +++- gui/src/redux/thunks/streamNormalInput.ts | 41 +++++-- gui/src/redux/thunks/streamResponse.ts | 57 +--------- .../thunks/streamResponseAfterToolCall.ts | 49 +-------- gui/src/redux/util/index.ts | 11 ++ gui/src/util/index.ts | 52 --------- 9 files changed, 138 insertions(+), 224 deletions(-) diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index f64448f36..daa1b6c35 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -112,7 +112,7 @@ export async function* streamDiffLines({ // If any rules are present this will result in using chat instead of legacy completion const systemMessage = rulesToInclude ? getSystemMessageWithRules({ - rules: rulesToInclude, + availableRules: rulesToInclude, userMessage: typeof prompt === "string" ? ({ @@ -125,7 +125,7 @@ export async function* streamDiffLines({ ) as UserChatMessage | ToolResultChatMessage | undefined), baseSystemMessage: undefined, contextItems: [], - }) + }).systemMessage : undefined; if (systemMessage) { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index eb33cb413..4cb7673bf 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -2,19 +2,19 @@ import { AssistantChatMessage, ChatHistoryItem, ChatMessage, - ContextItemWithId, + ModelDescription, RuleWithSource, TextMessagePart, Tool, ToolResultChatMessage, UserChatMessage, } from "../"; -import { findLast } from "../util/findLast"; +import { findLastIndex } from "../util/findLast"; import { normalizeToMessageParts, renderContextItems, } from "../util/messageContent"; -import { chatMessageIsEmpty, isUserOrToolMsg } from "./messages"; +import { chatMessageIsEmpty } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; import { RulePolicies } from "./rules/types"; @@ -84,50 +84,30 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ ${EDIT_MESSAGE} `; -/** - * Helper function to get the context items for a user message - */ -function getUserContextItems( - userMsg: UserChatMessage | ToolResultChatMessage | undefined, - history: ChatHistoryItem[], -): ContextItemWithId[] { - if (!userMsg) return []; - - // Find the history item that contains the userMsg - const historyItem = history.find((item) => { - // Check if the message ID matches - if ("id" in userMsg && "id" in item.message) { - return (item.message as any).id === (userMsg as any).id; - } - // Fallback to content comparison - return ( - item.message.content === userMsg.content && - item.message.role === userMsg.role - ); - }); - - return historyItem?.contextItems || []; -} - export function constructMessages( messageMode: string, history: ChatHistoryItem[], - baseChatOrAgentSystemMessage: string | undefined, - rules: RuleWithSource[], + model: ModelDescription, + availableRules: RuleWithSource[], + rulePolicies: RulePolicies, tools: Tool[], - rulePolicies?: RulePolicies, -): ChatMessage[] { +): { + messages: ChatMessage[]; + appliedRulesIndex: number; + appliedRules: RuleWithSource[]; +} { + const historyCopy = [...history]; const validTools = new Set(tools.map((tool) => tool.function.name)); const msgs: ChatMessage[] = []; - for (const item of history) { + for (const item of historyCopy) { if ( item.message.role === "system" || item.message.role === "tool" || chatMessageIsEmpty(item.message) ) { - continue; // Tool messages will be re-inserted + continue; } if (item.message.role === "user") { @@ -169,7 +149,7 @@ export function constructMessages( if (chatMessageIsEmpty(msgWithValidToolCalls)) { msgs.push({ role: "assistant", - content: "Message redacted", // TODO this might be confusing, edge case situation where tools are excluded + content: "Tool call message redacted in chat mode", // TODO this might be confusing, edge case situation where tools are excluded }); } @@ -202,21 +182,41 @@ export function constructMessages( } } - const lastUserMsg = findLast(msgs, isUserOrToolMsg) as - | UserChatMessage - | ToolResultChatMessage - | undefined; - - // Get context items for the last user message - const lastUserContextItems = getUserContextItems( - lastUserMsg, - filteredHistory, + const lastUserMsgIndex = findLastIndex( + historyCopy, + (item) => item.message.role === "user", ); - const systemMessage = getSystemMessageWithRules({ + const lastUserOrToolMsgIndex = findLastIndex( + historyCopy, + (item) => item.message.role === "user" || item.message.role === "tool", + ); + const lastUserOrToolMsg = historyCopy[lastUserOrToolMsgIndex]?.message as + | UserChatMessage + | ToolResultChatMessage; + const itemsBackToLastUserMessage = history + .slice(lastUserMsgIndex, historyCopy.length) + .filter( + (item) => item.message.role === "tool" || item.message.role === "user", + ); + const rulesContextItems = itemsBackToLastUserMessage + .map((item) => item.contextItems) + .flat(); + + // Get system message + let baseChatOrAgentSystemMessage: string | undefined; + if (messageMode === "agent") { + baseChatOrAgentSystemMessage = + model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; + } else { + baseChatOrAgentSystemMessage = + model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; + } + + const { systemMessage } = getSystemMessageWithRules({ baseSystemMessage: baseChatOrAgentSystemMessage, - rules, - userMessage: lastUserMsg, - contextItems: lastUserContextItems, + availableRules, + userMessage: lastUserOrToolMsg, + contextItems: rulesContextItems, rulePolicies, }); @@ -227,9 +227,13 @@ export function constructMessages( }); } - // Remove the "id" from all of the messages - return msgs.map((msg) => { + const messages = msgs.map((msg) => { const { id, ...rest } = msg as any; return rest; }); + return { + messages, + appliedRulesIndex: lastUserOrToolMsgIndex, + appliedRules: availableRules, + }; } diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index c005a5f92..5b7eb4865 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -327,27 +327,33 @@ export const getApplicableRules = ( export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, - rules, + availableRules, contextItems, rulePolicies = {}, }: { baseSystemMessage?: string; userMessage: UserChatMessage | ToolResultChatMessage | undefined; - rules: RuleWithSource[]; + availableRules: RuleWithSource[]; contextItems: ContextItemWithId[]; rulePolicies?: RulePolicies; -}) => { - const applicableRules = getApplicableRules( +}): { + systemMessage: string; + appliedRules: RuleWithSource[]; +} => { + const appliedRules = getApplicableRules( userMessage, - rules, + availableRules, contextItems, rulePolicies, ); let systemMessage = baseSystemMessage ?? ""; - for (const rule of applicableRules) { + for (const rule of appliedRules) { systemMessage += `\n\n${rule.rule}`; } - return systemMessage; + return { + systemMessage, + appliedRules, + }; }; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 339369cd9..1a0ceb5c9 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -20,13 +20,16 @@ import { SessionMetadata, } from "core"; import { NEW_SESSION_TITLE } from "core/util/constants"; -import { renderChatMessage } from "core/util/messageContent"; +import { + renderChatMessage, + renderContextItems, +} from "core/util/messageContent"; import { findUriInDirs, getUriPathBasename } from "core/util/uri"; import { v4 as uuidv4 } from "uuid"; import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; -import { findCurrentToolCall, findToolCall } from "../util"; +import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -547,6 +550,7 @@ export const sessionSlice = createSlice({ contextItems: ContextItem[]; }>, ) => { + // Update tool call state and corresponding tool output message const toolCallState = findToolCall( state.history, action.payload.toolCallId, @@ -554,6 +558,22 @@ export const sessionSlice = createSlice({ if (toolCallState) { toolCallState.output = action.payload.contextItems; } + const toolItem = findToolOutput(state.history, action.payload.toolCallId); + if (toolItem) { + toolItem.message.content = renderContextItems( + action.payload.contextItems, + ); + } + // addContextItemsAtIndex({ + // index: initialHistory.length, + // contextItems: toolOutput.map((contextItem) => ({ + // ...contextItem, + // id: { + // providerTitle: "toolCall", + // itemId: toolCallId, + // }, + // })), + // }), }, cancelToolCall: ( state, diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 292c973f9..8eb319cc8 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,6 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ChatMessage, LLMFullCompletionOptions } from "core"; +import { LLMFullCompletionOptions } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; +import { constructMessages } from "core/llm/constructMessages"; import { ToCoreProtocol } from "core/protocol"; import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; @@ -9,6 +10,7 @@ import { abortStream, addPromptCompletionPair, setActive, + setAppliedRulesAtIndex, setInactive, setToolGenerated, streamUpdate, @@ -19,28 +21,30 @@ import { callCurrentTool } from "./callCurrentTool"; export const streamNormalInput = createAsyncThunk< void, { - messages: ChatMessage[]; legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"]; }, ThunkApiType >( "chat/streamNormalInput", - async ( - { messages, legacySlashCommandData }, - { dispatch, extra, getState }, - ) => { - // Gather state + async ({ legacySlashCommandData }, { dispatch, extra, getState }) => { const state = getState(); const selectedChatModel = selectSelectedChatModel(state); - const streamAborter = state.session.streamAborter; if (!selectedChatModel) { - throw new Error("Default model not defined"); + throw new Error("No chat model selected"); } - let completionOptions: LLMFullCompletionOptions = {}; + const chatHistory = state.session.history; + const messageMode = state.session.mode; + const rulePolicies = state.ui.ruleSettings; + const streamAborter = state.session.streamAborter; + + // Get tools const activeTools = selectActiveTools(state); const toolsSupported = modelSupportsTools(selectedChatModel); + + // Construct completion options + let completionOptions: LLMFullCompletionOptions = {}; if (toolsSupported && activeTools.length > 0) { completionOptions = { tools: activeTools, @@ -55,6 +59,23 @@ export const streamNormalInput = createAsyncThunk< }; } + // Construct messages + const { messages, appliedRules, appliedRulesIndex } = constructMessages( + messageMode, + chatHistory, + selectedChatModel, + state.config.config.rules, + rulePolicies, + toolsSupported ? activeTools : [], + ); + + dispatch( + setAppliedRulesAtIndex({ + index: appliedRulesIndex, + appliedRules: appliedRules, + }), + ); + dispatch(setActive()); // Send request diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index f7334df2b..11763a462 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,17 +1,11 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; -import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; -import { constructMessages } from "core/llm/constructMessages"; -import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules"; +import { InputModifiers } from "core"; import posthog from "posthog-js"; import { v4 as uuidv4 } from "uuid"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; -import { getBaseSystemMessage } from "../../util"; -import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectSelectedChatModel } from "../slices/configSlice"; import { - setAppliedRulesAtIndex, submitEditorAndInitAtIndex, updateHistoryItemAtIndex, } from "../slices/sessionSlice"; @@ -79,7 +73,7 @@ export const streamResponseThunk = createAsyncThunk< .map((item) => item.uri!.value), ...selectedCode.map((rif) => rif.filepath), ]; - dispatch(updateFileSymbolsFromFiles(filesForSymbols)); + void dispatch(updateFileSymbolsFromFiles(filesForSymbols)); dispatch( updateHistoryItemAtIndex({ @@ -95,52 +89,6 @@ export const streamResponseThunk = createAsyncThunk< }), ); - // Get updated history after the update - const updatedHistory = getState().session.history; - - // Determine which rules apply to this message - const userMsg = updatedHistory[inputIndex].message; - const rules = getState().config.config.rules; - const rulePolicies = getState().ui.ruleSettings; - - // Calculate applicable rules once - // We need to check the message type to match what getApplicableRules expects - const applicableRules = getApplicableRules( - userMsg.role === "user" || userMsg.role === "tool" - ? (userMsg as UserChatMessage | ToolResultChatMessage) - : undefined, - rules, - selectedContextItems, - rulePolicies, - ); - - // Store in history for UI display - dispatch( - setAppliedRulesAtIndex({ - index: inputIndex, - appliedRules: applicableRules, - }), - ); - - const messageMode = getState().session.mode; - const baseChatOrAgentSystemMessage = getBaseSystemMessage( - selectedChatModel, - messageMode, - ); - - const activeTools = selectActiveTools(state); - const toolsSupported = modelSupportsTools(selectedChatModel); - const availableTools = toolsSupported ? activeTools : []; - - const messages = constructMessages( - messageMode, - [...updatedHistory], - baseChatOrAgentSystemMessage, - applicableRules, - availableTools, - rulePolicies, - ); - posthog.capture("step run", { step_name: "User Input", params: {}, @@ -157,7 +105,6 @@ export const streamResponseThunk = createAsyncThunk< unwrapResult( await dispatch( streamNormalInput({ - messages, legacySlashCommandData: legacyCommandWithInput ? { command: legacyCommandWithInput.command, diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 75134b951..8caf6625a 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,12 +1,7 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { ChatMessage } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; -import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; -import { getBaseSystemMessage } from "../../util"; -import { selectActiveTools } from "../selectors/selectActiveTools"; -import { selectSelectedChatModel } from "../slices/configSlice"; -import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice"; +import { streamUpdate } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { findToolCall } from "../util"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; @@ -23,15 +18,8 @@ export const streamResponseAfterToolCall = createAsyncThunk< await dispatch( streamThunkWrapper(async () => { const state = getState(); - const initialHistory = state.session.history; - const selectedChatModel = selectSelectedChatModel(state); - - if (!selectedChatModel) { - throw new Error("No model selected"); - } const toolCallState = findToolCall(state.session.history, toolCallId); - if (!toolCallState) { return; // in cases where edit tool is cancelled mid apply, this will be triggered } @@ -42,46 +30,15 @@ export const streamResponseAfterToolCall = createAsyncThunk< await new Promise((resolve) => setTimeout(resolve, 0)); + // TODO paralell tool calls - dispatch one tool message per tool call const newMessage: ChatMessage = { role: "tool", content: renderContextItems(toolOutput), toolCallId, }; dispatch(streamUpdate([newMessage])); - dispatch( - addContextItemsAtIndex({ - index: initialHistory.length, - contextItems: toolOutput.map((contextItem) => ({ - ...contextItem, - id: { - providerTitle: "toolCall", - itemId: toolCallId, - }, - })), - }), - ); - const updatedHistory = getState().session.history; - const messageMode = getState().session.mode; - - const baseChatOrAgentSystemMessage = getBaseSystemMessage( - selectedChatModel, - messageMode, - ); - - const activeTools = selectActiveTools(state); - const toolsSupported = modelSupportsTools(selectedChatModel); - const availableTools = toolsSupported ? activeTools : []; - - const messages = constructMessages( - messageMode, - [...updatedHistory], - baseChatOrAgentSystemMessage, - state.config.config.rules, - availableTools, - ); - - unwrapResult(await dispatch(streamNormalInput({ messages }))); + unwrapResult(await dispatch(streamNormalInput({}))); }), ); }, diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index eab18ae60..fb0f96c00 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -1,4 +1,5 @@ import { ToolCallState } from "core"; +import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice"; import { RootState } from "../store"; export function findCurrentToolCall( @@ -15,3 +16,13 @@ export function findToolCall( (item) => item.toolCallState?.toolCallId === toolCallId, )?.toolCallState; } + +export function findToolOutput( + chatHistory: RootState["session"]["history"], + toolCallId: string, +): ChatHistoryItemWithMessageId | undefined { + return chatHistory.find( + (item) => + item.message.role === "tool" && item.message.toolCallId === toolCallId, + ); +} diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index dc581b51b..d4cc451f4 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -1,10 +1,4 @@ -import { MessageModes, ModelDescription } from "core"; import { ProfileDescription } from "core/config/ProfileLifecycleManager"; -import { - DEFAULT_AGENT_SYSTEM_MESSAGE, - DEFAULT_CHAT_SYSTEM_MESSAGE, -} from "core/llm/constructMessages"; -import _ from "lodash"; import { KeyboardEvent as ReactKeyboardEvent } from "react"; import { getLocalStorage } from "./localStorage"; @@ -88,52 +82,6 @@ export function isPrerelease() { return false; } -/** - * Updates the values of an object's properties based on the specified paths. - * - * This function creates a deep clone of the provided object and updates its properties - * based on the given path-to-value mappings. If a value in the mapping is a function, - * it will be used to determine the new value for the property. Otherwise, the value itself - * will be set for the property. - * - * @param {Object} old - The original object to be cloned and updated. - * @param {Object} pathToValue - An object where the keys represent the paths to the properties - * to be updated and the values represent the new values or functions - * to determine the new values. - * @returns {Object} A new object with the updated values. - */ -export function updatedObj(old: any, pathToValue: { [key: string]: any }) { - const newObject = _.cloneDeep(old); - - for (const key in pathToValue) { - if (typeof pathToValue[key] === "function") { - _.updateWith(newObject, key, pathToValue[key]); - } else { - _.updateWith(newObject, key, (__) => pathToValue[key]); - } - } - - return newObject; -} - export function isLocalProfile(profile: ProfileDescription): boolean { return profile.profileType === "local"; } - -/** - * Get the base system message for the agent or chat mode from the model description. - */ -export function getBaseSystemMessage( - modelDetails: ModelDescription | null, - mode: MessageModes, -) { - let baseChatOrAgentSystemMessage: string | undefined; - if (mode === "agent") { - baseChatOrAgentSystemMessage = - modelDetails?.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; - } else { - baseChatOrAgentSystemMessage = - modelDetails?.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; - } - return baseChatOrAgentSystemMessage; -} From 744f2297d1682798814d0b1d92c788ac2a45d252 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 11:34:28 -0700 Subject: [PATCH 08/25] clear dangling messages logic --- .../Lump/LumpToolbar/LumpToolbar.tsx | 8 ++- .../LumpToolbar/PendingToolCallToolbar.tsx | 18 +++++-- gui/src/redux/slices/sessionSlice.ts | 37 ++++++++++---- gui/src/redux/thunks/cancelCurrentToolCall.ts | 50 ------------------- gui/src/redux/thunks/cancelStream.ts | 8 ++- 5 files changed, 51 insertions(+), 70 deletions(-) delete mode 100644 gui/src/redux/thunks/cancelCurrentToolCall.ts diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index 02027865e..510366448 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -2,8 +2,8 @@ import { useEffect } from "react"; import { useSelector } from "react-redux"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; +import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; -import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; import { isJetBrains } from "../../../../util"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; import { EditOutcomeToolbar } from "./EditOutcomeToolbar"; @@ -50,7 +50,11 @@ export function LumpToolbar() { } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") { event.preventDefault(); event.stopPropagation(); - void dispatch(cancelCurrentToolCall()); + void dispatch( + cancelToolCall({ + toolCallId: toolCallState.toolCallId, + }), + ); } }; diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx index 365898dce..3cb6acc2d 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx @@ -1,7 +1,8 @@ import styled from "styled-components"; -import { useAppDispatch } from "../../../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; +import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall"; +import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool"; -import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall"; import { getAltKeyLabel, getFontSize, @@ -27,6 +28,7 @@ const StopButton = styled.div` export function PendingToolCallToolbar() { const dispatch = useAppDispatch(); const jetbrains = isJetBrains(); + const currentToolCall = useAppSelector(selectCurrentToolCall); return ( @@ -37,7 +39,17 @@ export function PendingToolCallToolbar() {
dispatch(cancelCurrentToolCall())} + onClick={ + currentToolCall + ? () => { + dispatch( + cancelToolCall({ + toolCallId: currentToolCall.toolCallId, + }), + ); + } + : undefined + } data-testid="reject-tool-call-button" > {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 1a0ceb5c9..ee8e153a2 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -25,6 +25,7 @@ import { renderContextItems, } from "core/util/messageContent"; import { findUriInDirs, getUriPathBasename } from "core/util/uri"; +import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; @@ -108,19 +109,35 @@ export const sessionSlice = createSlice({ curMessage.isGatheringContext = payload; } }, - clearLastEmptyResponse: (state) => { + clearDanglingMessages: (state) => { + // This is used during cancellation + // After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing. + // The only thing allowed after the last assistant message that has either content or generated tool calls + // is a user or tool message if (state.history.length < 2) { return; } - const lastMessage = state.history[state.history.length - 1]; + const lastUserOrToolIdx = findLastIndex( + state.history, + (item) => item.message.role === "tool" || item.message.role === "user", + ); - // Only clear in the case of an empty message - if (!lastMessage.message.content.length) { - state.mainEditorContentTrigger = - state.history[state.history.length - 2].editorState; - state.history = state.history.slice(0, -2); - // TODO is this logic correct for tool use conversations? - // Maybe slice at last index of "user" role message? + let validAssistantMessageIdx = -1; + for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) { + const message = state.history[i]; + if ( + message.message.content || + message.toolCallState?.status === "generated" + ) { + validAssistantMessageIdx = i; + break; + } + } + + if (validAssistantMessageIdx === -1) { + state.history = state.history.slice(0, lastUserOrToolIdx + 1); + } else { + state.history = state.history.slice(0, validAssistantMessageIdx + 1); } }, // Trigger value picked up by editor with isMainInput to set its content @@ -720,7 +737,7 @@ export const { submitEditorAndInitAtIndex, truncateHistoryToMessage, updateHistoryItemAtIndex, - clearLastEmptyResponse, + clearDanglingMessages, setMainEditorContentTrigger, deleteMessage, setIsGatheringContext, diff --git a/gui/src/redux/thunks/cancelCurrentToolCall.ts b/gui/src/redux/thunks/cancelCurrentToolCall.ts deleted file mode 100644 index f90d80ff6..000000000 --- a/gui/src/redux/thunks/cancelCurrentToolCall.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; -import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; - -export const cancelCurrentToolCall = createAsyncThunk< - void, - undefined, - ThunkApiType ->("chat/cancelTool", async (_, { dispatch, extra, getState }) => { - const state = getState(); - const toolCallState = selectCurrentToolCall(state); - - if (!toolCallState) { - return; - } - - if (toolCallState.status !== "generated") { - return; - } - - const { toolCallId } = toolCallState; - dispatch( - cancelToolCall({ - toolCallId, - }), - ); - - dispatch( - updateToolCallOutput({ - toolCallId, - contextItems: [ - { - name: "Tool Cancelled", - description: "Tool Cancelled", - content: - "The tool call was cancelled by the user. Please try something else or request further instructions.", - hidden: true, - }, - ], - }), - ); - const output = await dispatch( - streamResponseAfterToolCall({ - toolCallId, - }), - ); - unwrapResult(output); -}); diff --git a/gui/src/redux/thunks/cancelStream.ts b/gui/src/redux/thunks/cancelStream.ts index 515a02cfc..4cac7e9c7 100644 --- a/gui/src/redux/thunks/cancelStream.ts +++ b/gui/src/redux/thunks/cancelStream.ts @@ -1,7 +1,7 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { abortStream, - clearLastEmptyResponse, + clearDanglingMessages, setInactive, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -12,9 +12,7 @@ export const cancelStream = createAsyncThunk( dispatch(setInactive()); dispatch(abortStream()); - // In the case tool calls were being generated, - // Replace them with - // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box - dispatch(clearLastEmptyResponse()); + // Clear any dangling incomplete tool calls, thinking messages, etc. + dispatch(clearDanglingMessages()); }, ); From 089808f1630038aa0d0b994b6b2600d4970f347d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:05:55 -0700 Subject: [PATCH 09/25] move construct messages to GUI side, fix duplicate tool calls bug --- core/config/util.ts | 2 +- core/llm/llms/index.ts | 2 +- core/tsconfig.json | 7 +- .../ToolCallDiv/toolCallStateToContextItem.ts | 5 +- gui/src/redux/slices/sessionSlice.ts | 3 +- gui/src/redux/thunks/streamNormalInput.ts | 6 +- .../src/redux/util}/constructMessages.ts | 86 +++++++++++-------- 7 files changed, 71 insertions(+), 40 deletions(-) rename {core/llm => gui/src/redux/util}/constructMessages.ts (75%) diff --git a/core/config/util.ts b/core/config/util.ts index 9128fc0b5..5cb2f6c3a 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -10,7 +10,7 @@ import { JSONModelDescription, PromptTemplate, } from "../"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../../gui/src/redux/util/constructMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 74c58e9da..1737780af 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -7,8 +7,8 @@ import { JSONModelDescription, LLMOptions, } from "../.."; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../../../gui/src/redux/util/constructMessages"; import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Asksage from "./Asksage"; diff --git a/core/tsconfig.json b/core/tsconfig.json index 69966e2de..273476b9d 100644 --- a/core/tsconfig.json +++ b/core/tsconfig.json @@ -18,6 +18,11 @@ "noEmitOnError": false, "types": ["jest", "node"] }, - "include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"], + "include": [ + "./**/*.ts", + "./**/*.js", + "./**/*.d.ts", + "../gui/src/redux/util/constructMessages.ts" + ], "exclude": ["dist"] } diff --git a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts index ccb8a7976..7a25ead3a 100644 --- a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts +++ b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts @@ -1,8 +1,11 @@ import { ContextItemWithId, ToolCallState } from "core"; export function toolCallStateToContextItems( - toolCallState: ToolCallState, + toolCallState: ToolCallState | undefined, ): ContextItemWithId[] { + if (!toolCallState) { + return []; + } return ( toolCallState.output?.map((item) => ({ ...item, diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index ee8e153a2..20ea7ca86 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -34,8 +34,9 @@ import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. +export type ChatMessageWithId = ChatMessage & { id: string }; export type ChatHistoryItemWithMessageId = ChatHistoryItem & { - message: ChatMessage & { id: string }; + message: ChatMessageWithId; }; type SessionState = { diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 8eb319cc8..f07a11376 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -60,9 +60,13 @@ export const streamNormalInput = createAsyncThunk< } // Construct messages + const withoutMessageIds = chatHistory.map((item) => { + const { id, ...messageWithoutId } = item.message; + return { ...item, message: messageWithoutId }; + }); const { messages, appliedRules, appliedRulesIndex } = constructMessages( messageMode, - chatHistory, + withoutMessageIds, selectedChatModel, state.config.config.rules, rulePolicies, diff --git a/core/llm/constructMessages.ts b/gui/src/redux/util/constructMessages.ts similarity index 75% rename from core/llm/constructMessages.ts rename to gui/src/redux/util/constructMessages.ts index 4cb7673bf..ec0fc3cfa 100644 --- a/core/llm/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -2,27 +2,29 @@ import { AssistantChatMessage, ChatHistoryItem, ChatMessage, + ContextItemWithId, ModelDescription, RuleWithSource, TextMessagePart, Tool, ToolResultChatMessage, UserChatMessage, -} from "../"; -import { findLastIndex } from "../util/findLast"; +} from "core"; +import { chatMessageIsEmpty } from "core/llm/messages"; +import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; +import { RulePolicies } from "core/llm/rules/types"; +import { findLastIndex } from "core/util/findLast"; import { normalizeToMessageParts, renderContextItems, -} from "../util/messageContent"; -import { chatMessageIsEmpty } from "./messages"; -import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; -import { RulePolicies } from "./rules/types"; +} from "core/util/messageContent"; +import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; + "https://github.com/continuedev/continue/blob/main/gui/src/redux/util/constructMessages.ts"; export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; + "https://github.com/continuedev/continue/blob/main/gui/src/redux/util/constructMessages.ts"; const EDIT_MESSAGE = `\ Always include the language and file name in the info string when you write code blocks. @@ -99,7 +101,10 @@ export function constructMessages( const historyCopy = [...history]; const validTools = new Set(tools.map((tool) => tool.function.name)); - const msgs: ChatMessage[] = []; + const msgs: { + ctxItems: ContextItemWithId[]; + message: ChatMessage; + }[] = []; for (const item of historyCopy) { if ( item.message.role === "system" || @@ -125,14 +130,18 @@ export function constructMessages( content = [...ctxItems, ...content]; msgs.push({ - ...item.message, - content, + ctxItems: item.contextItems, + message: { + ...item.message, + content, + }, }); - } else { - msgs.push(item.message); - } - - if (item.message.role === "assistant") { + } else if (item.message.role === "thinking") { + msgs.push({ + ctxItems: item.contextItems, + message: item.message, + }); + } else if (item.message.role === "assistant") { // First, push a version of the message with any valid tools calls const validToolCalls = item.message.toolCalls?.filter( (toolCall) => @@ -148,8 +157,11 @@ export function constructMessages( if (chatMessageIsEmpty(msgWithValidToolCalls)) { msgs.push({ - role: "assistant", - content: "Tool call message redacted in chat mode", // TODO this might be confusing, edge case situation where tools are excluded + ctxItems: [], + message: { + role: "assistant", + content: "Tool call message redacted in chat mode", // TODO this might be confusing, edge case situation where tools are excluded + }, }); } @@ -158,7 +170,10 @@ export function constructMessages( // Then sessions with that tool call in the history would fail // Case where no valid tool calls or content are present - msgs.push(msgWithValidToolCalls); + msgs.push({ + ctxItems: item.contextItems, + message: msgWithValidToolCalls, + }); // Add a tool message for each valid tool call if (validToolCalls?.length) { @@ -173,9 +188,12 @@ export function constructMessages( content = renderContextItems(item.toolCallState.output); } msgs.push({ - role: "tool", - content, - toolCallId: toolCall.id!, + ctxItems: toolCallStateToContextItems(item.toolCallState), + message: { + role: "tool", + content, + toolCallId: toolCall.id!, + }, }); } } @@ -183,23 +201,23 @@ export function constructMessages( } const lastUserMsgIndex = findLastIndex( - historyCopy, + msgs, (item) => item.message.role === "user", ); const lastUserOrToolMsgIndex = findLastIndex( - historyCopy, + msgs, (item) => item.message.role === "user" || item.message.role === "tool", ); - const lastUserOrToolMsg = historyCopy[lastUserOrToolMsgIndex]?.message as + const lastUserOrToolMsg = msgs[lastUserOrToolMsgIndex]?.message as | UserChatMessage | ToolResultChatMessage; - const itemsBackToLastUserMessage = history - .slice(lastUserMsgIndex, historyCopy.length) + const itemsBackToLastUserMessage = msgs + .slice(lastUserMsgIndex, msgs.length) .filter( (item) => item.message.role === "tool" || item.message.role === "user", ); const rulesContextItems = itemsBackToLastUserMessage - .map((item) => item.contextItems) + .map((item) => item.ctxItems) .flat(); // Get system message @@ -222,15 +240,15 @@ export function constructMessages( if (systemMessage.trim()) { msgs.unshift({ - role: "system", - content: systemMessage, + ctxItems: [], + message: { + role: "system", + content: systemMessage, + }, }); } - const messages = msgs.map((msg) => { - const { id, ...rest } = msg as any; - return rest; - }); + const messages = msgs.map((m) => m.message); return { messages, appliedRulesIndex: lastUserOrToolMsgIndex, From c69521fb95a9a7b8a560e34e6585308342fc281f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:14:20 -0700 Subject: [PATCH 10/25] specific file for default system messages --- core/llm/defaultSystemMessages.ts | 65 +++++++++++++++++ .../mainInput/Lump/sections/RulesSection.tsx | 2 +- gui/src/redux/thunks/streamNormalInput.ts | 2 +- gui/src/redux/util/constructMessages.ts | 70 ++----------------- 4 files changed, 71 insertions(+), 68 deletions(-) create mode 100644 core/llm/defaultSystemMessages.ts diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts new file mode 100644 index 000000000..64ea23dd0 --- /dev/null +++ b/core/llm/defaultSystemMessages.ts @@ -0,0 +1,65 @@ +export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; + +export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = + "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; + +const EDIT_MESSAGE = `\ + Always include the language and file name in the info string when you write code blocks. + If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' + + When addressing code modification requests, present a concise code snippet that + emphasizes only the necessary changes and uses abbreviated placeholders for + unmodified sections. For example: + + \`\`\`language /path/to/file + // ... existing code ... + + {{ modified code here }} + + // ... existing code ... + + {{ another modification }} + + // ... rest of code ... + \`\`\` + + In existing files, you should always restate the function or class that the snippet belongs to: + + \`\`\`language /path/to/file + // ... existing code ... + + function exampleFunction() { + // ... existing code ... + + {{ modified code here }} + + // ... rest of function ... + } + + // ... rest of code ... + \`\`\` + + Since users have access to their complete file, they prefer reading only the + relevant modifications. It's perfectly acceptable to omit unmodified portions + at the beginning, middle, or end of files using these "lazy" comments. Only + provide the complete file when explicitly requested. Include a concise explanation + of changes unless the user specifically asks for code only. +`; + +export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ + + You are in chat mode. + + If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. + If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. + +${EDIT_MESSAGE} +`; + +export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ + + You are in agent mode. + +${EDIT_MESSAGE} +`; diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 1097805d2..761973428 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -10,7 +10,7 @@ import { DEFAULT_AGENT_SYSTEM_MESSAGE_URL, DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE_URL, -} from "core/llm/constructMessages"; +} from "core/llm/defaultSystemMessages"; import { useContext, useMemo } from "react"; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index f07a11376..aa1744ed4 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,7 +1,6 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { LLMFullCompletionOptions } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; -import { constructMessages } from "core/llm/constructMessages"; import { ToCoreProtocol } from "core/protocol"; import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; @@ -16,6 +15,7 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; +import { constructMessages } from "../util/constructMessages"; import { callCurrentTool } from "./callCurrentTool"; export const streamNormalInput = createAsyncThunk< diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index ec0fc3cfa..f1163a3be 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -10,6 +10,10 @@ import { ToolResultChatMessage, UserChatMessage, } from "core"; +import { + DEFAULT_AGENT_SYSTEM_MESSAGE, + DEFAULT_CHAT_SYSTEM_MESSAGE, +} from "core/llm/defaultSystemMessages"; import { chatMessageIsEmpty } from "core/llm/messages"; import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; import { RulePolicies } from "core/llm/rules/types"; @@ -20,72 +24,6 @@ import { } from "core/util/messageContent"; import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; -export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/gui/src/redux/util/constructMessages.ts"; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/gui/src/redux/util/constructMessages.ts"; - -const EDIT_MESSAGE = `\ - Always include the language and file name in the info string when you write code blocks. - If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' - - When addressing code modification requests, present a concise code snippet that - emphasizes only the necessary changes and uses abbreviated placeholders for - unmodified sections. For example: - - \`\`\`language /path/to/file - // ... existing code ... - - {{ modified code here }} - - // ... existing code ... - - {{ another modification }} - - // ... rest of code ... - \`\`\` - - In existing files, you should always restate the function or class that the snippet belongs to: - - \`\`\`language /path/to/file - // ... existing code ... - - function exampleFunction() { - // ... existing code ... - - {{ modified code here }} - - // ... rest of function ... - } - - // ... rest of code ... - \`\`\` - - Since users have access to their complete file, they prefer reading only the - relevant modifications. It's perfectly acceptable to omit unmodified portions - at the beginning, middle, or end of files using these "lazy" comments. Only - provide the complete file when explicitly requested. Include a concise explanation - of changes unless the user specifically asks for code only. -`; - -export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ - - You are in chat mode. - - If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. - If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. - -${EDIT_MESSAGE} -`; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ - - You are in agent mode. - -${EDIT_MESSAGE} -`; - export function constructMessages( messageMode: string, history: ChatHistoryItem[], From aa962b1fa610bda612cb7652fc669e343c4d041c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:15:27 -0700 Subject: [PATCH 11/25] fix broken imports --- core/config/util.ts | 2 +- core/llm/llms/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/config/util.ts b/core/config/util.ts index 5cb2f6c3a..a53027a76 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -10,7 +10,7 @@ import { JSONModelDescription, PromptTemplate, } from "../"; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../../gui/src/redux/util/constructMessages"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 1737780af..318e4e88f 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -7,8 +7,8 @@ import { JSONModelDescription, LLMOptions, } from "../.."; -import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../../../gui/src/redux/util/constructMessages"; import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Asksage from "./Asksage"; From fa1253bae54fd69c9dbe0b7ef50671dafaf7fea1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:28:02 -0700 Subject: [PATCH 12/25] agent papercuts + tool message updates - cleanup --- core/tsconfig.json | 7 +------ .../mainInput/belowMainInput/ContextItemsPeek.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 2 +- gui/src/redux/slices/sessionSlice.ts | 3 +-- gui/src/redux/thunks/streamResponseAfterToolCall.ts | 2 +- 5 files changed, 5 insertions(+), 11 deletions(-) diff --git a/core/tsconfig.json b/core/tsconfig.json index 273476b9d..69966e2de 100644 --- a/core/tsconfig.json +++ b/core/tsconfig.json @@ -18,11 +18,6 @@ "noEmitOnError": false, "types": ["jest", "node"] }, - "include": [ - "./**/*.ts", - "./**/*.js", - "./**/*.d.ts", - "../gui/src/redux/util/constructMessages.ts" - ], + "include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"], "exclude": ["dist"] } diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 31c392bf1..a77e2fc98 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -121,7 +121,7 @@ export function ContextItemsPeekItem({ data-testid="context-items-peek-item" > {getContextItemIcon()} - + {contextItem.name}
-
+
{!!toolCallState.output && ( )} diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 20ea7ca86..ee8e153a2 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -34,9 +34,8 @@ import { findCurrentToolCall, findToolCall, findToolOutput } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. -export type ChatMessageWithId = ChatMessage & { id: string }; export type ChatHistoryItemWithMessageId = ChatHistoryItem & { - message: ChatMessageWithId; + message: ChatMessage & { id: string }; }; type SessionState = { diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 8caf6625a..010304557 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -30,7 +30,7 @@ export const streamResponseAfterToolCall = createAsyncThunk< await new Promise((resolve) => setTimeout(resolve, 0)); - // TODO paralell tool calls - dispatch one tool message per tool call + // TODO parallel tool calls - dispatch one tool message per tool call const newMessage: ChatMessage = { role: "tool", content: renderContextItems(toolOutput), From 2b022ad86d7ec59c368760f1fceb02a3afa058e3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:38:19 -0700 Subject: [PATCH 13/25] update tool message context items in redux --- .../ToolCallDiv/toolCallStateToContextItem.ts | 25 +++++++++++++------ gui/src/redux/slices/sessionSlice.ts | 14 +++-------- gui/src/redux/util/index.ts | 1 + 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts index 7a25ead3a..b3e132cad 100644 --- a/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts +++ b/gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts @@ -1,4 +1,4 @@ -import { ContextItemWithId, ToolCallState } from "core"; +import { ContextItem, ContextItemWithId, ToolCallState } from "core"; export function toolCallStateToContextItems( toolCallState: ToolCallState | undefined, @@ -7,12 +7,21 @@ export function toolCallStateToContextItems( return []; } return ( - toolCallState.output?.map((item) => ({ - ...item, - id: { - providerTitle: "toolCall", - itemId: toolCallState.toolCallId, - }, - })) ?? [] + toolCallState.output?.map((ctxItem) => + toolCallCtxItemToCtxItemWithId(ctxItem, toolCallState.toolCallId), + ) ?? [] ); } + +export function toolCallCtxItemToCtxItemWithId( + ctxItem: ContextItem, + toolCallId: string, +): ContextItemWithId { + return { + ...ctxItem, + id: { + providerTitle: "toolCall", + itemId: toolCallId, + }, + }; +} diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index ee8e153a2..14c1d1dc9 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -27,6 +27,7 @@ import { import { findUriInDirs, getUriPathBasename } from "core/util/uri"; import { findLastIndex } from "lodash"; import { v4 as uuidv4 } from "uuid"; +import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; import { addToolCallDeltaToState } from "../../util/toolCallState"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; @@ -580,17 +581,10 @@ export const sessionSlice = createSlice({ toolItem.message.content = renderContextItems( action.payload.contextItems, ); + toolItem.contextItems = action.payload.contextItems.map((item) => + toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId), + ); } - // addContextItemsAtIndex({ - // index: initialHistory.length, - // contextItems: toolOutput.map((contextItem) => ({ - // ...contextItem, - // id: { - // providerTitle: "toolCall", - // itemId: toolCallId, - // }, - // })), - // }), }, cancelToolCall: ( state, diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index fb0f96c00..825c19c09 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -8,6 +8,7 @@ export function findCurrentToolCall( return chatHistory[chatHistory.length - 1]?.toolCallState; } +// TODO parallel tool calls - find tool call must search within arrays export function findToolCall( chatHistory: RootState["session"]["history"], toolCallId: string, From 60aee4e36a4ad68a6dc458a8e60d5e7853050647 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 17:51:16 -0700 Subject: [PATCH 14/25] tweak clear dangling messages logic --- gui/src/redux/slices/sessionSlice.ts | 6 +++++- gui/src/redux/thunks/streamThunkWrapper.tsx | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 14c1d1dc9..9cc15863b 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -128,9 +128,13 @@ export const sessionSlice = createSlice({ const message = state.history[i]; if ( message.message.content || - message.toolCallState?.status === "generated" + message.toolCallState?.status !== "generating" ) { validAssistantMessageIdx = i; + // Cancel any tool calls that are dangling and generated + if (message.toolCallState?.status === "generated") { + message.toolCallState.status = "canceled"; + } break; } } diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index 2a6eb99b0..9e40f4f06 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -22,7 +22,7 @@ export const streamThunkWrapper = createAsyncThunk< ); } } catch (e) { - dispatch(cancelStream()); + await dispatch(cancelStream()); dispatch(setDialogMessage()); dispatch(setShowDialog(true)); } From fc9ef88668195a6c42edf72eff336c73ef011ca9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 18:27:02 -0700 Subject: [PATCH 15/25] merge main --- core/llm/constructMessages.ts | 187 ------------------ core/llm/defaultSystemMessages.ts | 9 +- .../belowMainInput/ContextItemsPeek.tsx | 7 +- .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 51 +---- 4 files changed, 13 insertions(+), 241 deletions(-) delete mode 100644 core/llm/constructMessages.ts diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts deleted file mode 100644 index dc9dbc8bf..000000000 --- a/core/llm/constructMessages.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { - ChatHistoryItem, - ChatMessage, - ContextItemWithId, - RuleWithSource, - TextMessagePart, - ToolResultChatMessage, - UserChatMessage, -} from "../"; -import { findLast } from "../util/findLast"; -import { normalizeToMessageParts } from "../util/messageContent"; -import { isUserOrToolMsg } from "./messages"; -import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; -import { RulePolicies } from "./rules/types"; - -export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; - -export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ - Always include the language and file name in the info string when you write code blocks. - If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' -`; - -export const EDIT_CODE_INSTRUCTIONS = `\ - When addressing code modification requests, present a concise code snippet that - emphasizes only the necessary changes and uses abbreviated placeholders for - unmodified sections. For example: - - \`\`\`language /path/to/file - // ... existing code ... - - {{ modified code here }} - - // ... existing code ... - - {{ another modification }} - - // ... rest of code ... - \`\`\` - - In existing files, you should always restate the function or class that the snippet belongs to: - - \`\`\`language /path/to/file - // ... existing code ... - - function exampleFunction() { - // ... existing code ... - - {{ modified code here }} - - // ... rest of function ... - } - - // ... rest of code ... - \`\`\` - - Since users have access to their complete file, they prefer reading only the - relevant modifications. It's perfectly acceptable to omit unmodified portions - at the beginning, middle, or end of files using these "lazy" comments. Only - provide the complete file when explicitly requested. Include a concise explanation - of changes unless the user specifically asks for code only. -`; - -export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ - - You are in chat mode. - - If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. - If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. - -${CODEBLOCK_FORMATTING_INSTRUCTIONS} -${EDIT_CODE_INSTRUCTIONS} -`; - -export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ - - You are in agent mode. - -${CODEBLOCK_FORMATTING_INSTRUCTIONS} -`; - -/** - * Helper function to get the context items for a user message - */ -function getUserContextItems( - userMsg: UserChatMessage | ToolResultChatMessage | undefined, - history: ChatHistoryItem[], -): ContextItemWithId[] { - if (!userMsg) return []; - - // Find the history item that contains the userMsg - const historyItem = history.find((item) => { - // Check if the message ID matches - if ("id" in userMsg && "id" in item.message) { - return (item.message as any).id === (userMsg as any).id; - } - // Fallback to content comparison - return ( - item.message.content === userMsg.content && - item.message.role === userMsg.role - ); - }); - - return historyItem?.contextItems || []; -} - -export function constructMessages( - messageMode: string, - history: ChatHistoryItem[], - baseChatOrAgentSystemMessage: string | undefined, - rules: RuleWithSource[], - rulePolicies?: RulePolicies, -): ChatMessage[] { - const filteredHistory = history.filter( - (item) => item.message.role !== "system", - ); - const msgs: ChatMessage[] = []; - - for (let i = 0; i < filteredHistory.length; i++) { - const historyItem = filteredHistory[i]; - - if (messageMode === "chat") { - const toolMessage: ToolResultChatMessage = - historyItem.message as ToolResultChatMessage; - if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) { - // remove all tool calls from the history - continue; - } - } - - if (historyItem.message.role === "user") { - // Gather context items for user messages - let content = normalizeToMessageParts(historyItem.message); - - const ctxItems = historyItem.contextItems - .map((ctxItem) => { - return { - type: "text", - text: `${ctxItem.content}\n`, - } as TextMessagePart; - }) - .filter((part) => !!part.text.trim()); - - content = [...ctxItems, ...content]; - msgs.push({ - ...historyItem.message, - content, - }); - } else { - msgs.push(historyItem.message); - } - } - - const lastUserMsg = findLast(msgs, isUserOrToolMsg) as - | UserChatMessage - | ToolResultChatMessage - | undefined; - - // Get context items for the last user message - const lastUserContextItems = getUserContextItems( - lastUserMsg, - filteredHistory, - ); - const systemMessage = getSystemMessageWithRules({ - baseSystemMessage: baseChatOrAgentSystemMessage, - rules, - userMessage: lastUserMsg, - contextItems: lastUserContextItems, - rulePolicies, - }); - - if (systemMessage.trim()) { - msgs.unshift({ - role: "system", - content: systemMessage, - }); - } - - // Remove the "id" from all of the messages - return msgs.map((msg) => { - const { id, ...rest } = msg as any; - return rest; - }); -} diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index 64ea23dd0..c2f82bac4 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -4,10 +4,12 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL = "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts"; -const EDIT_MESSAGE = `\ +export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\ Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' +`; +export const EDIT_CODE_INSTRUCTIONS = `\ When addressing code modification requests, present a concise code snippet that emphasizes only the necessary changes and uses abbreviated placeholders for unmodified sections. For example: @@ -54,12 +56,13 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically. If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details. -${EDIT_MESSAGE} +${CODEBLOCK_FORMATTING_INSTRUCTIONS} +${EDIT_CODE_INSTRUCTIONS} `; export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ You are in agent mode. -${EDIT_MESSAGE} +${CODEBLOCK_FORMATTING_INSTRUCTIONS} `; diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 14d44fadf..4b344ecea 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -122,13 +122,8 @@ export function ContextItemsPeekItem({ return (
openContextItem(contextItem, ideMessenger)} - className="group mr-2 flex cursor-pointer items-center overflow-hidden text-ellipsis whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10" ->>>>>>> d22ab74b15007ff7d84e3462bd344080305e1dc9 + className="mr-2 flex cursor-pointer flex-row items-center gap-1.5 whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10" data-testid="context-items-peek-item" > {getContextItemIcon()} diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 059f6e20b..07c547468 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -1,17 +1,11 @@ import { ChevronRightIcon } from "@heroicons/react/24/outline"; -<<<<<<< HEAD import { Tool, ToolCallState } from "core"; -import { ComponentType, useMemo, useState } from "react"; -import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; -======= -import { ContextItemWithId, Tool, ToolCallState } from "core"; import { ComponentType, useContext, useMemo, useState } from "react"; import { ContextItemsPeekItem, openContextItem, } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; ->>>>>>> d22ab74b15007ff7d84e3462bd344080305e1dc9 import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; @@ -30,18 +24,11 @@ export function SimpleToolCallUI({ tool, historyIndex, }: SimpleToolCallUIProps) { -<<<<<<< HEAD + const ideMessenger = useContext(IdeMessengerContext); const shownContextItems = useMemo(() => { const contextItems = toolCallStateToContextItems(toolCallState); return contextItems.filter((item) => !item.hidden); }, [toolCallState]); -======= - const ideMessenger = useContext(IdeMessengerContext); - - const ctxItems = useMemo(() => { - return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; - }, [contextItems]); ->>>>>>> d22ab74b15007ff7d84e3462bd344080305e1dc9 const [open, setOpen] = useState(false); const [isHovered, setIsHovered] = useState(false); @@ -51,8 +38,8 @@ export function SimpleToolCallUI({ return Object.entries(toolCallState.parsedArgs); }, [toolCallState.parsedArgs]); - const isToggleable = ctxItems.length > 1; - const isSingleItem = ctxItems.length === 1; + const isToggleable = shownContextItems.length > 1; + const isSingleItem = shownContextItems.length === 1; const shouldShowContent = isToggleable ? open : false; const isClickable = isToggleable || isSingleItem; @@ -60,7 +47,7 @@ export function SimpleToolCallUI({ if (isToggleable) { setOpen((prev) => !prev); } else if (isSingleItem) { - openContextItem(ctxItems[0], ideMessenger); + openContextItem(shownContextItems[0], ideMessenger); } } @@ -102,7 +89,6 @@ export function SimpleToolCallUI({
-<<<<<<< HEAD
{!!toolCallState.output?.length && ( @@ -116,31 +102,6 @@ export function SimpleToolCallUI({ ) : null}
- -
- {shownContextItems.length ? ( - shownContextItems.map((contextItem, idx) => ( - - )) - ) : ( -
- No tool call output -
-======= - {args.length > 0 && ( - ->>>>>>> d22ab74b15007ff7d84e3462bd344080305e1dc9 - )} -
- {isToggleable && ( @@ -149,8 +110,8 @@ export function SimpleToolCallUI({ shouldShowContent ? "max-h-[50vh] opacity-100" : "max-h-0 opacity-0" }`} > - {ctxItems.length > 0 ? ( - ctxItems.map((contextItem, idx) => ( + {shownContextItems.length > 0 ? ( + shownContextItems.map((contextItem, idx) => ( )) ) : ( From 401b3bbf502fe9ef4a9df1c3c43ffee83e0e1e0d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 30 Jun 2025 18:27:27 -0700 Subject: [PATCH 16/25] fix import error --- core/tools/definitions/editFile.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 53e18cd43..235833d1f 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,5 +1,5 @@ import { Tool } from "../.."; -import { EDIT_CODE_INSTRUCTIONS } from "../../llm/constructMessages"; +import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export interface EditToolArgs { From 6e3d42e80e9ccf4ee78e930315fc2770901d3dec Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 01:57:41 -0700 Subject: [PATCH 17/25] update message cancelaltion and rejection logic --- gui/src/components/AcceptRejectDiffButtons.tsx | 15 ++++++++++++++- gui/src/components/mainInput/InputToolbar.tsx | 14 +------------- gui/src/hooks/ParallelListeners.tsx | 11 +++++------ gui/src/pages/gui/Chat.tsx | 2 +- .../pages/gui/ToolCallDiv/SimpleToolCallUI.tsx | 2 +- gui/src/redux/util/constructMessages.ts | 4 +++- 6 files changed, 25 insertions(+), 23 deletions(-) diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index a19b56068..9420fc551 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -2,6 +2,9 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; import { useContext } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../redux/hooks"; +import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; +import { cancelToolCall } from "../redux/slices/sessionSlice"; import { getMetaKeyLabel } from "../util"; import { ToolTip } from "./gui/Tooltip"; @@ -20,8 +23,18 @@ export default function AcceptRejectAllButtons({ (state) => state.status === "done", ); const ideMessenger = useContext(IdeMessengerContext); - + const currentToolCallApplyState = useAppSelector( + selectCurrentToolCallApplyState, + ); + const dispatch = useAppDispatch(); async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { + if (currentToolCallApplyState?.status === "done") { + dispatch( + cancelToolCall({ + toolCallId: currentToolCallApplyState.toolCallId!, + }), + ); + } for (const { filepath = "", streamId } of pendingApplyStates) { ideMessenger.post(status, { filepath, diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 0dfbcd493..88d5a5c65 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -9,10 +9,6 @@ import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseActiveFile } from "../../redux/selectors"; -import { - selectCurrentToolCall, - selectCurrentToolCallApplyState, -} from "../../redux/selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice"; import { exitEdit } from "../../redux/thunks/edit"; @@ -53,20 +49,12 @@ function InputToolbar(props: InputToolbarProps) { const useActiveFile = useAppSelector(selectUseActiveFile); const isInEdit = useAppSelector((store) => store.session.isInEdit); const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit); - const toolCallState = useAppSelector(selectCurrentToolCall); - const currentToolCallApplyState = useAppSelector( - selectCurrentToolCallApplyState, - ); const hasReasoningEnabled = useAppSelector( (store) => store.session.hasReasoningEnabled, ); const isEnterDisabled = - props.disabled || - (isInEdit && codeToEdit.length === 0) || - toolCallState?.status === "generated" || - (currentToolCallApplyState && - currentToolCallApplyState.status !== "closed"); + props.disabled || (isInEdit && codeToEdit.length === 0); const toolsSupported = defaultModel && modelSupportsTools(defaultModel); diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 693359a97..246e92ce6 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -268,7 +268,6 @@ function ParallelListeners() { currentToolCallApplyState.streamId === state.streamId ) { if (state.status === "done" && autoAcceptEditToolDiffs) { - console.log("AUTO ACCEPTED"); ideMessenger.post("acceptDiff", { streamId: state.streamId, filepath: state.filepath, @@ -281,6 +280,11 @@ function ParallelListeners() { toolCallId: currentToolCallApplyState.toolCallId!, }), ); + void dispatch( + streamResponseAfterToolCall({ + toolCallId: currentToolCallApplyState.toolCallId!, + }), + ); } // const output: ContextItem = { // name: "Edit tool output", @@ -288,11 +292,6 @@ function ParallelListeners() { // description: "", // }; // dispatch(setToolCallOutput([])); - void dispatch( - streamResponseAfterToolCall({ - toolCallId: currentToolCallApplyState.toolCallId!, - }), - ); } } } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 126c4e894..a965f9559 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -319,7 +319,7 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === "tool" ? null : item.message.role === + ) : item.message.role === "tool" ? null : item.message.role === // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // +
Date: Tue, 1 Jul 2025 12:23:39 -0700 Subject: [PATCH 18/25] revert mode select fix for simplification (opened another PR) --- gui/src/components/ModeSelect/ModeSelect.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index 8989583ff..a5792d721 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -34,9 +34,7 @@ export function ModeSelect() { const cycleMode = useCallback(() => { dispatch(setMode(mode === "chat" ? "agent" : "chat")); - if (!document.activeElement?.classList.contains("ProseMirror")) { - mainEditor?.commands.focus(); - } + mainEditor?.commands.focus(); }, [mode, mainEditor]); const selectMode = useCallback( From eb7a5b63d50c5fd220ef3b0d969449e72d093ba0 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 12:40:46 -0700 Subject: [PATCH 19/25] move the tool truncation icon to a different PR --- gui/src/components/mainInput/icons.ts | 2 - gui/src/pages/gui/Chat.tsx | 3 +- .../gui/ToolCallDiv/SimpleToolCallUI.tsx | 48 ++++++++----------- gui/src/pages/gui/ToolCallDiv/ToolCall.tsx | 22 +++------ .../ToolCallDiv/ToolTruncateHistoryIcon.tsx | 40 ---------------- gui/src/pages/gui/ToolCallDiv/index.tsx | 11 +++-- gui/src/redux/slices/sessionSlice.ts | 23 --------- 7 files changed, 38 insertions(+), 111 deletions(-) delete mode 100644 gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx diff --git a/gui/src/components/mainInput/icons.ts b/gui/src/components/mainInput/icons.ts index 62d69e65b..d8d04cc83 100644 --- a/gui/src/components/mainInput/icons.ts +++ b/gui/src/components/mainInput/icons.ts @@ -18,7 +18,6 @@ import { PlusIcon, SparklesIcon, TrashIcon, - WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; import { DiscordIcon } from "../svg/DiscordIcon"; import { GithubIcon } from "../svg/GithubIcon"; @@ -56,5 +55,4 @@ export const NAMED_ICONS: { [key: string]: any } = { "gitlab-mr": GitlabIcon, http: GlobeAltIcon, trash: TrashIcon, - toolCall: WrenchScrewdriverIcon, }; diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index a965f9559..fb75d200c 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -319,7 +319,7 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === "tool" ? null : item.message.role === // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // ); diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx index 644638309..4a44a8ef3 100644 --- a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -1,5 +1,5 @@ import { ChevronRightIcon } from "@heroicons/react/24/outline"; -import { Tool, ToolCallState } from "core"; +import { ContextItemWithId, Tool, ToolCallState } from "core"; import { ComponentType, useContext, useMemo, useState } from "react"; import { ContextItemsPeekItem, @@ -7,28 +7,26 @@ import { } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; -import { toolCallStateToContextItems } from "./toolCallStateToContextItem"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; -import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon"; interface SimpleToolCallUIProps { toolCallState: ToolCallState; tool: Tool | undefined; + contextItems: ContextItemWithId[]; icon?: ComponentType>; - historyIndex: number; } export function SimpleToolCallUI({ + contextItems, icon: Icon, toolCallState, tool, - historyIndex, }: SimpleToolCallUIProps) { const ideMessenger = useContext(IdeMessengerContext); - const shownContextItems = useMemo(() => { - const contextItems = toolCallStateToContextItems(toolCallState); - return contextItems.filter((item) => !item.hidden); - }, [toolCallState]); + + const ctxItems = useMemo(() => { + return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; + }, [contextItems]); const [open, setOpen] = useState(false); const [isHovered, setIsHovered] = useState(false); @@ -38,8 +36,8 @@ export function SimpleToolCallUI({ return Object.entries(toolCallState.parsedArgs); }, [toolCallState.parsedArgs]); - const isToggleable = shownContextItems.length > 1; - const isSingleItem = shownContextItems.length === 1; + const isToggleable = ctxItems.length > 1; + const isSingleItem = ctxItems.length === 1; const shouldShowContent = isToggleable ? open : false; const isClickable = isToggleable || isSingleItem; @@ -47,7 +45,7 @@ export function SimpleToolCallUI({ if (isToggleable) { setOpen((prev) => !prev); } else if (isSingleItem) { - openContextItem(shownContextItems[0], ideMessenger); + openContextItem(ctxItems[0], ideMessenger); } } @@ -73,7 +71,7 @@ export function SimpleToolCallUI({ } return ( -
+
-
- {!!toolCallState.output?.length && ( - - )} - {args.length > 0 ? ( - - ) : null} -
+ {args.length > 0 && ( + + )}
+ {isToggleable && ( @@ -110,8 +104,8 @@ export function SimpleToolCallUI({ shouldShowContent ? "max-h-[50vh] opacity-100" : "max-h-0 opacity-0" }`} > - {shownContextItems.length > 0 ? ( - shownContextItems.map((contextItem, idx) => ( + {ctxItems.length > 0 ? ( + ctxItems.map((contextItem, idx) => ( )) ) : ( diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx index 956ef791b..dcfd186c7 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx @@ -2,14 +2,12 @@ import { Tool, ToolCallState } from "core"; import { useMemo, useState } from "react"; import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; -import { ToolTruncateHistoryIcon } from "./ToolTruncateHistoryIcon"; interface ToolCallDisplayProps { children: React.ReactNode; icon: React.ReactNode; tool: Tool | undefined; toolCallState: ToolCallState; - historyIndex: number; } export function ToolCallDisplay({ @@ -17,7 +15,6 @@ export function ToolCallDisplay({ toolCallState, children, icon, - historyIndex, }: ToolCallDisplayProps) { const [argsExpanded, setArgsExpanded] = useState(false); @@ -42,18 +39,13 @@ export function ToolCallDisplay({ toolCallState={toolCallState} />
-
- {!!toolCallState.output && ( - - )} - {!!args.length ? ( - - ) : null} -
+ {!!args.length ? ( + + ) : null}
{argsExpanded && !!args.length && ( diff --git a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx b/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx deleted file mode 100644 index e4f0a1cc8..000000000 --- a/gui/src/pages/gui/ToolCallDiv/ToolTruncateHistoryIcon.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { BarsArrowUpIcon } from "@heroicons/react/24/outline"; -import { chatMessageIsEmpty } from "core/llm/messages"; -import { findLastIndex } from "core/util/findLast"; -import { useMemo } from "react"; -import { useMainEditor } from "../../../components/mainInput/TipTapEditor"; -import { ToolbarButtonWithTooltip } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { truncateHistoryToMessage } from "../../../redux/slices/sessionSlice"; - -export function ToolTruncateHistoryIcon({ - historyIndex, -}: { - historyIndex: number; -}) { - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const history = useAppSelector((state) => state.session.history); - const lastMessageIndex = useMemo(() => { - return findLastIndex(history, (item) => !chatMessageIsEmpty(item.message)); - }, [history]); - const dispatch = useAppDispatch(); - const { mainEditor } = useMainEditor(); - if (isStreaming || historyIndex === lastMessageIndex) { - return null; - } - return ( - { - dispatch( - truncateHistoryToMessage({ - index: historyIndex, - }), - ); - mainEditor?.commands.focus(); - }} - > - - - ); -} diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 4141631bb..9f867356e 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -12,7 +12,12 @@ import { PencilIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { ToolCallDelta, ToolCallState, ToolStatus } from "core"; +import { + ContextItemWithId, + ToolCallDelta, + ToolCallState, + ToolStatus, +} from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { ComponentType, useMemo } from "react"; import { vscButtonBackground } from "../../../components"; @@ -25,6 +30,7 @@ import { ToolCallDisplay } from "./ToolCall"; interface ToolCallDivProps { toolCall: ToolCallDelta; toolCallState: ToolCallState; + output?: ContextItemWithId[]; historyIndex: number; } @@ -80,7 +86,7 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={ props.toolCallState.status === "generated" ? ArrowRightIcon : icon } - historyIndex={props.historyIndex} + contextItems={props.output ?? []} /> ); } @@ -90,7 +96,6 @@ export function ToolCallDiv(props: ToolCallDivProps) { icon={getStatusIcon(props.toolCallState.status)} tool={tool} toolCallState={props.toolCallState} - historyIndex={props.historyIndex} > , - ) => { - const { index } = payload; - - if (state.history.length && index < state.history.length) { - state.codeBlockApplyStates.curIndex = 0; - state.history = state.history.slice(0, index + 1).concat({ - message: { - id: uuidv4(), - role: "assistant", - content: "", // IMPORTANT - this is subsequently updated by response streaming - }, - contextItems: [], - }); - } - }, submitEditorAndInitAtIndex: ( state, { @@ -733,7 +711,6 @@ export const { addPromptCompletionPair, setActive, submitEditorAndInitAtIndex, - truncateHistoryToMessage, updateHistoryItemAtIndex, clearDanglingMessages, setMainEditorContentTrigger, From 6b0c022fd93e80530d574bc0345628b933b47b55 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 16:10:10 -0700 Subject: [PATCH 20/25] constructMessages tests --- core/llm/rules/getSystemMessageWithRules.ts | 5 +- gui/src/redux/thunks/streamNormalInput.ts | 37 +- gui/src/redux/util/constructMessages.test.ts | 734 +++++++++++++++++++ gui/src/redux/util/constructMessages.ts | 113 +-- 4 files changed, 789 insertions(+), 100 deletions(-) create mode 100644 gui/src/redux/util/constructMessages.test.ts diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 5b7eb4865..f017f24fd 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -349,7 +349,10 @@ export const getSystemMessageWithRules = ({ let systemMessage = baseSystemMessage ?? ""; for (const rule of appliedRules) { - systemMessage += `\n\n${rule.rule}`; + if (systemMessage) { + systemMessage += "\n\n"; + } + systemMessage += rule.rule; } return { diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index aa1744ed4..4dc78adaa 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -15,7 +15,10 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { constructMessages } from "../util/constructMessages"; +import { + constructMessages, + getBaseSystemMessage, +} from "../util/constructMessages"; import { callCurrentTool } from "./callCurrentTool"; export const streamNormalInput = createAsyncThunk< @@ -34,11 +37,6 @@ export const streamNormalInput = createAsyncThunk< throw new Error("No chat model selected"); } - const chatHistory = state.session.history; - const messageMode = state.session.mode; - const rulePolicies = state.ui.ruleSettings; - const streamAborter = state.session.streamAborter; - // Get tools const activeTools = selectActiveTools(state); const toolsSupported = modelSupportsTools(selectedChatModel); @@ -59,41 +57,46 @@ export const streamNormalInput = createAsyncThunk< }; } - // Construct messages - const withoutMessageIds = chatHistory.map((item) => { + // Construct messages (excluding system message) + const baseSystemMessage = getBaseSystemMessage( + state.session.mode, + selectedChatModel, + ); + + const withoutMessageIds = state.session.history.map((item) => { const { id, ...messageWithoutId } = item.message; return { ...item, message: messageWithoutId }; }); - const { messages, appliedRules, appliedRulesIndex } = constructMessages( - messageMode, + const { messages, appliedRules } = constructMessages( withoutMessageIds, - selectedChatModel, + baseSystemMessage, state.config.config.rules, - rulePolicies, - toolsSupported ? activeTools : [], + state.ui.ruleSettings, ); + // TODO parallel tool calls will cause issues with this + // because there will be multiple tool messages, so which one should have applied rules? dispatch( setAppliedRulesAtIndex({ - index: appliedRulesIndex, + index: messages.length - 1, appliedRules: appliedRules, }), ); dispatch(setActive()); - // Send request + // Send request and stream response + const streamAborter = state.session.streamAborter; const gen = extra.ideMessenger.llmStreamChat( { completionOptions, title: selectedChatModel.title, - messages, + messages: messages, legacySlashCommandData, }, streamAborter.signal, ); - // Stream response let next = await gen.next(); while (!next.done) { if (!getState().session.isStreaming) { diff --git a/gui/src/redux/util/constructMessages.test.ts b/gui/src/redux/util/constructMessages.test.ts new file mode 100644 index 000000000..18ab0ed45 --- /dev/null +++ b/gui/src/redux/util/constructMessages.test.ts @@ -0,0 +1,734 @@ +import { + AssistantChatMessage, + ChatHistoryItem, + ChatMessage, + ContextItemWithId, + ModelDescription, + RuleWithSource, + ThinkingChatMessage, + ToolResultChatMessage, + UserChatMessage, +} from "core"; +import { + DEFAULT_AGENT_SYSTEM_MESSAGE, + DEFAULT_CHAT_SYSTEM_MESSAGE, +} from "core/llm/defaultSystemMessages"; +import { renderChatMessage } from "core/util/messageContent"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { + CANCELLED_TOOL_CALL_MESSAGE, + constructMessages, + getBaseSystemMessage, + NO_TOOL_CALL_OUTPUT_MESSAGE, +} from "./constructMessages"; + +// For these tests we will mock the rules to simulate different scenarios +const CONTEXT_RULE: RuleWithSource = { + source: "rules-block", + rule: "CONTEXT_RULE", + description: "CONTEXT_TRIGGER", +}; +const LAST_MESSAGE_RULE: RuleWithSource = { + source: "rules-block", + rule: "LAST_MESSAGE_RULE", + description: "LAST_MESSAGE_TRIGGER", +}; +const NORMAL_RULE: RuleWithSource = { + source: "rules-block", + rule: "Always apply rule", +}; + +vi.mock("core/llm/rules/getSystemMessageWithRules", async (importOriginal) => { + const original = (await importOriginal()) as any; + return { + ...original, + getSystemMessageWithRules: ({ + baseSystemMessage, + availableRules, + userMessage, + contextItems, + rulePolicies, + }: { + baseSystemMessage: string; + availableRules: RuleWithSource[]; + userMessage?: UserChatMessage | ToolResultChatMessage; + contextItems: ContextItemWithId[]; + rulePolicies?: Record; + }) => { + // Filter rules based on our mock logic + const appliedRules = availableRules.filter((rule) => { + if (rule.rule === LAST_MESSAGE_RULE.rule) { + if (userMessage) { + return renderChatMessage(userMessage).includes( + LAST_MESSAGE_RULE.description!, + ); + } else { + return false; + } + } + if (rule.rule === CONTEXT_RULE.rule) { + return contextItems.some((item) => + item.content.includes(CONTEXT_RULE.description!), + ); + } + return true; + }); + + // Build the system message with applied rules + let systemMessage = baseSystemMessage || ""; + if (appliedRules.length > 0) { + systemMessage += "\n\nRules to follow:\n"; + for (const rule of appliedRules) { + systemMessage += `- ${rule.rule}\n`; + } + } + + return { systemMessage, appliedRules }; + }, + }; +}); + +test("getBaseSystemMessage should return the correct system message based on mode", () => { + const mockModel = { + baseAgentSystemMessage: "Custom Agent System Message", + baseChatSystemMessage: "Custom Chat System Message", + } as ModelDescription; + + // Test agent mode with custom message + expect(getBaseSystemMessage("agent", mockModel)).toBe( + "Custom Agent System Message", + ); + + // Test chat mode with custom message + expect(getBaseSystemMessage("chat", mockModel)).toBe( + "Custom Chat System Message", + ); + + // Test agent mode with default message + expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe( + DEFAULT_AGENT_SYSTEM_MESSAGE, + ); + + // Test chat mode with default message + expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe( + DEFAULT_CHAT_SYSTEM_MESSAGE, + ); +}); + +describe("constructMessages", () => { + // Setup mock data + let mockHistory: ChatHistoryItem[]; + const mockRules: RuleWithSource[] = [ + CONTEXT_RULE, + LAST_MESSAGE_RULE, + NORMAL_RULE, + ]; + + const createContextItem = ( + id: string, + content: string, + ): ContextItemWithId => ({ + id: { + providerTitle: "test-provider", + itemId: id, + }, + content, + name: `Context Item ${id}`, + description: `Description for ${id}`, + }); + + beforeEach(() => { + // Reset mock history before each test + mockHistory = []; + }); + + test("should ignore empty, tool, and system messages that go in", () => { + // Setup history with various message types including ones to be ignored + mockHistory = [ + { + message: { + role: "system", + content: "I should be ignored", + } as ChatMessage, + contextItems: [], + }, + { + message: { + role: "tool", + content: "I should be ignored", + toolCallId: "123", + } as ToolResultChatMessage, + contextItems: [], + }, + { + message: { role: "user", content: "" } as ChatMessage, // Empty message + contextItems: [], + }, + { + message: { role: "user", content: "Valid user message" } as ChatMessage, + contextItems: [], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should only contain a system message (added by the function) and the valid user message + expect(messages.length).toBe(2); + expect(messages[0].role).toBe("system"); + expect(messages[1].role).toBe("user"); + expect(messages[1].content).toEqual([ + { type: "text", text: "Valid user message" }, + ]); + expect(messages.some((msg) => msg.content === "I should be ignored")).toBe( + false, + ); + }); + + test("should convert user messages to message parts arrays with context items", () => { + const contextItems = [ + createContextItem("1", "Context content 1"), + createContextItem("2", "Context content 2"), + ]; + + mockHistory = [ + { + message: { + role: "user", + content: "User message with context", + } as ChatMessage, + contextItems, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Check that user message was converted to parts array with context items first + expect(messages.length).toBe(2); // System message + user message + expect(messages[1].role).toBe("user"); + + // Check content structure + const content = messages[1].content as any[]; + expect(content.length).toBe(3); // 2 context items + original message + expect(content[0].text).toContain("Context content 1"); + expect(content[1].text).toContain("Context content 2"); + expect(content[2].text).toBe("User message with context"); + }); + + test("should inject thinking messages with no changes", () => { + const thinkingMessage: ThinkingChatMessage = { + role: "thinking", + content: "Thinking process...", + }; + + mockHistory = [ + { + message: thinkingMessage, + contextItems: [], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have system message + thinking message + expect(messages.length).toBe(2); + expect(messages[1].role).toBe("thinking"); + expect(messages[1].content).toBe("Thinking process..."); + }); + + test("should inject assistant messages with no changes", () => { + const assistantMessage: AssistantChatMessage = { + role: "assistant", + content: "Assistant response", + }; + + mockHistory = [ + { + message: assistantMessage, + contextItems: [], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have system message + assistant message + expect(messages.length).toBe(2); + expect(messages[1].role).toBe("assistant"); + expect(messages[1].content).toBe("Assistant response"); + }); + + test("should follow assistant messages with tool calls by tool messages containing the tool output", () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I will search for that", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + // With tool output + mockHistory = [ + { + message: { + role: "user", + content: "Can you search for something?", + } as UserChatMessage, + contextItems: [], + }, + { + message: assistantWithToolCall, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "done", + parsedArgs: { query: "test" }, + output: [createContextItem("search-result", "Search result content")], + }, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have: system + user + assistant + tool messages + expect(messages.length).toBe(4); + expect(messages[2].role).toBe("assistant"); + expect(messages[3].role).toBe("tool"); + const toolMessage = messages[3] as ToolResultChatMessage; + expect(toolMessage.toolCallId).toBe("tool-call-1"); + expect(toolMessage.content).toContain("Search result content"); + }); + + test("should show cancelled message for cancelled tool calls", () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I will search for that", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + // With cancelled tool call + mockHistory = [ + { + message: assistantWithToolCall, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "canceled", + parsedArgs: { query: "test" }, + }, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have system + assistant + tool message with cancelled message + expect(messages.length).toBe(3); + expect(messages[2].role).toBe("tool"); + const toolMessage = messages[2] as ToolResultChatMessage; + expect(toolMessage.toolCallId).toBe("tool-call-1"); + expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE); + }); + + test('should show "No tool output" for tool calls without output', () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I will search for that", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + // With tool call but no output + mockHistory = [ + { + message: assistantWithToolCall, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "generating", // Not done yet + parsedArgs: { query: "test" }, + }, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have system + assistant + tool message with "No tool output" + expect(messages.length).toBe(3); + expect(messages[2].role).toBe("tool"); + expect(messages[2].content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); + }); + + test("should start with system message using base message if provided", () => { + mockHistory = [ + { + message: { role: "user", content: "Hello" } as UserChatMessage, + contextItems: [], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Custom Base System Message", + mockRules, + {}, + ); + + expect(messages[0].role).toBe("system"); + expect(messages[0].content).toContain("Custom Base System Message"); + }); + + test("should handle multiple tool calls in a single assistant message", () => { + const assistantWithMultipleToolCalls: AssistantChatMessage = { + role: "assistant", + content: "I will search and check the weather", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + { + id: "tool-call-2", + type: "function", + function: { + name: "weather", + arguments: '{"location": "New York"}', + }, + }, + ], + }; + + // Only the first tool call has output + mockHistory = [ + { + message: assistantWithMultipleToolCalls, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "done", + parsedArgs: { query: "test" }, + output: [createContextItem("search-result", "Search result content")], + }, + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Should have: system + assistant + 2 tool messages + expect(messages.length).toBe(4); + expect(messages[1].role).toBe("assistant"); + + // First tool message should have output + expect(messages[2].role).toBe("tool"); + expect(messages[3].role).toBe("tool"); + + const toolMessage1 = messages[2] as ToolResultChatMessage; + const toolMessage2 = messages[3] as ToolResultChatMessage; + expect(toolMessage1.toolCallId).toBe("tool-call-1"); + expect(toolMessage1.content).toContain("Search result content"); + + // Second tool message should have "No tool output" + expect(toolMessage2.toolCallId).toBe("tool-call-2"); + expect(toolMessage2.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); + }); + + test("should handle messages with array content", () => { + // User message with array content (including an image) + const userMessageWithArray: UserChatMessage = { + role: "user", + content: [ + { type: "text", text: "Here is some text" }, + { + type: "imageUrl", + imageUrl: { url: "https://example.com/image.jpg" }, + }, + ], + }; + + mockHistory = [ + { + message: userMessageWithArray, + contextItems: [createContextItem("ctx", "Context text")], + }, + ]; + + const { messages, appliedRules } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Check the user message content structure + expect(messages.length).toBe(2); + expect(messages[1].role).toBe("user"); + + const content = messages[1].content as any[]; + // Should have context item + original 2 parts + expect(content.length).toBe(3); + expect(content[0].type).toBe("text"); + expect(content[0].text).toContain("Context text"); + expect(content[1].type).toBe("text"); + expect(content[1].text).toBe("Here is some text"); + expect(content[2].type).toBe("imageUrl"); + expect(content[2].imageUrl.url).toBe("https://example.com/image.jpg"); + + // This also verifies that rules are NOT applied if the triggers are not present + expect(appliedRules).toHaveLength(1); + expect(appliedRules).toContainEqual(NORMAL_RULE); + }); + + test("system message should include rules triggered by context items from the last user message forward", () => { + // Create context item that should trigger the CONTEXT_RULE + const triggeringContextItem = createContextItem( + "trigger", + `Some content with ${CONTEXT_RULE.description} in it`, + ); + + mockHistory = [ + // First user message with non-triggering context + { + message: { role: "user", content: "First message" } as UserChatMessage, + contextItems: [createContextItem("normal", "Normal context")], + }, + // Assistant response + { + message: { + role: "assistant", + content: "Assistant response", + } as AssistantChatMessage, + contextItems: [], + }, + // Last user message with triggering context + { + message: { role: "user", content: "Last message" } as UserChatMessage, + contextItems: [triggeringContextItem], + }, + ]; + + const { messages, appliedRules } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Verify context rule was applied in the system message + expect(appliedRules).toHaveLength(2); + expect(appliedRules).toContainEqual(NORMAL_RULE); + expect(appliedRules).toContainEqual(CONTEXT_RULE); + expect(messages[0].role).toBe("system"); + expect(messages[0].content).toContain("Base System Message"); + expect(messages[0].content).toContain(CONTEXT_RULE.rule); + }); + + test("system message should include rules triggered by tool output after the last user message", () => { + // Create a history with a user message, assistant with tool call, and tool output containing triggering content + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I will search for that", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + // Tool output containing the trigger for CONTEXT_RULE + const triggeringToolOutput = createContextItem( + "search-result", + `Search result with ${CONTEXT_RULE.description} trigger`, + ); + + mockHistory = [ + { + message: { + role: "user", + content: "Can you search for something?", + } as UserChatMessage, + contextItems: [], + }, + { + message: assistantWithToolCall, + contextItems: [], + toolCallState: { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "done", + parsedArgs: { query: "test" }, + output: [triggeringToolOutput], + }, + }, + ]; + + const { messages, appliedRules } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // Verify context rule was applied in the system message due to the tool output + expect(appliedRules).toHaveLength(2); + expect(appliedRules).toContainEqual(NORMAL_RULE); + expect(appliedRules).toContainEqual(CONTEXT_RULE); + expect(messages[0].role).toBe("system"); + expect(messages[0].content).toContain("Base System Message"); + expect(messages[0].content).toContain(CONTEXT_RULE.rule); + }); + + test("system message should only apply rules triggered by the last user message", () => { + // First user message with trigger for LAST_MESSAGE_RULE + const firstUserMessage = { + role: "user", + content: `This contains ${LAST_MESSAGE_RULE.description}`, + } as UserChatMessage; + + // Last user message without any triggers + const lastUserMessage = { + role: "user", + content: "This is a normal message", + } as UserChatMessage; + + mockHistory = [ + { + message: firstUserMessage, + contextItems: [], + }, + { + message: { + role: "assistant", + content: "First response", + } as AssistantChatMessage, + contextItems: [], + }, + { + message: lastUserMessage, + contextItems: [], + }, + ]; + + const { messages, appliedRules } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + // LAST_MESSAGE_RULE should not be applied since the trigger is not in the last message + expect(appliedRules).toHaveLength(1); + expect(appliedRules).toContainEqual(NORMAL_RULE); // Normal rule should always apply + expect(messages[0].role).toBe("system"); + expect(messages[0].content).toContain("Base System Message"); + expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule); + }); +}); diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index 811b92c46..419e9af64 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -5,7 +5,6 @@ import { ModelDescription, RuleWithSource, TextMessagePart, - Tool, ToolResultChatMessage, UserChatMessage, } from "core"; @@ -16,31 +15,30 @@ import { import { chatMessageIsEmpty } from "core/llm/messages"; import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; import { RulePolicies } from "core/llm/rules/types"; -import { findLastIndex } from "core/util/findLast"; +import { findLast, findLastIndex } from "core/util/findLast"; import { normalizeToMessageParts, renderContextItems, } from "core/util/messageContent"; import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem"; +export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output"; +export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call."; + interface MessageWithContextItems { ctxItems: ContextItemWithId[]; message: ChatMessage; } export function constructMessages( - messageMode: string, history: ChatHistoryItem[], - model: ModelDescription, + baseSystemMessage: string | undefined, availableRules: RuleWithSource[], rulePolicies: RulePolicies, - tools: Tool[], ): { messages: ChatMessage[]; - appliedRulesIndex: number; appliedRules: RuleWithSource[]; } { const historyCopy = [...history]; - const validTools = new Set(tools.map((tool) => tool.function.name)); const msgs: MessageWithContextItems[] = []; for (const item of historyCopy) { @@ -57,7 +55,7 @@ export function constructMessages( // Gather context items for user messages let content = normalizeToMessageParts(item.message); - const ctxItems = item.contextItems + const ctxItemParts = item.contextItems .map((ctxItem) => { return { type: "text", @@ -66,7 +64,7 @@ export function constructMessages( }) .filter((part) => !!part.text.trim()); - content = [...ctxItems, ...content]; + content = [...ctxItemParts, ...content]; msgs.push({ ctxItems: item.contextItems, message: { @@ -80,42 +78,19 @@ export function constructMessages( message: item.message, }); } else if (item.message.role === "assistant") { - // This was implemented for APIs that require all tool calls to have - // A corresponsing tool sent, which means if a user excluded a tool - // Then sessions with that tool call in the history would fail - - // // First, push a version of the message with any valid tools calls - // const validToolCalls = item.message.toolCalls?.filter( - // (toolCall) => - // toolCall.function?.name && - // toolCall.id && - // validTools.has(toolCall.function.name), - // ); - - // const msgWithValidToolCalls: AssistantChatMessage = { - // ...item.message, - // toolCalls: validToolCalls, - // }; - - // if (chatMessageIsEmpty(msgWithValidToolCalls)) { - // msgs.push(...getChatSafeMessagesFromAgentToolCall(item)); - // } - - // Case where no valid tool calls or content are present msgs.push({ ctxItems: item.contextItems, message: item.message, }); - // Add a tool message for each valid tool call - // if(validToolCalls?.length) { + // Add a tool message for each tool call if (item.message.toolCalls?.length) { // If the assistant message has tool calls, we need to insert tool messages for (const toolCall of item.message.toolCalls) { - let content: string = "No tool output"; - // TODO toolCallState only supports one tool call per message for now + let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE; + // TODO parallel tool calls: toolCallState only supports one tool call per message for now if (item.toolCallState?.status === "canceled") { - content = "The user cancelled this tool call."; + content = CANCELLED_TOOL_CALL_MESSAGE; } else if ( item.toolCallState?.toolCallId === toolCall.id && item.toolCallState?.output @@ -135,17 +110,17 @@ export function constructMessages( } } + // Some rules only apply to the last user or tool message + const lastUserOrToolMsg = findLast( + msgs, + (item) => item.message.role === "user" || item.message.role === "tool", + )?.message as UserChatMessage | ToolResultChatMessage; + + // Some rules apply to all context items since the last user message, inclusiv const lastUserMsgIndex = findLastIndex( msgs, (item) => item.message.role === "user", ); - const lastUserOrToolMsgIndex = findLastIndex( - msgs, - (item) => item.message.role === "user" || item.message.role === "tool", - ); - const lastUserOrToolMsg = msgs[lastUserOrToolMsgIndex]?.message as - | UserChatMessage - | ToolResultChatMessage; const itemsBackToLastUserMessage = msgs .slice(lastUserMsgIndex, msgs.length) .filter( @@ -155,18 +130,8 @@ export function constructMessages( .map((item) => item.ctxItems) .flat(); - // Get system message - let baseChatOrAgentSystemMessage: string | undefined; - if (messageMode === "agent") { - baseChatOrAgentSystemMessage = - model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; - } else { - baseChatOrAgentSystemMessage = - model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; - } - - const { systemMessage } = getSystemMessageWithRules({ - baseSystemMessage: baseChatOrAgentSystemMessage, + const { systemMessage, appliedRules } = getSystemMessageWithRules({ + baseSystemMessage, availableRules, userMessage: lastUserOrToolMsg, contextItems: rulesContextItems, @@ -186,33 +151,17 @@ export function constructMessages( const messages = msgs.map((m) => m.message); return { messages, - appliedRulesIndex: lastUserOrToolMsgIndex, - appliedRules: availableRules, + appliedRules, }; } -// function getChatSafeMessagesFromAgentToolCall(item: ChatHistoryItem): MessageWithContextItems[] { -// if(item.message.role !== "assistant" || !item.message.toolCalls?.length) { -// console.error("Misusing getChatSafeMessagesFromAgentToolCall") -// return [] -// } -// const assistantItem: MessageWithContextItems = { -// ctxItems: item.toolCallState?.output ?? [], -// message: { -// role: "assistant", -// content: item.message.content + "\n\n" + item.message.toolCalls.map(tc => tc.function.name).join(", ") -// } -// } -// const userItem: MessageWithContextItems = { -// ctxItems: item.toolCallState?.output, -// message: { -// role: "user", -// content: item.message.content, -// } -// return [item, userItem] - -// if(message) - -// const msgs: MessageWithContextItems[] = []; -// if (message.message.role === "assistant" && message.message.toolCalls) { -// } +export function getBaseSystemMessage( + messageMode: string, + model: ModelDescription, +): string { + if (messageMode === "agent") { + return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; + } else { + return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; + } +} From fc0f9e3042cacd6bc925df758efdaf3e2867a7ac Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 17:31:38 -0700 Subject: [PATCH 21/25] bedrock message conversions --- core/llm/llms/Bedrock.ts | 335 +++++++++++++++++++++------------------ 1 file changed, 184 insertions(+), 151 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 371713905..5b9895c06 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -1,8 +1,10 @@ import { BedrockRuntimeClient, ContentBlock, + ConversationRole, ConverseStreamCommand, ConverseStreamCommandOutput, + ImageFormat, InvokeModelCommand, Message, ToolConfiguration, @@ -14,6 +16,7 @@ import { Chunk, CompletionOptions, LLMOptions, + MessageContent, } from "../../index.js"; import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; @@ -289,8 +292,8 @@ class Bedrock extends BaseLLM { const systemMessage = stripImages( messages.find((m) => m.role === "system")?.content ?? "", ); - const convertedMessages = this._convertMessages(messages); + // Prompt and system message caching settings const shouldCacheSystemMessage = (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) || this.completionOptions.promptCaching; @@ -298,9 +301,7 @@ class Bedrock extends BaseLLM { shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching; - const shouldCacheToolsConfig = this.completionOptions.promptCaching; - // Add header for prompt caching if (enablePromptCaching) { this.requestOptions.headers = { ...this.requestOptions.headers, @@ -308,30 +309,37 @@ class Bedrock extends BaseLLM { }; } + // First get tools const supportsTools = (this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false; - let toolConfig = - supportsTools && options.tools - ? ({ - tools: options.tools.map((tool) => ({ - toolSpec: { - name: tool.function.name, - description: tool.function.description, - inputSchema: { - json: tool.function.parameters, - }, - }, - })), - } as ToolConfiguration) - : undefined; - - if (toolConfig?.tools && shouldCacheToolsConfig) { - toolConfig.tools.push({ cachePoint: { type: "default" } }); + let toolConfig: undefined | ToolConfiguration = undefined; + const availableTools = new Set(); + if (supportsTools && options.tools && options.tools.length > 0) { + toolConfig = { + tools: options.tools.map((tool) => ({ + toolSpec: { + name: tool.function.name, + description: tool.function.description, + inputSchema: { + json: tool.function.parameters, + }, + }, + })), + } as ToolConfiguration; + const shouldCacheToolsConfig = this.completionOptions.promptCaching; + if (shouldCacheToolsConfig) { + toolConfig.tools!.push({ cachePoint: { type: "default" } }); + } + options.tools.forEach((tool) => { + availableTools.add(tool.function.name); + }); } + const convertedMessages = this._convertMessages(messages, availableTools); + return { modelId: options.model, system: systemMessage @@ -368,25 +376,75 @@ class Bedrock extends BaseLLM { }; } - private _convertMessage( - message: ChatMessage, - addCaching: boolean = false, - ): Message | null { - // Handle system messages explicitly - if (message.role === "system") { - return null; + private _convertMessages( + messages: ChatMessage[], + availableTools: Set, + ): Message[] { + const nonSystemMessages = messages.filter((m) => m.role !== "system"); + + const lastTwoUserMsgIndices: number[] = []; + for (let i = nonSystemMessages.length - 1; i >= 0; i--) { + if (nonSystemMessages[i].role === "user") { + lastTwoUserMsgIndices.push(i); + if (lastTwoUserMsgIndices.length === 2) { + break; + } + } } - const cachePoint = addCaching - ? { cachePoint: { type: "default" } } - : undefined; + let currentRole: "user" | "assistant" = "user"; + let currentBlocks: ContentBlock[] = []; + let addCachePoint = false; - // Tool response handling - if (message.role === "tool") { - return { - role: "user", - content: [ - { + const converted: Message[] = []; + const pushCurrentMessage = () => { + if (currentBlocks.length === 0 && converted.length > 1) { + throw new Error( + `Bedrock: no content in ${currentRole} message before conversational turn change`, + ); + } + if (currentBlocks.length > 0) { + if (addCachePoint) { + currentBlocks.push({ cachePoint: { type: "default" } }); + } + converted.push({ + role: currentRole, + content: currentBlocks, + }); + } + // Change roles and reset + currentBlocks = []; + addCachePoint = false; + }; + + for (let idx = 0; idx < nonSystemMessages.length; idx++) { + const message = nonSystemMessages[idx]; + if (message.role === "user" || message.role === "tool") { + pushCurrentMessage(); + currentRole = ConversationRole.USER; + + if (message.role === "user") { + if (message.content) { + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + const messageIsCached = !!( + this.cacheBehavior?.cacheConversation && + lastTwoUserMsgIndices.includes(idx) + ); + if (messageIsCached) { + addCachePoint = true; + } + currentBlocks.push( + ...this._convertMessageContentToBlocks( + message.content, + messageIsCached, + ), + ); + } + } else if (message.role === "tool") { + currentBlocks.push({ toolResult: { toolUseId: message.toolCallId, content: [ @@ -395,140 +453,115 @@ class Bedrock extends BaseLLM { }, ], }, - }, - ], - }; - } - - // Tool calls handling - if (message.role === "assistant" && message.toolCalls) { - return { - role: "assistant", - content: message.toolCalls.map((toolCall) => ({ - toolUse: { - toolUseId: toolCall.id, - name: toolCall.function?.name, - input: safeParseToolCallArgs(toolCall), - }, - })), - }; - } - - if (message.role === "thinking") { - if (message.redactedThinking) { - const content: ContentBlock.ReasoningContentMember = { - reasoningContent: { - redactedContent: new Uint8Array( - Buffer.from(message.redactedThinking), - ), - }, - }; - return { - role: "assistant", - content: [content], - }; + }); + } } else { - const content: ContentBlock.ReasoningContentMember = { - reasoningContent: { - reasoningText: { - text: (message.content as string) || "", - signature: message.signature, - }, - }, - }; - return { - role: "assistant", - content: [content], - }; + pushCurrentMessage(); + currentRole = ConversationRole.ASSISTANT; + + if (message.role === "assistant") { + if (message.content) { + currentBlocks.push( + ...this._convertMessageContentToBlocks(message.content, false), + ); + } + if (message.toolCalls) { + for (const toolCall of message.toolCalls) { + if (availableTools.has(toolCall.function?.name || "")) { + currentBlocks.push({ + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function?.name, + input: safeParseToolCallArgs(toolCall), + }, + }); + } else { + console.warn( + `Tool ${toolCall.function?.name} is not available for this model.`, + ); + } + } + } + } else if (message.role === "thinking") { + if (message.redactedThinking) { + const block: ContentBlock.ReasoningContentMember = { + reasoningContent: { + redactedContent: new Uint8Array( + Buffer.from(message.redactedThinking), + ), + }, + }; + currentBlocks.push(block); + } else { + const block: ContentBlock.ReasoningContentMember = { + reasoningContent: { + reasoningText: { + text: (message.content as string) || "", + signature: message.signature, + }, + }, + }; + currentBlocks.push(block); + } + } } } - // Standard text message - if (typeof message.content === "string") { - if (addCaching) { - message.content += getSecureID(); - } - const content: any[] = [{ text: message.content }]; - if (addCaching) { - content.push({ cachePoint: { type: "default" } }); - } - return { - role: message.role, - content, - }; - } + return converted; + } - // Improved multimodal content handling - if (Array.isArray(message.content)) { - const content: any[] = []; - - // Process all parts first - message.content.forEach((part) => { + private _convertMessageContentToBlocks( + content: MessageContent, + addCaching: boolean, + ): ContentBlock[] { + const blocks: ContentBlock[] = []; + if (typeof content === "string") { + let contentText = content; + if (addCaching) { + contentText += getSecureID(); + } + blocks.push({ text: contentText }); + if (addCaching) { + blocks.push({ cachePoint: { type: "default" } }); + } + } else { + for (const part of content) { if (part.type === "text") { if (addCaching) { part.text += getSecureID(); } - content.push({ text: part.text }); + blocks.push({ text: part.text }); } else if (part.type === "imageUrl" && part.imageUrl) { try { const [mimeType, base64Data] = part.imageUrl.url.split(","); const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; - content.push({ - image: { - format, - source: { - bytes: Buffer.from(base64Data, "base64"), + if ( + format === ImageFormat.JPEG || + format === ImageFormat.PNG || + format === ImageFormat.WEBP || + format === ImageFormat.GIF + ) { + blocks.push({ + image: { + format, + source: { + bytes: Uint8Array.from(Buffer.from(base64Data, "base64")), + }, }, - }, - }); + }); + } else { + console.warn( + `Bedrock: skipping unsupported image part format: ${format}`, + part, + ); + } } catch (error) { - console.warn(`Failed to process image: ${error}`); + console.warn("Bedrock: failed to process image part", error, part); } } - }); - - // Add cache point as a separate block at the end if needed - if (addCaching && content.length > 0) { - content.push({ cachePoint: { type: "default" } }); } - - return { - role: message.role, - content, - } as Message; } - return null; - } - - private _convertMessages(messages: ChatMessage[]): any[] { - const filteredmessages = messages.filter( - (m) => m.role !== "system" && !!m.content, - ); - const lastTwoUserMsgIndices = filteredmessages - .map((msg, index) => (msg.role === "user" ? index : -1)) - .filter((index) => index !== -1) - .slice(-2); - - const converted = filteredmessages - .map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html - const addCaching = - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(filteredMsgIdx); - - try { - return this._convertMessage(message, addCaching); - } catch (error) { - console.error(`Failed to convert message: ${error}`); - return null; - } - }) - .filter(Boolean); - - return converted; + return blocks; } private async _getCredentials() { From 4789babdbb159d87ee1a80c18e429bf3c241778f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 18:12:18 -0700 Subject: [PATCH 22/25] update bedrock tests --- core/llm/llms/Bedrock.test.ts | 344 +++++++++++++++++++++++++--------- core/llm/llms/Bedrock.ts | 89 ++++++--- 2 files changed, 317 insertions(+), 116 deletions(-) diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts index a3088f409..69b4ab7a8 100644 --- a/core/llm/llms/Bedrock.test.ts +++ b/core/llm/llms/Bedrock.test.ts @@ -1,12 +1,10 @@ -import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; -import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; -import Bedrock from "./Bedrock.js"; import { ChatMessage, Chunk, CompletionOptions, UserChatMessage, } from "../../index.js"; +import Bedrock from "./Bedrock.js"; // Mock AWS SDK jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ @@ -317,96 +315,266 @@ describe("Bedrock", () => { }); }); - it("should convert text messages correctly", () => { - const message: ChatMessage = { - role: "user", - content: "Hello", - } as UserChatMessage; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [{ text: "Hello" }], - }); + it("should convert simple user and assistant messages correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Hello" } as UserChatMessage, + { role: "assistant", content: "Hi there" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Hello" }] }, + { role: "assistant", content: [{ text: "Hi there" }] }, + ]); }); - it("should convert tool responses correctly", () => { - const message: ChatMessage = { - role: "tool", - content: "Tool result", - toolCallId: "tool-1", - }; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [ - { - toolResult: { - toolUseId: "tool-1", - content: [{ text: "Tool result" }], - }, - }, - ], - }); - }); - - it("should convert tool calls correctly", () => { - const message: ChatMessage = { - role: "assistant", - content: "", - toolCalls: [ - { - id: "tool-1", - type: "function" as const, - function: { - name: "test_tool", - arguments: '{"arg":"value"}', - }, - }, - ], - }; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "assistant", - content: [ - { - toolUse: { - toolUseId: "tool-1", - name: "test_tool", - input: { arg: "value" }, - }, - }, - ], - }); - }); - - it("should handle multimodal content correctly", () => { - const message: ChatMessage = { - role: "user", - content: [ - { type: "text", text: "Look at this image:" }, - { - type: "imageUrl", - imageUrl: { - url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", - }, - }, - ], - } as UserChatMessage; - const converted = bedrock["_convertMessage"](message); - expect(converted).toEqual({ - role: "user", - content: [ - { text: "Look at this image:" }, - { - image: { - format: "jpeg", - source: { - bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"), + it("should handle tool responses correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Use a tool" } as UserChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-1", + type: "function", + function: { + name: "test_tool", + arguments: '{"arg":"value"}', }, }, - }, - ], + ], + }, + { + role: "tool", + content: "Tool result", + toolCallId: "tool-1", + }, + ]; + + const availableTools = new Set(["test_tool"]); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Use a tool" }] }, + { + role: "assistant", + content: [ + { + toolUse: { + toolUseId: "tool-1", + name: "test_tool", + input: { arg: "value" }, + }, + }, + ], + }, + { + role: "user", + content: [ + { + toolResult: { + toolUseId: "tool-1", + content: [{ text: "Tool result" }], + }, + }, + ], + }, + ]); + }); + + it("should handle tool calls with unavailable tools as text", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Use a tool" } as UserChatMessage, + { + role: "assistant", + content: "", + toolCalls: [ + { + id: "tool-1", + type: "function", + function: { + name: "unavailable_tool", + arguments: '{"arg":"value"}', + }, + }, + ], + }, + ]; + + // Empty set means no tools are available + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Use a tool" }] }, + { + role: "assistant", + content: [ + { + text: expect.stringContaining("Assistant tool call:"), + }, + ], + }, + ]); + }); + + it("should handle thinking messages correctly", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Think about this" } as UserChatMessage, + { role: "thinking", content: "I am thinking about the solution" }, + { role: "assistant", content: "Here's my answer" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Think about this" }] }, + { + role: "assistant", + content: [ + { + reasoningContent: { + reasoningText: { + text: "I am thinking about the solution", + signature: undefined, + }, + }, + }, + { text: "Here's my answer" }, + ], + }, + ]); + }); + + it("should handle redacted thinking messages", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "Think about this" } as UserChatMessage, + { + role: "thinking", + content: "", + redactedThinking: "redacted-content-bytes", + }, + { role: "assistant", content: "Here's my answer" }, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { role: "user", content: [{ text: "Think about this" }] }, + { + role: "assistant", + content: [ + { + reasoningContent: { + redactedContent: expect.any(Uint8Array), + }, + }, + { text: "Here's my answer" }, + ], + }, + ]); + + // Check that the Uint8Array contains the expected bytes + const redactedContent = + converted[1].content?.[0].reasoningContent?.redactedContent; + expect(redactedContent).toBeInstanceOf(Uint8Array); + expect(Buffer.from(redactedContent!).toString()).toBe( + "redacted-content-bytes", + ); + }); + + it("should convert multimodal content correctly", () => { + const messages: ChatMessage[] = [ + { + role: "user", + content: [ + { type: "text", text: "Look at this image:" }, + { + type: "imageUrl", + imageUrl: { + url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", + }, + }, + ], + } as UserChatMessage, + ]; + + const availableTools = new Set(); + const converted = bedrock["_convertMessages"](messages, availableTools); + + expect(converted).toEqual([ + { + role: "user", + content: [ + { text: "Look at this image:" }, + { + image: { + format: "jpeg", + source: { + bytes: expect.any(Uint8Array), + }, + }, + }, + ], + }, + ]); + + // Check that the image bytes were processed correctly + const imageBytes = converted[0].content?.[1].image?.source?.bytes; + expect(imageBytes).toBeInstanceOf(Uint8Array); + expect(Buffer.from(imageBytes!).toString("base64")).toBe( + "/9j/4AAQSkZJRg==", + ); + }); + + it("should add cache points for prompt caching when needed", () => { + // Create a test instance with caching behavior enabled + const bedrockWithCaching = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", }); + + // Set caching behavior + bedrockWithCaching.cacheBehavior = { + cacheConversation: true, + cacheSystemMessage: true, + }; + + const messages: ChatMessage[] = [ + { role: "system", content: "You are a helpful assistant" }, + { role: "user", content: "First message" } as UserChatMessage, + { role: "assistant", content: "First response" }, + { role: "user", content: "Second message" } as UserChatMessage, + ]; + + const availableTools = new Set(); + const converted = bedrockWithCaching["_convertMessages"]( + messages, + availableTools, + ); + + // The last two user messages should have cache points + // But we're not testing the system message here since it's handled separately + expect(converted.length).toBe(3); + expect(converted[0].role).toBe("user"); + expect(converted[0].content?.some((block) => block.cachePoint)).toBe( + true, + ); + expect(converted[1].role).toBe("assistant"); + expect(converted[2].role).toBe("user"); + expect(converted[2].content?.some((block) => block.cachePoint)).toBe( + true, + ); + + // Verify that text content includes a cache ID suffix + const userMessageText = converted[0].content?.[0].text; + expect(userMessageText).toMatch(/First message.+/); }); }); }); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 5b9895c06..c50ad842e 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -392,6 +392,7 @@ class Bedrock extends BaseLLM { } } + const hasAddedToolCallIds = new Set(); let currentRole: "user" | "assistant" = "user"; let currentBlocks: ContentBlock[] = []; let addCachePoint = false; @@ -419,12 +420,19 @@ class Bedrock extends BaseLLM { for (let idx = 0; idx < nonSystemMessages.length; idx++) { const message = nonSystemMessages[idx]; + if (message.role === "user" || message.role === "tool") { - pushCurrentMessage(); - currentRole = ConversationRole.USER; + if (currentRole !== ConversationRole.USER) { + pushCurrentMessage(); + currentRole = ConversationRole.USER; + } if (message.role === "user") { - if (message.content) { + const trimmedContent = + typeof message.content === "string" + ? message.content.trim() + : message.content; + if (trimmedContent) { // Add cache_control parameter to the last two user messages // The second-to-last because it retrieves potentially already cached contents, // The last one because we want it cached for later retrieval. @@ -438,47 +446,69 @@ class Bedrock extends BaseLLM { } currentBlocks.push( ...this._convertMessageContentToBlocks( - message.content, + trimmedContent, messageIsCached, ), ); } } else if (message.role === "tool") { - currentBlocks.push({ - toolResult: { - toolUseId: message.toolCallId, - content: [ - { - text: message.content || "", - }, - ], - }, - }); + const trimmedContent = message.content.trim() || "No tool output"; + if (hasAddedToolCallIds.has(message.toolCallId)) { + currentBlocks.push({ + toolResult: { + toolUseId: message.toolCallId, + content: [ + { + text: trimmedContent, + }, + ], + }, + }); + } else { + currentBlocks.push({ + text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`, + }); + } + } + } else if (message.role === "assistant" || message.role === "thinking") { + if (currentRole !== ConversationRole.ASSISTANT) { + pushCurrentMessage(); + currentRole = ConversationRole.ASSISTANT; } - } else { - pushCurrentMessage(); - currentRole = ConversationRole.ASSISTANT; if (message.role === "assistant") { - if (message.content) { + const trimmedContent = + typeof message.content === "string" + ? message.content.trim() + : message.content; + if (trimmedContent) { currentBlocks.push( - ...this._convertMessageContentToBlocks(message.content, false), + ...this._convertMessageContentToBlocks(trimmedContent, false), ); } if (message.toolCalls) { for (const toolCall of message.toolCalls) { - if (availableTools.has(toolCall.function?.name || "")) { - currentBlocks.push({ - toolUse: { - toolUseId: toolCall.id, - name: toolCall.function?.name, - input: safeParseToolCallArgs(toolCall), - }, - }); + if (toolCall.id && toolCall.function?.name) { + if (availableTools.has(toolCall.function.name)) { + hasAddedToolCallIds.add(toolCall.id); + currentBlocks.push({ + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function.name, + input: safeParseToolCallArgs(toolCall), + }, + }); + } else { + const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`; + currentBlocks.push({ + text: toolCallText, + }); + } } else { console.warn( - `Tool ${toolCall.function?.name} is not available for this model.`, + `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`, ); + continue; } } } @@ -506,6 +536,9 @@ class Bedrock extends BaseLLM { } } } + if (currentBlocks.length > 0) { + pushCurrentMessage(); + } return converted; } From d77684280b2a74354da9f8c9e563bc2f84ada1ab Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 18:40:25 -0700 Subject: [PATCH 23/25] fix failing edit test - only cancel if rejectDiff --- gui/src/components/AcceptRejectDiffButtons.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index 9420fc551..252d19332 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -28,7 +28,10 @@ export default function AcceptRejectAllButtons({ ); const dispatch = useAppDispatch(); async function handleAcceptOrReject(status: AcceptOrRejectOutcome) { - if (currentToolCallApplyState?.status === "done") { + if ( + status === "rejectDiff" && + currentToolCallApplyState?.status === "done" + ) { dispatch( cancelToolCall({ toolCallId: currentToolCallApplyState.toolCallId!, From 334282fc3415147424b196f16da5f20c33740ea8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 19:02:52 -0700 Subject: [PATCH 24/25] applied rules to user message --- gui/src/redux/thunks/streamNormalInput.ts | 4 ++-- gui/src/redux/util/constructMessages.ts | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 4dc78adaa..0133a101a 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -67,7 +67,7 @@ export const streamNormalInput = createAsyncThunk< const { id, ...messageWithoutId } = item.message; return { ...item, message: messageWithoutId }; }); - const { messages, appliedRules } = constructMessages( + const { messages, appliedRules, appliedRuleIndex } = constructMessages( withoutMessageIds, baseSystemMessage, state.config.config.rules, @@ -78,7 +78,7 @@ export const streamNormalInput = createAsyncThunk< // because there will be multiple tool messages, so which one should have applied rules? dispatch( setAppliedRulesAtIndex({ - index: messages.length - 1, + index: appliedRuleIndex, appliedRules: appliedRules, }), ); diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index 419e9af64..15f8120db 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -37,11 +37,15 @@ export function constructMessages( ): { messages: ChatMessage[]; appliedRules: RuleWithSource[]; + appliedRuleIndex: number; } { const historyCopy = [...history]; const msgs: MessageWithContextItems[] = []; + let appliedRuleIndex = -1; + let index = -1; for (const item of historyCopy) { + index++; if ( item.message.role === "system" || item.message.role === "tool" || @@ -52,6 +56,7 @@ export function constructMessages( } if (item.message.role === "user") { + appliedRuleIndex = index; // Gather context items for user messages let content = normalizeToMessageParts(item.message); @@ -152,6 +157,7 @@ export function constructMessages( return { messages, appliedRules, + appliedRuleIndex, }; } From fb6ec5bbe9b692b2e1d21188e25cd59890072a58 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 1 Jul 2025 20:14:56 -0700 Subject: [PATCH 25/25] fix bedrock caching, add comments to message conversions --- core/llm/llms/Bedrock.ts | 109 +++++++++++++++++++++------------------ 1 file changed, 60 insertions(+), 49 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index c50ad842e..1c1c61ed3 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -376,26 +376,16 @@ class Bedrock extends BaseLLM { }; } + /* + Converts the messages to the format expected by the Bedrock API. + + */ private _convertMessages( messages: ChatMessage[], availableTools: Set, ): Message[] { - const nonSystemMessages = messages.filter((m) => m.role !== "system"); - - const lastTwoUserMsgIndices: number[] = []; - for (let i = nonSystemMessages.length - 1; i >= 0; i--) { - if (nonSystemMessages[i].role === "user") { - lastTwoUserMsgIndices.push(i); - if (lastTwoUserMsgIndices.length === 2) { - break; - } - } - } - - const hasAddedToolCallIds = new Set(); let currentRole: "user" | "assistant" = "user"; let currentBlocks: ContentBlock[] = []; - let addCachePoint = false; const converted: Message[] = []; const pushCurrentMessage = () => { @@ -405,53 +395,46 @@ class Bedrock extends BaseLLM { ); } if (currentBlocks.length > 0) { - if (addCachePoint) { - currentBlocks.push({ cachePoint: { type: "default" } }); - } converted.push({ role: currentRole, content: currentBlocks, }); } - // Change roles and reset currentBlocks = []; - addCachePoint = false; }; + const nonSystemMessages = messages.filter((m) => m.role !== "system"); + const hasAddedToolCallIds = new Set(); + for (let idx = 0; idx < nonSystemMessages.length; idx++) { const message = nonSystemMessages[idx]; if (message.role === "user" || message.role === "tool") { + // Detect conversational turn change if (currentRole !== ConversationRole.USER) { pushCurrentMessage(); currentRole = ConversationRole.USER; } + // USER messages: + // Non-empty user message content is converted to "text" and "image" blocks + // If ANY user message part is cached, we add a single cache point block when we push the message if (message.role === "user") { const trimmedContent = typeof message.content === "string" ? message.content.trim() : message.content; if (trimmedContent) { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html - const messageIsCached = !!( - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(idx) - ); - if (messageIsCached) { - addCachePoint = true; - } currentBlocks.push( - ...this._convertMessageContentToBlocks( - trimmedContent, - messageIsCached, - ), + ...this._convertMessageContentToBlocks(trimmedContent), ); } - } else if (message.role === "tool") { + } + // TOOL messages: + // Tool messages are represented by "toolResult" blocks + // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig) + // If it doesn't, we convert it to a text block + else if (message.role === "tool") { const trimmedContent = message.content.trim() || "No tool output"; if (hasAddedToolCallIds.has(message.toolCallId)) { currentBlocks.push({ @@ -471,11 +454,14 @@ class Bedrock extends BaseLLM { } } } else if (message.role === "assistant" || message.role === "thinking") { + // Detect conversational turn change if (currentRole !== ConversationRole.ASSISTANT) { pushCurrentMessage(); currentRole = ConversationRole.ASSISTANT; } + // ASSISTANT messages: + // Non-empty assistant message content is converted to "text" and "image" blocks if (message.role === "assistant") { const trimmedContent = typeof message.content === "string" @@ -483,14 +469,18 @@ class Bedrock extends BaseLLM { : message.content; if (trimmedContent) { currentBlocks.push( - ...this._convertMessageContentToBlocks(trimmedContent, false), + ...this._convertMessageContentToBlocks(trimmedContent), ); } + // TOOL CALLS: + // Tool calls are represented by "toolUse" blocks + // Each tool call must have an id and a function name + // The function name must match one of the available tools + // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools) if (message.toolCalls) { for (const toolCall of message.toolCalls) { if (toolCall.id && toolCall.function?.name) { if (availableTools.has(toolCall.function.name)) { - hasAddedToolCallIds.add(toolCall.id); currentBlocks.push({ toolUse: { toolUseId: toolCall.id, @@ -498,6 +488,7 @@ class Bedrock extends BaseLLM { input: safeParseToolCallArgs(toolCall), }, }); + hasAddedToolCallIds.add(toolCall.id); } else { const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`; currentBlocks.push({ @@ -513,6 +504,8 @@ class Bedrock extends BaseLLM { } } } else if (message.role === "thinking") { + // THINKING: + // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content if (message.redactedThinking) { const block: ContentBlock.ReasoningContentMember = { reasoningContent: { @@ -540,29 +533,47 @@ class Bedrock extends BaseLLM { pushCurrentMessage(); } + // If caching is enabled, we add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + if (this.cacheBehavior?.cacheConversation) { + this._addCachingToLastTwoUserMessages(converted); + } + return converted; } + private _addCachingToLastTwoUserMessages(converted: Message[]) { + let numCached = 0; + for (let i = converted.length - 1; i >= 0; i--) { + const message = converted[i]; + if (message.role === "user") { + message.content?.forEach((block) => { + if (block.text) { + block.text += getSecureID(); + } + }); + message.content?.push({ cachePoint: { type: "default" } }); + numCached++; + } + if (numCached === 2) { + break; + } + } + } + + // Converts Continue message content (string/parts) to Bedrock ContentBlock format. + // Unsupported/problematic image formats are skipped with a warning. private _convertMessageContentToBlocks( content: MessageContent, - addCaching: boolean, ): ContentBlock[] { const blocks: ContentBlock[] = []; if (typeof content === "string") { - let contentText = content; - if (addCaching) { - contentText += getSecureID(); - } - blocks.push({ text: contentText }); - if (addCaching) { - blocks.push({ cachePoint: { type: "default" } }); - } + blocks.push({ text: content }); } else { for (const part of content) { if (part.type === "text") { - if (addCaching) { - part.text += getSecureID(); - } blocks.push({ text: part.text }); } else if (part.type === "imageUrl" && part.imageUrl) { try {