diff --git a/jest.config.mjs b/jest.config.mjs index 2592f3834..88ae0a616 100644 --- a/jest.config.mjs +++ b/jest.config.mjs @@ -8,6 +8,7 @@ export default { moduleNameMapper: { "(.+)\\.js": "$1", + "^ink-testing-library$": "/node_modules/ink-testing-library/build/index.js", }, extensionsToTreatAsEsm: [".ts"], preset: "ts-jest/presets/default-esm", diff --git a/package-lock.json b/package-lock.json index e586d9ea9..18d898342 100644 --- a/package-lock.json +++ b/package-lock.json @@ -40,11 +40,13 @@ "@types/diff": "^7.0.2", "@types/glob": "^8.1.0", "@types/ignore-walk": "^4.0.3", + "@types/ink-testing-library": "^1.0.4", "@types/jest": "^29.5.14", "@types/readline-sync": "^1.4.8", "@types/uuid": "^9.0.8", "conventional-changelog-conventionalcommits": "^9.1.0", "cross-env": "^7.0.3", + "ink-testing-library": "^4.0.0", "jest": "^29.7.0", "semantic-release": "^24.2.7", "ts-jest": "^29.2.3", @@ -2921,6 +2923,25 @@ "@types/node": "*" } }, + "node_modules/@types/ink": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/@types/ink/-/ink-0.5.2.tgz", + "integrity": "sha512-yEuhWTRMXJkIWiaM58c5kuRot5HFccv9kjjgy0fBZG0+tYb+sMBaxHNPVqyZXspGGlmwDOQ1d3BsygWpWlW17w==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/prop-types": "*" + } + }, + "node_modules/@types/ink-testing-library": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@types/ink-testing-library/-/ink-testing-library-1.0.4.tgz", + "integrity": "sha512-ui3mKjA+IBpXuIe1WsSQzU8WwOK2hkIM9O27RUEIMxFEzFesfSPGrlwQV0xYuDjxgSibD8mZGeRG+ruimGM+qg==", + "dev": true, + "dependencies": { + "@types/ink": "^0.5.2" + } + }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", @@ -3029,6 +3050,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "dev": true + }, "node_modules/@types/qs": { "version": "6.9.18", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.18.tgz", @@ -6353,6 +6380,23 @@ } } }, + "node_modules/ink-testing-library": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ink-testing-library/-/ink-testing-library-4.0.0.tgz", + "integrity": "sha512-yF92kj3pmBvk7oKbSq5vEALO//o7Z9Ck/OaLNlkzXNeYdwfpxMQkSowGTFUCS5MSu9bWfSZMewGpp7bFc66D7Q==", + "dev": true, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/react": ">=18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/ink/node_modules/ansi-escapes": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.0.0.tgz", diff --git a/package.json b/package.json index cec771b1d..e7add936a 100644 --- a/package.json +++ b/package.json @@ -59,11 +59,13 @@ "@types/diff": "^7.0.2", "@types/glob": "^8.1.0", "@types/ignore-walk": "^4.0.3", + "@types/ink-testing-library": "^1.0.4", "@types/jest": "^29.5.14", "@types/readline-sync": "^1.4.8", "@types/uuid": "^9.0.8", "conventional-changelog-conventionalcommits": "^9.1.0", "cross-env": "^7.0.3", + "ink-testing-library": "^4.0.0", "jest": "^29.7.0", "semantic-release": "^24.2.7", "ts-jest": "^29.2.3", diff --git a/src/tools.ts b/src/tools.ts index f2aeb341e..24935100a 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -4,7 +4,7 @@ import { extractToolCalls, getToolsDescription, getToolDisplayName, - Tool, + type Tool, } from "./tools/index.js"; // Re-export all tool functionality @@ -13,6 +13,7 @@ export { extractToolCalls, getToolsDescription, getToolDisplayName, - Tool, BUILTIN_TOOLS as tools, }; + +export type { Tool }; diff --git a/src/tools/index.ts b/src/tools/index.ts index 2340b6db3..b413826da 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -5,11 +5,11 @@ import { listFilesTool } from "./listFiles.js"; import { readFileTool } from "./readFile.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; -import { Tool, ToolParameters } from "./types.js"; +import { type Tool, type ToolParameters } from "./types.js"; import { viewDiffTool } from "./viewDiff.js"; import { writeFileTool } from "./writeFile.js"; -export { Tool, ToolParameters }; +export type { Tool, ToolParameters }; export const BUILTIN_TOOLS: Tool[] = [ readFileTool, diff --git a/src/ui/MarkdownRenderer.test.tsx b/src/ui/MarkdownRenderer.test.tsx new file mode 100644 index 000000000..128f78bab --- /dev/null +++ b/src/ui/MarkdownRenderer.test.tsx @@ -0,0 +1,206 @@ +import React from "react"; +import MarkdownRenderer from "./MarkdownRenderer.js"; + +describe("MarkdownRenderer", () => { + // Helper function to simulate calling the component function directly + function renderMarkdown(content: string) { + const component = MarkdownRenderer({ content }); + return (component as any).props.children; + } + + it("renders plain text without formatting", () => { + const result = renderMarkdown("Hello world"); + expect(result).toEqual(["Hello world"]); + }); + + it("renders bold text", () => { + const result = renderMarkdown("This is **bold** text"); + expect(result.length).toBe(3); + expect(result[0]).toBe("This is "); + expect(React.isValidElement(result[1])).toBe(true); + expect((result[1] as any).props.bold).toBe(true); + expect((result[1] as any).props.children).toBe("bold"); + expect(result[2]).toBe(" text"); + }); + + it("renders italic text with asterisks", () => { + const result = renderMarkdown("This is *italic* text"); + expect(result.length).toBe(3); + expect(result[0]).toBe("This is "); + expect(React.isValidElement(result[1])).toBe(true); + expect((result[1] as any).props.italic).toBe(true); + expect((result[1] as any).props.children).toBe("italic"); + expect(result[2]).toBe(" text"); + }); + + it("renders italic text with underscores", () => { + const result = renderMarkdown("This is _italic_ text"); + expect(result.length).toBe(3); + expect(result[0]).toBe("This is "); + expect(React.isValidElement(result[1])).toBe(true); + expect((result[1] as any).props.italic).toBe(true); + expect((result[1] as any).props.children).toBe("italic"); + expect(result[2]).toBe(" text"); + }); + + it("renders strikethrough text", () => { + const result = renderMarkdown("This is ~~strikethrough~~ text"); + expect(result.length).toBe(3); + expect(result[0]).toBe("This is "); + expect(React.isValidElement(result[1])).toBe(true); + expect((result[1] as any).props.strikethrough).toBe(true); + expect((result[1] as any).props.children).toBe("strikethrough"); + expect(result[2]).toBe(" text"); + }); + + it("renders code text", () => { + const result = renderMarkdown("This is `code` text"); + expect(result.length).toBe(3); + expect(result[0]).toBe("This is "); + expect(React.isValidElement(result[1])).toBe(true); + expect((result[1] as any).props.color).toBe("cyan"); + expect((result[1] as any).props.children).toBe("code"); + expect(result[2]).toBe(" text"); + }); + + it("handles empty string", () => { + const result = renderMarkdown(""); + expect(result).toEqual([]); + }); + + it("handles text without formatting", () => { + const result = renderMarkdown("Just plain text"); + expect(result).toEqual(["Just plain text"]); + }); + + it("handles multiple formatting types", () => { + const result = renderMarkdown("**Bold** and *italic*"); + expect(result.length).toBe(3); + expect((result[0] as any).props.bold).toBe(true); + expect((result[0] as any).props.children).toBe("Bold"); + expect(result[1]).toBe(" and "); + expect((result[2] as any).props.italic).toBe(true); + expect((result[2] as any).props.children).toBe("italic"); + }); + + // Test the overlapping pattern handling + it("handles overlapping patterns by prioritizing first match", () => { + const result = renderMarkdown("**bold*italic**"); + // Should now match bold pattern and render "bold*italic" as bold + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.bold).toBe(true); + expect((result[0] as any).props.children).toBe("bold*italic"); + }); + + describe("Heading formatting", () => { + it("renders h1 heading as bold", () => { + const result = renderMarkdown("# Main Title"); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.bold).toBe(true); + expect((result[0] as any).props.children).toBe("Main Title"); + }); + + it("renders h2 heading as bold", () => { + const result = renderMarkdown("## Section Title"); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.bold).toBe(true); + expect((result[0] as any).props.children).toBe("Section Title"); + }); + + it("renders h3 heading as bold", () => { + const result = renderMarkdown("### Subsection"); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.bold).toBe(true); + expect((result[0] as any).props.children).toBe("Subsection"); + }); + + it("renders h6 heading as bold", () => { + const result = renderMarkdown("###### Deep Heading"); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.bold).toBe(true); + expect((result[0] as any).props.children).toBe("Deep Heading"); + }); + + it("handles headings with multiple words", () => { + const result = renderMarkdown( + "# This is a long heading with multiple words" + ); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.bold).toBe(true); + expect((result[0] as any).props.children).toBe( + "This is a long heading with multiple words" + ); + }); + + it("handles mixed content with headings", () => { + const result = renderMarkdown("# Title\nNormal text **bold** text"); + expect(result.length).toBe(4); + expect((result[0] as any).props.bold).toBe(true); + expect((result[0] as any).props.children).toBe("Title"); + expect(result[1]).toBe("\nNormal text "); + expect((result[2] as any).props.bold).toBe(true); + expect((result[2] as any).props.children).toBe("bold"); + expect(result[3]).toBe(" text"); + }); + }); + + describe("Code block formatting", () => { + it("renders code blocks with triple backticks", () => { + const result = renderMarkdown("```\nconst x = 1;\nconsole.log(x);\n```"); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.color).toBe("cyan"); + expect((result[0] as any).props.children).toBe( + "\nconst x = 1;\nconsole.log(x);\n" + ); + }); + + it("renders single line code blocks", () => { + const result = renderMarkdown("```console.log('hello')```"); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.color).toBe("cyan"); + expect((result[0] as any).props.children).toBe("console.log('hello')"); + }); + + it("renders code blocks with language specification", () => { + const result = renderMarkdown("```javascript\nconst x = 1;\n```"); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.color).toBe("cyan"); + expect((result[0] as any).props.children).toBe( + "javascript\nconst x = 1;\n" + ); + }); + + it("handles code blocks mixed with other formatting", () => { + const result = renderMarkdown( + "Here's some code:\n```\nfunction test() {\n return 42;\n}\n```\nAnd **bold** text" + ); + expect(result.length).toBe(5); + expect(result[0]).toBe("Here's some code:\n"); + expect((result[1] as any).props.color).toBe("cyan"); + expect((result[1] as any).props.children).toBe( + "\nfunction test() {\n return 42;\n}\n" + ); + expect(result[2]).toBe("\nAnd "); + expect((result[3] as any).props.bold).toBe(true); + expect((result[3] as any).props.children).toBe("bold"); + expect(result[4]).toBe(" text"); + }); + + it("handles empty code blocks", () => { + const result = renderMarkdown("``````"); + expect(result.length).toBe(1); + expect(React.isValidElement(result[0])).toBe(true); + expect((result[0] as any).props.color).toBe("cyan"); + expect((result[0] as any).props.children).toBe(""); + }); + }); +}); diff --git a/src/ui/MarkdownRenderer.tsx b/src/ui/MarkdownRenderer.tsx new file mode 100644 index 000000000..bad1ec28b --- /dev/null +++ b/src/ui/MarkdownRenderer.tsx @@ -0,0 +1,142 @@ +import { Text } from "ink"; +import React from "react"; + +interface MarkdownRendererProps { + content: string; +} + +interface MarkdownPattern { + regex: RegExp; + render: (content: string, key: string) => React.ReactNode; +} + +const MarkdownRenderer: React.FC = ({ content }) => { + const patterns: MarkdownPattern[] = [ + { + regex: /```([\s\S]*?)```/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /^(#{1,6})\s+(.+)$/gm, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /\*\*(.+?)\*\*/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /\*([^\s*][^*]*[^\s*]|[^\s*])\*/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /_([^_]+)_/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /~~([^~]+)~~/g, + render: (content, key) => ( + + {content} + + ), + }, + { + regex: /`([^`]+)`/g, + render: (content, key) => ( + + {content} + + ), + }, + ]; + + const renderMarkdown = (text: string) => { + const parts: React.ReactNode[] = []; + let currentIndex = 0; + + // Find all matches for all patterns + const allMatches: Array<{ + index: number; + length: number; + content: string; + render: (content: string, key: string) => React.ReactNode; + }> = []; + + patterns.forEach((pattern) => { + let match; + const regex = new RegExp(pattern.regex.source, pattern.regex.flags); + + while ((match = regex.exec(text)) !== null) { + allMatches.push({ + index: match.index, + length: match[0].length, + content: match[2] || match[1], // Use second capture group for headings, first for others + render: pattern.render, + }); + } + }); + + // Sort matches by index to process them in order + allMatches.sort((a, b) => a.index - b.index); + + // Process matches, avoiding overlaps + let processedMatches: typeof allMatches = []; + for (const match of allMatches) { + const overlaps = processedMatches.some( + (processed) => + (match.index >= processed.index && + match.index < processed.index + processed.length) || + (processed.index >= match.index && + processed.index < match.index + match.length) + ); + + if (!overlaps) { + processedMatches.push(match); + } + } + + // Render the text with formatting + processedMatches.forEach((match, idx) => { + // Add text before this match + if (match.index > currentIndex) { + parts.push(text.slice(currentIndex, match.index)); + } + + // Add the formatted match + parts.push(match.render(match.content, `format-${idx}-${match.index}`)); + + currentIndex = match.index + match.length; + }); + + // Add remaining text + if (currentIndex < text.length) { + parts.push(text.slice(currentIndex)); + } + + return parts; + }; + + return {renderMarkdown(content)}; +}; + +export default MarkdownRenderer; diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 3ba26802e..1a691649c 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -3,12 +3,13 @@ import { Box, Text, useApp } from "ink"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import path from "path"; import React, { useEffect, useState } from "react"; +import { loadSession, saveSession } from "../session.js"; import { handleSlashCommands } from "../slashCommands.js"; import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import { getToolDisplayName } from "../tools.js"; -import { loadSession, saveSession, hasSession } from "../session.js"; import LoadingAnimation from "./LoadingAnimation.js"; +import MarkdownRenderer from "./MarkdownRenderer.js"; import ToolResultSummary from "./ToolResultSummary.js"; import UserInput from "./UserInput.js"; @@ -37,7 +38,7 @@ const TUIChat: React.FC = ({ const [chatHistory, setChatHistory] = useState( () => { let history: ChatCompletionMessageParam[] = []; - + // Load previous session if --resume flag is used if (resume) { const savedHistory = loadSession(); @@ -45,7 +46,7 @@ const TUIChat: React.FC = ({ history = savedHistory; } } - + // If no session loaded or not resuming, initialize with system message if (history.length === 0) { const rulesSystemMessage = assistant.systemMessage; @@ -54,7 +55,7 @@ const TUIChat: React.FC = ({ history.push({ role: "system", content: systemMessage }); } } - + return history; } ); @@ -66,10 +67,10 @@ const TUIChat: React.FC = ({ const savedHistory = loadSession(); if (savedHistory) { return savedHistory - .filter(msg => msg.role !== "system") - .map(msg => ({ + .filter((msg) => msg.role !== "system") + .map((msg) => ({ role: msg.role, - content: msg.content as string + content: msg.content as string, })); } } @@ -78,7 +79,9 @@ const TUIChat: React.FC = ({ const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = useState(null); - const [attachedFiles, setAttachedFiles] = useState>([]); + const [attachedFiles, setAttachedFiles] = useState< + Array<{ path: string; content: string }> + >([]); const { exit } = useApp(); // Handle initial prompt @@ -99,18 +102,20 @@ const TUIChat: React.FC = ({ if (commandResult.clear) { // Clear chat history but keep system message - const systemMessage = chatHistory.find(msg => msg.role === "system"); + const systemMessage = chatHistory.find((msg) => msg.role === "system"); const newHistory = systemMessage ? [systemMessage] : []; setChatHistory(newHistory); setMessages([]); - + // Add command output to messages if (commandResult.output) { - setMessages([{ - role: "system", - content: commandResult.output!, - messageType: "system", - }]); + setMessages([ + { + role: "system", + content: commandResult.output!, + messageType: "system", + }, + ]); } return; } @@ -136,18 +141,20 @@ const TUIChat: React.FC = ({ // Add user message to history and display let messageContent = message; - + // Prepend attached files to the message if (attachedFiles.length > 0) { - const fileContents = attachedFiles.map(file => - `\n\n\n${file.content}\n` - ).join(''); + const fileContents = attachedFiles + .map( + (file) => `\n\n\n${file.content}\n` + ) + .join(""); messageContent = `${message}${fileContents}`; - + // Clear attached files after sending setAttachedFiles([]); } - + const newUserMessage: ChatCompletionMessageParam = { role: "user", content: messageContent, @@ -170,7 +177,11 @@ const TUIChat: React.FC = ({ onContent: (content: string) => { // Buffer content but don't update UI until complete or tool call if (!currentStreamingMessage) { - currentStreamingMessage = { role: "assistant", content: "", isStreaming: true }; + currentStreamingMessage = { + role: "assistant", + content: "", + isStreaming: true, + }; } currentStreamingMessage.content += content; }, @@ -179,7 +190,7 @@ const TUIChat: React.FC = ({ if (currentStreamingMessage) { setMessages((prev) => [ ...prev, - { role: "assistant", content: content, isStreaming: false } + { role: "assistant", content: content, isStreaming: false }, ]); currentStreamingMessage = null; } @@ -191,7 +202,7 @@ const TUIChat: React.FC = ({ // Get the first parameter value for display const firstValue = Object.values(args)[0]; - + // Convert absolute paths to relative paths from workspace root const formatPath = (value: any) => { if (typeof value === "string" && path.isAbsolute(value)) { @@ -210,7 +221,11 @@ const TUIChat: React.FC = ({ const messageContent = currentStreamingMessage.content; setMessages((prev) => [ ...prev, - { role: "assistant", content: messageContent, isStreaming: false } + { + role: "assistant", + content: messageContent, + isStreaming: false, + }, ]); currentStreamingMessage = null; } @@ -271,7 +286,7 @@ const TUIChat: React.FC = ({ const messageContent = (currentStreamingMessage as any).content; setMessages((prev) => [ ...prev, - { role: "assistant", content: messageContent, isStreaming: false } + { role: "assistant", content: messageContent, isStreaming: false }, ]); } @@ -305,7 +320,7 @@ const TUIChat: React.FC = ({ }; const handleFileAttached = (filePath: string, content: string) => { - setAttachedFiles(prev => [...prev, { path: filePath, content }]); + setAttachedFiles((prev) => [...prev, { path: filePath, content }]); }; const renderMessage = (message: DisplayMessage, index: number) => { @@ -363,7 +378,12 @@ const TUIChat: React.FC = ({ return ( ● - {message.content} + + {isUser ? ( + {message.content} + ) : ( + + )} {message.isStreaming && ▋} ); @@ -386,7 +406,6 @@ const TUIChat: React.FC = ({ )} - {/* Input area - always at bottom */}