promptv1 render tests
This commit is contained in:
parent
3dfaa790f0
commit
0cbd7e110c
11 changed files with 1026 additions and 389 deletions
|
|
@ -16,7 +16,7 @@ export function rifWithContentsToContextItem(
|
|||
return {
|
||||
content: rif.contents,
|
||||
name: `${basename} ${rangeStr}`,
|
||||
description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
|
||||
description: `${relativePathOrBasename} ${rangeStr}`,
|
||||
id: {
|
||||
providerTitle: "code",
|
||||
itemId: uuidv4(),
|
||||
|
|
|
|||
|
|
@ -90,7 +90,7 @@ export async function prepareTemplatedFilepaths(
|
|||
}
|
||||
} catch (e) {
|
||||
console.error(`Error reading file in prompt file ${filepath}:`, e);
|
||||
templateData[letter] = `[Error reading file ${filepath}]`;
|
||||
templateData[letter] = `[Error reading file "${filepath}"]`;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,536 @@
|
|||
import { JSONContent } from "@tiptap/react";
|
||||
import { ContextItemWithId } from "core";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { processEditorContent } from "./processEditorContent";
|
||||
|
||||
describe("processEditorContent", () => {
|
||||
// Create some reusable test data
|
||||
const createContextItem = (
|
||||
content: string,
|
||||
description: string,
|
||||
fileUri?: string,
|
||||
editing?: boolean,
|
||||
): ContextItemWithId => ({
|
||||
id: { providerTitle: "test", itemId: "test-id" },
|
||||
content,
|
||||
description,
|
||||
name: "Test Item",
|
||||
editing,
|
||||
uri: fileUri ? { type: "file", value: fileUri } : undefined,
|
||||
});
|
||||
|
||||
test("processEditorContent should return empty arrays when content is empty", () => {
|
||||
// Empty editor state
|
||||
const emptyEditorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [],
|
||||
};
|
||||
|
||||
const result = processEditorContent(emptyEditorState);
|
||||
|
||||
expect(result.parts).toEqual([]);
|
||||
expect(result.contextRequests).toEqual([]);
|
||||
expect(result.selectedCode).toEqual([]);
|
||||
expect(result.slashCommandName).toBeUndefined();
|
||||
});
|
||||
|
||||
test("processEditorContent should process text paragraphs", () => {
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Hello world",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "This is another paragraph",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Hello world\nThis is another paragraph",
|
||||
},
|
||||
]);
|
||||
expect(result.contextRequests).toEqual([]);
|
||||
expect(result.selectedCode).toEqual([]);
|
||||
});
|
||||
|
||||
test("processEditorContent should detect slash commands", () => {
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "prompt-block",
|
||||
attrs: {
|
||||
item: {
|
||||
name: "test-command",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Some text after the prompt",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
expect(result.slashCommandName).toBe("test-command");
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Some text after the prompt",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("processEditorContent should handle mentions and collect context requests", () => {
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Hello ",
|
||||
},
|
||||
{
|
||||
type: "mention",
|
||||
attrs: {
|
||||
id: "fileSearch",
|
||||
label: "@fileSearch",
|
||||
itemType: "contextProvider",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: " and also ",
|
||||
},
|
||||
{
|
||||
type: "mention",
|
||||
attrs: {
|
||||
id: "github",
|
||||
label: "@github",
|
||||
itemType: "contextProvider",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Hello @fileSearch and also @github",
|
||||
},
|
||||
]);
|
||||
expect(result.contextRequests).toEqual([
|
||||
{ provider: "fileSearch" },
|
||||
{ provider: "github" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("processEditorContent should handle code blocks", () => {
|
||||
const codeItem = createContextItem(
|
||||
"function test() {\n return 'hello';\n}",
|
||||
"a description",
|
||||
"file:///example.js",
|
||||
);
|
||||
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Check this code:",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "code-block",
|
||||
attrs: {
|
||||
item: codeItem,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Check this code:\n\n```js example.js\nfunction test() {\n return 'hello';\n}\n```\n",
|
||||
},
|
||||
]);
|
||||
expect(result.selectedCode).toHaveLength(1);
|
||||
expect(result.selectedCode[0].filepath).toBe("file:///example.js");
|
||||
});
|
||||
|
||||
test("processEditorContent should not include editing code blocks in the text", () => {
|
||||
const editingCodeItem = createContextItem(
|
||||
"function test() {\n return 'hello';\n}",
|
||||
"a description",
|
||||
"file:///editing.js",
|
||||
true, // Set editing to true
|
||||
);
|
||||
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Edit this code:",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "code-block",
|
||||
attrs: {
|
||||
item: editingCodeItem,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
// The code block should not be included in parts because it's marked as editing
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Edit this code:",
|
||||
},
|
||||
]);
|
||||
|
||||
// But it should still be in selectedCode
|
||||
expect(result.selectedCode).toHaveLength(1);
|
||||
expect(result.selectedCode[0].filepath).toBe("file:///editing.js");
|
||||
});
|
||||
|
||||
test("processEditorContent should handle images", () => {
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Here's an image:",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
attrs: {
|
||||
src: "https://example.com/image.png",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Here's an image:",
|
||||
},
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: "https://example.com/image.png" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("processEditorContent should handle complex content with multiple elements", () => {
|
||||
const codeItem = createContextItem(
|
||||
"const x = 42;",
|
||||
"a description",
|
||||
"file:///script.ts",
|
||||
);
|
||||
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "prompt-block",
|
||||
attrs: {
|
||||
item: {
|
||||
name: "explain",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Please explain this code and also check ",
|
||||
},
|
||||
{
|
||||
type: "mention",
|
||||
attrs: {
|
||||
id: "related",
|
||||
label: "@related",
|
||||
itemType: "similarFiles",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "code-block",
|
||||
attrs: {
|
||||
item: codeItem,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "What does this constant do?",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
attrs: {
|
||||
src: "https://example.com/diagram.png",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
expect(result.slashCommandName).toBe("explain");
|
||||
expect(result.contextRequests).toEqual([{ provider: "similarFiles" }]);
|
||||
expect(result.selectedCode).toHaveLength(1);
|
||||
expect(result.selectedCode[0].filepath).toBe("file:///script.ts");
|
||||
|
||||
// `\n\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`;
|
||||
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Please explain this code and also check @related\n\n```ts script.ts\nconst x = 42;\n```\n\nWhat does this constant do?",
|
||||
},
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: "https://example.com/diagram.png" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("processEditorContent should merge consecutive text parts", () => {
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "First paragraph",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Second paragraph",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
attrs: {
|
||||
src: "https://example.com/image.png",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Third paragraph",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
// First two paragraphs should be merged, but the third should be separate
|
||||
// because there's an image in between
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "First paragraph\nSecond paragraph",
|
||||
},
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: "https://example.com/image.png" },
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Third paragraph",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("processEditorContent should handle unexpected content types gracefully", () => {
|
||||
// Testing with an unknown node type
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Normal text",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "unknown-type", // This type doesn't exist
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "This should be ignored",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Spy on console.warn to verify it's called
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
// Only the normal paragraph should be processed
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Normal text",
|
||||
},
|
||||
]);
|
||||
|
||||
// Console.warn should be called for the unknown type
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
"Unexpected content type",
|
||||
"unknown-type",
|
||||
);
|
||||
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("processEditorContent should handle missing attrs in code blocks", () => {
|
||||
// Testing with a code block that has no item attribute
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "code-block",
|
||||
// Missing attrs property
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Spy on console.warn to verify it's called
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
// No parts should be created
|
||||
expect(result.parts).toEqual([]);
|
||||
expect(result.selectedCode).toEqual([]);
|
||||
|
||||
// Console.warn should be called for the missing item attribute
|
||||
expect(warnSpy).toHaveBeenCalledWith("codeBlock has no item attribute");
|
||||
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("processEditorContent should handle paragraphs with unexpected child types", () => {
|
||||
// Testing with a paragraph that has an unknown child type
|
||||
const editorState: JSONContent = {
|
||||
type: "doc",
|
||||
content: [
|
||||
{
|
||||
type: "paragraph",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Normal text ",
|
||||
},
|
||||
{
|
||||
type: "unknown-child", // This type doesn't exist
|
||||
text: "This should be ignored",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Spy on console.warn to verify it's called
|
||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
|
||||
const result = processEditorContent(editorState);
|
||||
|
||||
// Only the normal text should be processed
|
||||
expect(result.parts).toEqual([
|
||||
{
|
||||
type: "text",
|
||||
text: "Normal text ",
|
||||
},
|
||||
]);
|
||||
|
||||
// Console.warn should be called for the unknown child type
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
"Unexpected child type",
|
||||
"unknown-child",
|
||||
);
|
||||
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
import Image from "@tiptap/extension-image";
|
||||
import { Paragraph } from "@tiptap/extension-paragraph";
|
||||
import { Text } from "@tiptap/extension-text";
|
||||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
MessagePart,
|
||||
RangeInFile,
|
||||
TextMessagePart,
|
||||
} from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { getUriDescription } from "core/util/uri";
|
||||
import { CodeBlock, Mention, PromptBlock } from "../extensions";
|
||||
import { GetContextRequest } from "./types";
|
||||
|
||||
interface MentionAttrs {
|
||||
label: string;
|
||||
id: string;
|
||||
itemType?: string;
|
||||
query?: string;
|
||||
}
|
||||
|
||||
function resolvePromptBlock(p: JSONContent): string | undefined {
|
||||
return p.attrs?.item.name;
|
||||
}
|
||||
|
||||
function resolveParagraph(p: JSONContent): [string, GetContextRequest[]] {
|
||||
const contextRequests: GetContextRequest[] = [];
|
||||
|
||||
const text = (p.content || [])
|
||||
.map((child) => {
|
||||
switch (child.type) {
|
||||
case Text.name:
|
||||
return child.text;
|
||||
case Mention.name:
|
||||
const attrs = child.attrs as MentionAttrs;
|
||||
contextRequests.push({
|
||||
provider:
|
||||
attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!,
|
||||
});
|
||||
return child.attrs?.renderInlineAs ?? child.attrs?.label;
|
||||
|
||||
default:
|
||||
console.warn("Unexpected child type", child.type);
|
||||
return "";
|
||||
}
|
||||
})
|
||||
.join("")
|
||||
.trimStart();
|
||||
|
||||
return [text, contextRequests];
|
||||
}
|
||||
|
||||
export function processEditorContent(editorState: JSONContent) {
|
||||
const contextRequests: GetContextRequest[] = [];
|
||||
const selectedCode: RangeInFile[] = [];
|
||||
let slashCommandName: string | undefined;
|
||||
|
||||
const parts: MessagePart[] = [];
|
||||
for (const p of editorState?.content || []) {
|
||||
switch (p.type) {
|
||||
case PromptBlock.name:
|
||||
slashCommandName = resolvePromptBlock(p);
|
||||
break;
|
||||
case Paragraph.name:
|
||||
const [text, ctxItems] = resolveParagraph(p);
|
||||
|
||||
contextRequests.push(...ctxItems);
|
||||
|
||||
if (text) {
|
||||
// Merge with previous text part if possible
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
} else {
|
||||
parts.push({ type: "text", text });
|
||||
}
|
||||
}
|
||||
break;
|
||||
case CodeBlock.name:
|
||||
if (!p.attrs?.item) {
|
||||
console.warn("codeBlock has no item attribute");
|
||||
break;
|
||||
}
|
||||
|
||||
const contextItem = p.attrs.item as ContextItemWithId;
|
||||
const rif = ctxItemToRifWithContents(contextItem, true);
|
||||
selectedCode.push(rif);
|
||||
|
||||
// If editing, only include in selectedCode
|
||||
if (contextItem.editing) {
|
||||
break;
|
||||
}
|
||||
|
||||
const { extension, relativePathOrBasename } = getUriDescription(
|
||||
rif.filepath,
|
||||
window.workspacePaths ?? [],
|
||||
);
|
||||
const codeText = `\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`;
|
||||
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + codeText;
|
||||
} else {
|
||||
parts.push({ type: "text", text: codeText });
|
||||
}
|
||||
break;
|
||||
case Image.name:
|
||||
parts.push({
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: p.attrs?.src },
|
||||
});
|
||||
break;
|
||||
default: {
|
||||
console.warn("Unexpected content type", p.type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { parts, contextRequests, selectedCode, slashCommandName };
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
import { SlashCommandDescWithSource } from "core";
|
||||
import { beforeEach, describe, it, vi } from "vitest";
|
||||
import {
|
||||
MockIdeMessenger,
|
||||
MockResponseHandler,
|
||||
} from "../../../../context/MockIdeMessenger";
|
||||
import { getRenderedV1Prompt } from "./renderPromptv1";
|
||||
|
||||
function getTestPromptV1Command(body: string): SlashCommandDescWithSource {
|
||||
return {
|
||||
prompt: body,
|
||||
name: "test-prompt-name",
|
||||
description: "test-prompt-description",
|
||||
isLegacy: false,
|
||||
source: "prompt-file-v1",
|
||||
};
|
||||
}
|
||||
describe("get rendered v1 prompt file", () => {
|
||||
const ideMessenger = new MockIdeMessenger();
|
||||
const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? "";
|
||||
const customGetContextItems: MockResponseHandler<
|
||||
"context/getContextItems"
|
||||
> = async ({ name }) => {
|
||||
if (name === "diff") {
|
||||
return [
|
||||
{
|
||||
id: {
|
||||
itemId: "id",
|
||||
providerTitle: "diff",
|
||||
},
|
||||
name: "name",
|
||||
description: "description",
|
||||
content: "Diff provider content",
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
ideMessenger.resetMocks();
|
||||
});
|
||||
|
||||
it("should render a prompt file with no attachments or templated input", async () => {
|
||||
const rawContent = "Simple prompt with no attachments";
|
||||
const command = getTestPromptV1Command(rawContent);
|
||||
const rendered = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
"User input",
|
||||
[],
|
||||
);
|
||||
expect(rendered).toBe("Simple prompt with no attachments\n\nUser input");
|
||||
});
|
||||
|
||||
it("should render a prompt file templated input", async () => {
|
||||
const rawContent = "{{{ input }}} Simple prompt with no attachments";
|
||||
const command = getTestPromptV1Command(rawContent);
|
||||
const rendered = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
"User input",
|
||||
[],
|
||||
);
|
||||
expect(rendered).toBe("User input Simple prompt with no attachments");
|
||||
});
|
||||
|
||||
it("Should handle file attachments", async () => {
|
||||
ideMessenger.responses["readFile"] = "Test file content";
|
||||
const rawContent = "Content with URL {{{ testFile.txt }}}";
|
||||
const command = getTestPromptV1Command(rawContent);
|
||||
const rendered = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
"User input",
|
||||
[],
|
||||
);
|
||||
expect(rendered).toBe("Content with URL Test file content\n\nUser input");
|
||||
});
|
||||
|
||||
it("should handle supported providers", async () => {
|
||||
ideMessenger.responseHandlers["context/getContextItems"] =
|
||||
customGetContextItems;
|
||||
const rawContent = "Tell me about {{{ diff }}} please";
|
||||
const command = getTestPromptV1Command(rawContent);
|
||||
const rendered = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
"User input",
|
||||
[],
|
||||
);
|
||||
expect(rendered).toBe(
|
||||
"Tell me about Diff provider content please\n\nUser input",
|
||||
);
|
||||
});
|
||||
|
||||
it("should render file read errors within prompt", async () => {
|
||||
ideMessenger.responses["fileExists"] = false;
|
||||
const rawContent = "Content with provider {{{ nonexistent }}}";
|
||||
const command = getTestPromptV1Command(rawContent);
|
||||
const rendered = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
"User input",
|
||||
[],
|
||||
);
|
||||
expect(rendered).toBe(
|
||||
`Content with provider [Error reading file "nonexistent"]\n\nUser input`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiple attachments", async () => {
|
||||
ideMessenger.responseHandlers["context/getContextItems"] =
|
||||
customGetContextItems;
|
||||
ideMessenger.responses["readFile"] = "Test file content";
|
||||
const rawContent = "Content with {{{ diff }}} and {{{ file.txt }}}";
|
||||
const command = getTestPromptV1Command(rawContent);
|
||||
const rendered = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
"User input",
|
||||
[],
|
||||
);
|
||||
expect(rendered).toBe(
|
||||
"Content with Diff provider content and Test file content\n\nUser input",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -30,7 +30,9 @@ export async function getRenderedV1Prompt(
|
|||
if (response.status === "success") {
|
||||
return response.content.map((item) => item.content).join("\n\n");
|
||||
} else {
|
||||
throw new Error(`Failed to get context items from provider: ${name}`);
|
||||
throw new Error(
|
||||
`Failed to get context items from provider "${name}": ${response.error}`,
|
||||
);
|
||||
}
|
||||
},
|
||||
],
|
||||
|
|
@ -40,7 +42,7 @@ export async function getRenderedV1Prompt(
|
|||
return resolveRelativePathInDir(path, ideMessenger.ide, workspaceDirs);
|
||||
};
|
||||
const handlebars = await import("handlebars");
|
||||
return await renderTemplatedString(
|
||||
let rendered = await renderTemplatedString(
|
||||
handlebars,
|
||||
command.prompt,
|
||||
{ input: userInput },
|
||||
|
|
@ -48,4 +50,9 @@ export async function getRenderedV1Prompt(
|
|||
ideMessenger.ide.readFile.bind(ideMessenger.ide),
|
||||
getUriFromPath,
|
||||
);
|
||||
// For prompt file append the input if it isn't rendered
|
||||
if (!rendered.includes(userInput)) {
|
||||
rendered = rendered + `\n\n${userInput}`;
|
||||
}
|
||||
return rendered.trim();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { SlashCommandDescWithSource } from "core";
|
||||
import { setUpTestDir, tearDownTestDir } from "core/test/testDir";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { IdeMessenger, IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MockIdeMessenger } from "../../../../context/MockIdeMessenger";
|
||||
import { getPromptV2ContextRequests } from "./renderPromptv2";
|
||||
|
||||
function getTestPromptV2Command(body: string): SlashCommandDescWithSource {
|
||||
|
|
@ -14,116 +13,68 @@ function getTestPromptV2Command(body: string): SlashCommandDescWithSource {
|
|||
};
|
||||
}
|
||||
describe("getPromptV2ContextRequests", () => {
|
||||
let ideMessenger: IIdeMessenger;
|
||||
const mockGetContextItems = vi.fn().mockResolvedValue([
|
||||
{
|
||||
name: "custom",
|
||||
content: "Custom provider content",
|
||||
description: "Custom provider",
|
||||
},
|
||||
]);
|
||||
const ideMessenger = new MockIdeMessenger();
|
||||
const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? "";
|
||||
beforeEach(async () => {
|
||||
// Mock the ideMessenger
|
||||
vi.clearAllMocks();
|
||||
setUpTestDir();
|
||||
ideMessenger = new IdeMessenger();
|
||||
vi.spyOn(ideMessenger.ide, "readFile").mockImplementation(() => {
|
||||
return Promise.resolve("Example Content");
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
tearDownTestDir();
|
||||
ideMessenger.resetMocks();
|
||||
});
|
||||
|
||||
it("should render a prompt file with no attachments", async () => {
|
||||
const rawContent = "Simple prompt with no attachments";
|
||||
const command = getTestPromptV2Command(rawContent);
|
||||
const requests = await getPromptV2ContextRequests(ideMessenger, command);
|
||||
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
// it("should handle URL attachments", async () => {
|
||||
// const rawContent = "Content with URL @https://example.com";
|
||||
it("should handle URL attachments", async () => {
|
||||
const rawContent = "Content with URL @https://example.com";
|
||||
const command = getTestPromptV2Command(rawContent);
|
||||
const requests = await getPromptV2ContextRequests(ideMessenger, command);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].provider).toBe("url");
|
||||
expect(requests[0].query).toBe("https://example.com");
|
||||
});
|
||||
|
||||
// const [contextItems, renderedPrompt] = await getPromptV2ContextAttrs(
|
||||
// rawContent,
|
||||
// extras,
|
||||
// );
|
||||
it("should resolve file attachments", async () => {
|
||||
const rawContent = "Content with file attachment @test.txt";
|
||||
const command = getTestPromptV2Command(rawContent);
|
||||
const requests = await getPromptV2ContextRequests(ideMessenger, command);
|
||||
|
||||
// expect(contextItems).toHaveLength(1);
|
||||
// expect(renderedPrompt).toContain("Example Content");
|
||||
// });
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(requests[0].provider).toBe("file");
|
||||
expect(requests[0].query).toBe(`${firstDir}/test.txt`);
|
||||
});
|
||||
|
||||
// it("should resolve file attachments", async () => {
|
||||
// const rawContent = "Content with file attachment @test.txt";
|
||||
it("should handle nested prompt files", async () => {
|
||||
ideMessenger.responses["readFile"] = "Contents @myfile.txt";
|
||||
const rawContent = "Main prompt with nested @test.prompt";
|
||||
const command = getTestPromptV2Command(rawContent);
|
||||
const requests = await getPromptV2ContextRequests(ideMessenger, command);
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(requests[0].provider).toBe("file");
|
||||
expect(requests[0].query).toBe(`${firstDir}/myfile.txt`);
|
||||
expect(requests[1].provider).toBe("file");
|
||||
expect(requests[1].query).toBe(`${firstDir}/test.prompt`);
|
||||
});
|
||||
|
||||
// addToTestDir([["test.txt", "File content"]]);
|
||||
it("should ignore unsupported providers", async () => {
|
||||
ideMessenger.responses["fileExists"] = false;
|
||||
const rawContent = "Content with custom provider @unsupported";
|
||||
const command = getTestPromptV2Command(rawContent);
|
||||
const requests = await getPromptV2ContextRequests(ideMessenger, command);
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
// const [contextItems, renderedPrompt] = await getPromptV2ContextAttrs(
|
||||
// rawContent,
|
||||
// extras,
|
||||
// );
|
||||
it("should handle multiple attachments", async () => {
|
||||
const rawContent = "Content with @file1.txt and @file2.txt";
|
||||
const command = getTestPromptV2Command(rawContent);
|
||||
const requests = await getPromptV2ContextRequests(ideMessenger, command);
|
||||
|
||||
// expect(contextItems).toHaveLength(1);
|
||||
// expect(renderedPrompt).toContain("```test.txt\nFile content\n```");
|
||||
// expect(renderedPrompt).toContain("Content with file attachment @test.txt");
|
||||
// });
|
||||
|
||||
// it("should handle nested prompt files", async () => {
|
||||
// const rawContent = "Main prompt with nested @nested.prompt";
|
||||
// addToTestDir([
|
||||
// ["nested.prompt", "Nested prompt content with @CustomProvider"],
|
||||
// ]);
|
||||
|
||||
// const [contextItems, renderedPrompt] = await getPromptV2ContextAttrs(
|
||||
// rawContent,
|
||||
// extras,
|
||||
// );
|
||||
|
||||
// expect(renderedPrompt).toContain("Custom provider content");
|
||||
// });
|
||||
|
||||
// it("should handle custom context providers", async () => {
|
||||
// const rawContent = "Content with custom provider @CustomProvider";
|
||||
|
||||
// const [contextItems, renderedPrompt] = await getPromptV2ContextAttrs(
|
||||
// rawContent,
|
||||
// extras,
|
||||
// );
|
||||
|
||||
// expect(contextItems).toHaveLength(1);
|
||||
// expect(renderedPrompt).toContain("Custom provider content");
|
||||
// expect(mockGetContextItems).toHaveBeenCalled();
|
||||
// });
|
||||
|
||||
// it("should handle multiple attachments", async () => {
|
||||
// const rawContent = "Content with @file1.txt and @file2.txt";
|
||||
// addToTestDir([
|
||||
// ["file1.txt", "Content 1"],
|
||||
// ["file2.txt", "Content 2"],
|
||||
// ]);
|
||||
|
||||
// const [contextItems, renderedPrompt] = await getPromptV2ContextAttrs(
|
||||
// rawContent,
|
||||
// extras,
|
||||
// );
|
||||
|
||||
// expect(contextItems).toHaveLength(2);
|
||||
// expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```");
|
||||
// expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```");
|
||||
// });
|
||||
|
||||
// it("should handle failed attachment resolutions gracefully", async () => {
|
||||
// const rawContent = "Content with @nonexistent";
|
||||
|
||||
// const [contextItems, renderedPrompt] = await getPromptV2ContextAttrs(
|
||||
// rawContent,
|
||||
// extras,
|
||||
// );
|
||||
|
||||
// expect(contextItems).toHaveLength(0);
|
||||
// expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input");
|
||||
// });
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(requests[0].provider).toBe("file");
|
||||
expect(requests[0].query).toBe(`${firstDir}/file1.txt`);
|
||||
expect(requests[1].provider).toBe("file");
|
||||
expect(requests[1].query).toBe(`${firstDir}/file2.txt`);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ export async function getPromptV2ContextRequests(
|
|||
|
||||
// Files
|
||||
const resolvedFileUri = await resolveRelativePathInDir(
|
||||
match[0],
|
||||
match[1],
|
||||
ideMessenger.ide,
|
||||
workspaceDirs,
|
||||
);
|
||||
|
|
@ -54,10 +54,11 @@ export async function getPromptV2ContextRequests(
|
|||
return [];
|
||||
}
|
||||
visitedFiles.add(resolvedFileUri);
|
||||
// As well as any context providers it references
|
||||
await addContextRequestsRecursive(contents);
|
||||
}
|
||||
contextRequests.push({
|
||||
provider: name,
|
||||
provider: "file",
|
||||
query: resolvedFileUri,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,155 @@
|
|||
import { MessagePart, RangeInFile, SlashCommandDescWithSource } from "core";
|
||||
import { stripImages } from "core/util/messageContent";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { getRenderedV1Prompt } from "./renderPromptv1";
|
||||
import { getPromptV2ContextRequests } from "./renderPromptv2";
|
||||
import { GetContextRequest } from "./types";
|
||||
|
||||
/*
|
||||
Slash commands can come from many sources. Render based on the source.
|
||||
*/
|
||||
export async function renderSlashCommandPrompt(
|
||||
ideMessenger: IIdeMessenger,
|
||||
commandName: string | undefined,
|
||||
parts: MessagePart[],
|
||||
availableSlashCommands: SlashCommandDescWithSource[],
|
||||
selectedCode: RangeInFile[],
|
||||
): Promise<{
|
||||
slashedParts: MessagePart[];
|
||||
legacyCommandWithInput?: {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
};
|
||||
contextRequests: GetContextRequest[];
|
||||
}> {
|
||||
const NO_COMMAND = {
|
||||
slashedParts: parts,
|
||||
legacyCommandWithInput: undefined,
|
||||
contextRequests: [],
|
||||
};
|
||||
if (!commandName) {
|
||||
return NO_COMMAND;
|
||||
}
|
||||
const command = availableSlashCommands.find((c) => c.name === commandName);
|
||||
if (!command) {
|
||||
return NO_COMMAND;
|
||||
}
|
||||
|
||||
const nonTextParts = parts.filter((part) => part.type !== "text");
|
||||
const textParts = parts.filter((part) => part.type === "text");
|
||||
const slashedParts: MessagePart[] = [...nonTextParts];
|
||||
|
||||
const userInput = stripImages(textParts).trimStart();
|
||||
|
||||
const legacyCommandWithInput = command.isLegacy
|
||||
? {
|
||||
command,
|
||||
input: userInput,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const contextRequests: GetContextRequest[] = [];
|
||||
|
||||
switch (command.source) {
|
||||
case "built-in-legacy":
|
||||
case "config-ts-slash-command":
|
||||
/**
|
||||
* For legacy slash commands, we simply insert the text "/{name}" in front of the message
|
||||
* And then parsing for this is done in core
|
||||
*/
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: `/${command.name}${command.prompt ? " " + command.prompt : ""}${userInput ? " " + userInput : ""}`,
|
||||
});
|
||||
break;
|
||||
case "mcp-prompt":
|
||||
// TODO add support for mcp prompt args using command.mcpArgs
|
||||
const args: { [key: string]: string } = {};
|
||||
if (command.mcpArgs) {
|
||||
command.mcpArgs.forEach((arg, i) => {
|
||||
args[arg.name] = "";
|
||||
});
|
||||
}
|
||||
const response = await ideMessenger.request("mcp/getPrompt", {
|
||||
serverName: command.mcpServerName!,
|
||||
promptName: command.name,
|
||||
args: args,
|
||||
});
|
||||
if (response.status === "success") {
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: `${response.content.prompt}${userInput ? "\n\n" + userInput : ""}`,
|
||||
});
|
||||
} else {
|
||||
throw new Error(
|
||||
`Failed to get MCP prompt for slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
case "prompt-file-v1":
|
||||
case "prompt-file-v2":
|
||||
case "yaml-prompt-block":
|
||||
if (!command.prompt) {
|
||||
console.warn(`Invalid/empty prompt from slash command ${command.name}`);
|
||||
break;
|
||||
}
|
||||
let renderedPrompt: string;
|
||||
if (
|
||||
command.source === "prompt-file-v1" ||
|
||||
command.prompt.includes("{{{ input }}}")
|
||||
) {
|
||||
renderedPrompt = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
userInput,
|
||||
selectedCode,
|
||||
);
|
||||
} else {
|
||||
const promptFileCtxRequests = await getPromptV2ContextRequests(
|
||||
ideMessenger,
|
||||
command,
|
||||
);
|
||||
contextRequests.push(...promptFileCtxRequests);
|
||||
renderedPrompt = [command.prompt, userInput].join("\n\n");
|
||||
}
|
||||
|
||||
if (renderedPrompt) {
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: renderedPrompt.trim(), // Includes user input
|
||||
});
|
||||
} else {
|
||||
console.warn(
|
||||
`Invalid/empty prompt + input from slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
case "built-in":
|
||||
case "invokable-rule":
|
||||
case "json-custom-command":
|
||||
if (!command.prompt) {
|
||||
console.warn(`Slash command ${command.name} is missing prompt`);
|
||||
break;
|
||||
}
|
||||
const rendered =
|
||||
`${command.prompt}${userInput ? "\n\n" + userInput : ""}`.trim();
|
||||
if (rendered) {
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: rendered,
|
||||
});
|
||||
} else {
|
||||
console.warn(
|
||||
`Invalid/empty prompt + input from slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return {
|
||||
slashedParts,
|
||||
legacyCommandWithInput,
|
||||
contextRequests,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,7 +1,4 @@
|
|||
import { Dispatch } from "@reduxjs/toolkit";
|
||||
import Image from "@tiptap/extension-image";
|
||||
import { Paragraph } from "@tiptap/extension-paragraph";
|
||||
import { Text } from "@tiptap/extension-text";
|
||||
import { JSONContent } from "@tiptap/react";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
|
|
@ -11,25 +8,14 @@ import {
|
|||
MessagePart,
|
||||
RangeInFile,
|
||||
SlashCommandDescWithSource,
|
||||
TextMessagePart,
|
||||
} from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { stripImages } from "core/util/messageContent";
|
||||
import { getUriFileExtension } from "core/util/uri";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice";
|
||||
import { CodeBlock, Mention, PromptBlock } from "../extensions";
|
||||
import { getRenderedV1Prompt } from "./renderPromptv1";
|
||||
import { getPromptV2ContextRequests } from "./renderPromptv2";
|
||||
import { processEditorContent } from "./processEditorContent";
|
||||
import { renderSlashCommandPrompt } from "./renderSlashCommand";
|
||||
import { GetContextRequest } from "./types";
|
||||
|
||||
interface MentionAttrs {
|
||||
label: string;
|
||||
id: string;
|
||||
itemType?: string;
|
||||
query?: string;
|
||||
}
|
||||
|
||||
interface ResolveEditorContentInput {
|
||||
editorState: JSONContent;
|
||||
modifiers: InputModifiers;
|
||||
|
|
@ -115,243 +101,6 @@ export async function resolveEditorContent({
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes editor content and extracts parts, context items, code, and slash commands
|
||||
*/
|
||||
function processEditorContent(editorState: JSONContent) {
|
||||
const contextRequests: GetContextRequest[] = [];
|
||||
const selectedCode: RangeInFile[] = [];
|
||||
let slashCommandName: string | undefined;
|
||||
|
||||
const parts = (editorState?.content || []).reduce<MessagePart[]>(
|
||||
(parts, p) => {
|
||||
switch (p.type) {
|
||||
case PromptBlock.name: {
|
||||
slashCommandName = resvolePromptBlock(p);
|
||||
}
|
||||
|
||||
case Paragraph.name: {
|
||||
const [text, ctxItems] = resolveParagraph(p);
|
||||
|
||||
contextRequests.push(...ctxItems);
|
||||
|
||||
if (!text) return parts;
|
||||
|
||||
// Merge with previous text part if possible
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
return parts;
|
||||
}
|
||||
|
||||
return [...parts, { type: "text", text }];
|
||||
}
|
||||
|
||||
case CodeBlock.name: {
|
||||
if (!p.attrs?.item) {
|
||||
console.warn("codeBlock has no item attribute");
|
||||
return parts;
|
||||
}
|
||||
|
||||
const contextItem = p.attrs.item as ContextItemWithId;
|
||||
const rif = ctxItemToRifWithContents(contextItem, true);
|
||||
selectedCode.push(rif);
|
||||
|
||||
// If editing, only include in selectedCode
|
||||
if (contextItem.editing) {
|
||||
return parts;
|
||||
}
|
||||
|
||||
const fileExtension = getUriFileExtension(rif.filepath);
|
||||
const codeText = [
|
||||
"\n\n```",
|
||||
fileExtension,
|
||||
" ",
|
||||
contextItem.description,
|
||||
"\n",
|
||||
contextItem.content,
|
||||
"\n```",
|
||||
].join("");
|
||||
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
(parts[parts.length - 1] as TextMessagePart).text +=
|
||||
"\n" + codeText;
|
||||
return parts;
|
||||
}
|
||||
|
||||
return [...parts, { type: "text", text: codeText }];
|
||||
}
|
||||
|
||||
case Image.name: {
|
||||
return [
|
||||
...parts,
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: p.attrs?.src },
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
default: {
|
||||
console.warn("Unexpected content type", p.type);
|
||||
return parts;
|
||||
}
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return { parts, contextRequests, selectedCode, slashCommandName };
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes slash commands and prepares the command with input
|
||||
*/
|
||||
async function renderSlashCommandPrompt(
|
||||
ideMessenger: IIdeMessenger,
|
||||
commandName: string | undefined,
|
||||
parts: MessagePart[],
|
||||
availableSlashCommands: SlashCommandDescWithSource[],
|
||||
selectedCode: RangeInFile[],
|
||||
): Promise<{
|
||||
slashedParts: MessagePart[];
|
||||
legacyCommandWithInput?: {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
};
|
||||
contextRequests: GetContextRequest[];
|
||||
}> {
|
||||
const NO_COMMAND = {
|
||||
slashedParts: parts,
|
||||
legacyCommandWithInput: undefined,
|
||||
contextRequests: [],
|
||||
};
|
||||
if (!commandName) {
|
||||
return NO_COMMAND;
|
||||
}
|
||||
const command = availableSlashCommands.find((c) => c.name === commandName);
|
||||
if (!command) {
|
||||
return NO_COMMAND;
|
||||
}
|
||||
|
||||
const nonTextParts = parts.filter((part) => part.type !== "text");
|
||||
const textParts = parts.filter((part) => part.type === "text");
|
||||
const slashedParts: MessagePart[] = [...nonTextParts];
|
||||
|
||||
const userInput = stripImages(textParts).trimStart();
|
||||
|
||||
const legacyCommandWithInput = command.isLegacy
|
||||
? {
|
||||
command,
|
||||
input: userInput,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const contextRequests: GetContextRequest[] = [];
|
||||
|
||||
switch (command.source) {
|
||||
case "built-in-legacy":
|
||||
case "config-ts-slash-command":
|
||||
/**
|
||||
* For legacy slash commands, we simply insert the text "/{name}" in front of the message
|
||||
* And then parsing for this is done in core
|
||||
*/
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: `/${command.name}${command.prompt ? " " + command.prompt : ""}${userInput ? " " + userInput : ""}`,
|
||||
});
|
||||
break;
|
||||
case "mcp-prompt":
|
||||
// TODO add support for mcp prompt args using command.mcpArgs
|
||||
const args: { [key: string]: string } = {};
|
||||
if (command.mcpArgs) {
|
||||
command.mcpArgs.forEach((arg, i) => {
|
||||
args[arg.name] = "";
|
||||
});
|
||||
}
|
||||
const response = await ideMessenger.request("mcp/getPrompt", {
|
||||
serverName: command.mcpServerName!,
|
||||
promptName: command.name,
|
||||
args: args,
|
||||
});
|
||||
if (response.status === "success") {
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: `${response.content.prompt}${userInput ? "\n\n" + userInput : ""}`,
|
||||
});
|
||||
} else {
|
||||
throw new Error(
|
||||
`Failed to get MCP prompt for slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
case "prompt-file-v1":
|
||||
case "prompt-file-v2":
|
||||
case "yaml-prompt-block":
|
||||
if (!command.prompt) {
|
||||
console.warn(`Invalid/empty prompt from slash command ${command.name}`);
|
||||
break;
|
||||
}
|
||||
let renderedPrompt: string;
|
||||
if (
|
||||
command.source === "prompt-file-v1" ||
|
||||
command.prompt.includes("{{{ input }}}")
|
||||
) {
|
||||
renderedPrompt = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
userInput,
|
||||
selectedCode,
|
||||
);
|
||||
} else {
|
||||
const promptFileCtxRequests = await getPromptV2ContextRequests(
|
||||
ideMessenger,
|
||||
command,
|
||||
);
|
||||
contextRequests.push(...promptFileCtxRequests);
|
||||
renderedPrompt = [command.prompt, userInput].join("\n\n");
|
||||
}
|
||||
|
||||
if (renderedPrompt) {
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: renderedPrompt.trim(), // Includes user input
|
||||
});
|
||||
} else {
|
||||
console.warn(
|
||||
`Invalid/empty prompt + input from slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
case "built-in":
|
||||
case "invokable-rule":
|
||||
case "json-custom-command":
|
||||
if (!command.prompt) {
|
||||
console.warn(`Slash command ${command.name} is missing prompt`);
|
||||
break;
|
||||
}
|
||||
const rendered =
|
||||
`${command.prompt}${userInput ? "\n\n" + userInput : ""}`.trim();
|
||||
if (rendered) {
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: rendered,
|
||||
});
|
||||
} else {
|
||||
console.warn(
|
||||
`Invalid/empty prompt + input from slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return {
|
||||
slashedParts,
|
||||
legacyCommandWithInput,
|
||||
contextRequests,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gathers context items from various sources
|
||||
*/
|
||||
|
|
@ -468,34 +217,3 @@ async function gatherContextItems({
|
|||
);
|
||||
return deduplicatedOutputs;
|
||||
}
|
||||
|
||||
function resvolePromptBlock(p: JSONContent): string | undefined {
|
||||
return p.attrs?.item.name;
|
||||
}
|
||||
|
||||
function resolveParagraph(p: JSONContent): [string, GetContextRequest[]] {
|
||||
const contextRequests: GetContextRequest[] = [];
|
||||
|
||||
const text = (p.content || [])
|
||||
.map((child) => {
|
||||
switch (child.type) {
|
||||
case Text.name:
|
||||
return child.text;
|
||||
case Mention.name:
|
||||
const attrs = child.attrs as MentionAttrs;
|
||||
contextRequests.push({
|
||||
provider:
|
||||
attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!,
|
||||
});
|
||||
return child.attrs?.renderInlineAs ?? child.attrs?.label;
|
||||
|
||||
default:
|
||||
console.warn("Unexpected child type", child.type);
|
||||
return "";
|
||||
}
|
||||
})
|
||||
.join("")
|
||||
.trimStart();
|
||||
|
||||
return [text, contextRequests];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,14 @@ type MockResponses = Partial<{
|
|||
[K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1];
|
||||
}>;
|
||||
|
||||
export type MockResponseHandler<T extends keyof FromWebviewProtocol> = (
|
||||
input: FromWebviewProtocol[T][0],
|
||||
) => Promise<FromWebviewProtocol[T][1]>;
|
||||
|
||||
type MockResponseHandlers = Partial<{
|
||||
[K in keyof FromWebviewProtocol]: MockResponseHandler<K>;
|
||||
}>;
|
||||
|
||||
const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
|
||||
fileExists: true,
|
||||
getCurrentFile: {
|
||||
|
|
@ -66,6 +74,7 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
|
|||
"chatDescriber/describe": "Session summary",
|
||||
applyToFile: undefined,
|
||||
acceptDiff: undefined,
|
||||
readFile: "File contents",
|
||||
};
|
||||
|
||||
const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
|
||||
|
|
@ -119,6 +128,7 @@ export class MockIdeMessenger implements IIdeMessenger {
|
|||
}
|
||||
|
||||
responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
|
||||
responseHandlers: MockResponseHandlers = {};
|
||||
chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
|
||||
chatStreamDelay: number = 0;
|
||||
setChatResponseText(text: string): void {
|
||||
|
|
@ -164,6 +174,14 @@ export class MockIdeMessenger implements IIdeMessenger {
|
|||
messageType: T,
|
||||
data: FromWebviewProtocol[T][0],
|
||||
): Promise<WebviewSingleProtocolMessage<T>> {
|
||||
if (this.responseHandlers[messageType]) {
|
||||
const content = await this.responseHandlers[messageType](data);
|
||||
return {
|
||||
status: "success",
|
||||
content,
|
||||
done: true,
|
||||
};
|
||||
}
|
||||
if (messageType in this.responses) {
|
||||
const content = this.responses[messageType];
|
||||
return {
|
||||
|
|
@ -173,7 +191,10 @@ export class MockIdeMessenger implements IIdeMessenger {
|
|||
};
|
||||
}
|
||||
console.error(messageType);
|
||||
throw new Error("MockIdeMessenger: No response defined for " + messageType);
|
||||
throw new Error(
|
||||
"MockIdeMessenger: No response handler or response defined for " +
|
||||
messageType,
|
||||
);
|
||||
}
|
||||
|
||||
respond<T extends keyof ToWebviewProtocol>(
|
||||
|
|
@ -195,6 +216,7 @@ export class MockIdeMessenger implements IIdeMessenger {
|
|||
|
||||
resetMocks(): void {
|
||||
this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
|
||||
this.responseHandlers = {};
|
||||
this.chatResponse = DEFAULT_CHAT_RESPONSE;
|
||||
this.chatStreamDelay = 0;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue