slash command fixes

This commit is contained in:
Dallin Romney 2025-03-27 15:09:34 -07:00
parent ca085d71d5
commit 7d5eb828f0
9 changed files with 74 additions and 130 deletions

View file

@ -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,

View file

@ -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");

View file

@ -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,

View file

@ -1,4 +1,4 @@
export function updateChatHistory(
export function replaceSlashCommandWithPromptInChatHistory(
history: any[],
commandName: string,
renderedPrompt: string,

View file

@ -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 (
<div className="bg-vsc-editor-background mx-3 flex flex-col rounded-t-lg p-1">
<div className="text-lightgray flex items-center justify-between gap-1.5 py-1.5 pl-3 pr-2 text-xs">
<div className="text-lightgray flex flex-wrap items-center justify-between gap-1.5 py-1.5 pl-3 pr-2 text-xs">
<span>{title}</span>
<AddFileButton onClick={() => setShowAddFileCombobox(true)} />
</div>

View file

@ -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,
};
}
}

View file

@ -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,
});

View file

@ -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;

View file

@ -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,
}),
),
);
}),
);
},