From 7d5eb828f059fbccf47340eb30eab95674a66478 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 27 Mar 2025 15:09:34 -0700 Subject: [PATCH] slash command fixes --- core/commands/index.ts | 57 ++++----------- core/commands/slash/http.ts | 4 +- .../v1/slashCommandFromPromptFile.ts | 4 +- core/promptFiles/v1/updateChatHistory.ts | 2 +- .../CodeToEditCard/CodeToEditCard.tsx | 12 +-- .../mainInput/tiptap/resolveInput.ts | 73 +++++++------------ gui/src/pages/gui/Chat.tsx | 4 +- gui/src/redux/thunks/gatherContext.ts | 3 +- gui/src/redux/thunks/streamResponse.ts | 45 +++++------- 9 files changed, 74 insertions(+), 130 deletions(-) diff --git a/core/commands/index.ts b/core/commands/index.ts index b6f233485..7115d22be 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,5 +1,6 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; +import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory"; import { renderChatMessage } from "../util/messageContent"; import SlashCommands from "./slash"; @@ -15,58 +16,26 @@ export function slashFromCustomCommand( description: customCommand.description ?? "", prompt: customCommand.prompt, run: async function* ({ input, llm, history, ide, completionOptions }) { - console.log("SLASH COMMAND RUN", input, prompt, commandName); - // Remove slash command prefix from input - let userInput = input; - if (userInput.startsWith(commandName)) { - userInput = userInput.substring(commandName.length).trimStart(); - } - // Render prompt template - let promptUserInput: string; + let renderedPrompt: string; if (customCommand.prompt.includes("{{{ input }}}")) { - promptUserInput = await renderTemplatedString( + renderedPrompt = await renderTemplatedString( customCommand.prompt, ide.readFile.bind(ide), - { input: userInput }, + { input }, ); } else { - promptUserInput = customCommand.prompt + "\n\n" + userInput; + renderedPrompt = customCommand.prompt + "\n\n" + input; } - const messages = [...history]; - // Find the last chat message with this slash command and replace it with the user input - for (let i = messages.length - 1; i >= 0; i--) { - const message = messages[i]; - const { role, content } = message; - if (role !== "user") { - continue; - } - - if ( - Array.isArray(content) && - content.some( - (part) => "text" in part && part.text?.startsWith(commandName), - ) - ) { - messages[i] = { - ...message, - content: content.map((part) => { - if ("text" in part && part.text.startsWith(commandName)) { - return { type: "text", text: promptUserInput }; - } - return part; - }), - }; - break; - } else if ( - typeof content === "string" && - content.startsWith(commandName) - ) { - messages[i] = { ...message, content: promptUserInput }; - break; - } - } + // Replaces slash command messages with the rendered prompt + // which INCLUDES the input + const messages = replaceSlashCommandWithPromptInChatHistory( + history, + commandName, + renderedPrompt, + undefined, + ); for await (const chunk of llm.streamChat( messages, diff --git a/core/commands/slash/http.ts b/core/commands/slash/http.ts index 7a662561c..1c0d38626 100644 --- a/core/commands/slash/http.ts +++ b/core/commands/slash/http.ts @@ -1,11 +1,11 @@ import { SlashCommand } from "../../index.js"; -import { removeQuotesAndEscapes } from "../../util/index.js"; import { streamResponse } from "../../llm/stream.js"; +import { removeQuotesAndEscapes } from "../../util/index.js"; const HttpSlashCommand: SlashCommand = { name: "http", description: "Call an HTTP endpoint to serve response", - run: async function* ({ ide, llm, input, params, fetch }) { + run: async function* ({ input, params, fetch }) { const url = params?.url; if (!url) { throw new Error("URL is not defined in params"); diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index b9d4e88c8..6abd4927f 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -5,7 +5,7 @@ import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; -import { updateChatHistory } from "./updateChatHistory"; +import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory"; export function extractName(preamble: { name?: string }, path: string): string { return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0]; @@ -68,7 +68,7 @@ export function slashCommandFromPromptFileV1( const userInput = extractUserInput(context.input, name); const renderedPrompt = await renderPromptV1(prompt, context, userInput); - const messages = updateChatHistory( + const messages = replaceSlashCommandWithPromptInChatHistory( context.history, name, renderedPrompt, diff --git a/core/promptFiles/v1/updateChatHistory.ts b/core/promptFiles/v1/updateChatHistory.ts index 8ebc6f038..04cbcd91b 100644 --- a/core/promptFiles/v1/updateChatHistory.ts +++ b/core/promptFiles/v1/updateChatHistory.ts @@ -1,4 +1,4 @@ -export function updateChatHistory( +export function replaceSlashCommandWithPromptInChatHistory( history: any[], commandName: string, renderedPrompt: string, diff --git a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx index 99149ba5f..772777337 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditCard.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditCard.tsx @@ -1,16 +1,16 @@ +import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import type { CodeToEdit } from "core"; import { useContext, useState } from "react"; import { useDispatch } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import CodeToEditListItem from "./CodeToEditListItem"; -import type { CodeToEdit } from "core"; -import AddFileButton from "./AddFileButton"; -import AddFileCombobox from "./AddFileCombobox"; -import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { useAppSelector } from "../../redux/hooks"; import { addCodeToEdit, removeCodeToEdit, } from "../../redux/slices/sessionSlice"; +import AddFileButton from "./AddFileButton"; +import AddFileCombobox from "./AddFileCombobox"; +import CodeToEditListItem from "./CodeToEditListItem"; export default function CodeToEditCard() { const dispatch = useDispatch(); @@ -56,7 +56,7 @@ export default function CodeToEditCard() { return (
-
+
{title} setShowAddFileCombobox(true)} />
diff --git a/gui/src/components/mainInput/tiptap/resolveInput.ts b/gui/src/components/mainInput/tiptap/resolveInput.ts index 427edead1..76a868115 100644 --- a/gui/src/components/mainInput/tiptap/resolveInput.ts +++ b/gui/src/components/mainInput/tiptap/resolveInput.ts @@ -11,7 +11,7 @@ import { TextMessagePart, } from "core"; import { ctxItemToRifWithContents } from "core/commands/util"; -import { stripImages } from "core/util/messageContent"; +import { renderChatMessage, stripImages } from "core/util/messageContent"; import { getUriFileExtension } from "core/util/uri"; import { IIdeMessenger } from "../../../context/IdeMessenger"; import { setIsGatheringContext } from "../../../redux/slices/sessionSlice"; @@ -52,7 +52,7 @@ async function resolveEditorContent({ MessageContent, ( | { - name: string; + command: SlashCommandDescription; input: string; } | undefined @@ -63,8 +63,9 @@ async function resolveEditorContent({ let contextItemAttrs: MentionAttrs[] = []; const selectedCode: RangeInFile[] = []; let slashCommandName: string | undefined = undefined; - let slashCommandWithInput: { name: string; input: string } | undefined = - undefined; + let slashCommandWithInput: + | { command: SlashCommandDescription; input: string } + | undefined = undefined; if (editorState?.content) { for (const p of editorState.content) { if (p.type === "paragraph") { @@ -129,56 +130,34 @@ async function resolveEditorContent({ } } - // Add slash command text back in (this could be removed) if (slashCommandName) { const command = availableSlashCommands.find( - (c) => c.name === slashCommandWithName, + (c) => c.name === slashCommandName, ); if (command) { - slashCommandWithInput = { - name: command.name, - input: "TODO INPUT", - }; - } - } - const getSlashCommandForInput = ( - input: MessageContent, - slashCommands: SlashCommandDescription[], - ): [SlashCommandDescription, string] | undefined => { - let slashCommand: SlashCommandDescription | undefined; - let slashCommandName: string | undefined; - - let lastText = - typeof input === "string" - ? input - : ( - input.filter((part) => part.type === "text").slice(-1)[0] as - | TextMessagePart - | undefined - )?.text || ""; - - if (lastText.startsWith("/")) { - slashCommandName = lastText.split(" ")[0].substring(1); - slashCommand = slashCommands.find((command) => - lastText.startsWith(command), + const lastTextIndex = findLastIndex( + parts, + (part) => part.type === "text", ); - } - if (!slashCommand || !slashCommandName) { - return undefined; - } + const lastTextPart = parts[lastTextIndex] as TextMessagePart; - // Convert to actual slash command object with runnable function - return [slashCommand, renderChatMessage({ role: "user", content: input })]; - }; + let input: string; + // Get input and add text of last slash command text back in to last text node + if (lastTextPart) { + input = renderChatMessage({ + role: "user", + content: lastTextPart.text, + }).trimStart(); + lastTextPart.text = `/${command.name} ${lastTextPart.text}`; + } else { + input = ""; + parts.push({ type: "text", text: `/${command.name}` }); + } - if (slashCommand) { - let lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); - const lastTextPart = parts[lastTextIndex] as TextMessagePart; - const lastPart = `/${slashCommand} ${lastTextPart?.text || ""}`; - if (parts.length > 0) { - lastTextPart.text = lastPart; - } else { - parts = [{ type: "text", text: lastPart }]; + slashCommandWithInput = { + command, + input, + }; } } diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 05c1f2c47..aea4bdadb 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -235,7 +235,8 @@ export function Chat() { console.error("No selected chat model"); return; } - const [contextItems, __, userInstructions] = await resolveEditorContent({ + + const [contextItems, __, userInstructions, _] = await resolveEditorContent({ editorState, modifiers: { noContext: true, @@ -243,6 +244,7 @@ export function Chat() { }, ideMessenger, defaultContextProviders: [], + availableSlashCommands: [], dispatch, selectedModelTitle: defaultModel.title, }); diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 5386881f7..1c38e965b 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -5,6 +5,7 @@ import { InputModifiers, MessageContent, RangeInFile, + SlashCommandDescription, } from "core"; import * as URI from "uri-js"; import resolveEditorContent from "../../components/mainInput/tiptap/resolveInput"; @@ -18,7 +19,7 @@ export const gatherContext = createAsyncThunk< content: MessageContent; slashCommandWithInput: | { - name: string; + command: SlashCommandDescription; input: string; } | undefined; diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index cfdb5a9d2..9b802ffbb 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -94,36 +94,29 @@ export const streamResponseThunk = createAsyncThunk< }); posthog.capture("userInput", {}); - // Determine if the input is a slash command - let commandAndInput = getSlashCommandForInput(content, slashCommands); - - if (!commandAndInput) { - unwrapResult(await dispatch(streamNormalInput({ messages }))); - } else { - const [slashCommand, commandInput] = commandAndInput; - + if (slashCommandWithInput) { posthog.capture("step run", { - step_name: slashCommand.name, + step_name: slashCommandWithInput.command.name, params: {}, }); - - // TODO - handle non-legacy slash commands, update messages if relevant - // Pass around isFromConfigTs - unwrapResult( - await dispatch( - streamNormalInput({ - messages, - legacySlashCommandData: { - command: slashCommand, - contextItems: selectedContextItems, - historyIndex: inputIndex, - input: commandInput, - selectedCode, - }, - }), - ), - ); } + + unwrapResult( + await dispatch( + streamNormalInput({ + messages, + legacySlashCommandData: slashCommandWithInput + ? { + command: slashCommandWithInput.command, + contextItems: selectedContextItems, + historyIndex: inputIndex, + input: slashCommandWithInput.input, + selectedCode, + } + : undefined, + }), + ), + ); }), ); },