From 91adad26077ffe93d680c3bdfa0440d946408667 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 11:11:28 -0700 Subject: [PATCH 01/18] feat: go back in history --- extensions/cli/src/ui/EditMessageSelector.tsx | 222 ++++++++++++++++++ extensions/cli/src/ui/TUIChat.tsx | 5 + extensions/cli/src/ui/UserInput.tsx | 22 ++ .../cli/src/ui/components/ScreenContent.tsx | 25 ++ .../cli/src/ui/context/NavigationContext.tsx | 1 + extensions/cli/src/ui/hooks/useChat.ts | 30 +++ extensions/cli/src/ui/hooks/useChat.types.ts | 1 + 7 files changed, 306 insertions(+) create mode 100644 extensions/cli/src/ui/EditMessageSelector.tsx diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx new file mode 100644 index 000000000..ef86afd6c --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -0,0 +1,222 @@ +import { Box, Text, useInput } from "ink"; +import React, { useMemo, useState } from "react"; + +import type { ChatHistoryItem } from "../../../../core/index.js"; + +import { TextBuffer } from "./TextBuffer.js"; +import { defaultBoxStyles } from "./styles.js"; + +interface EditMessageSelectorProps { + chatHistory: ChatHistoryItem[]; + onEdit: (messageIndex: number, newContent: string) => void; + onExit: () => void; +} + +export function EditMessageSelector({ + chatHistory, + onEdit, + onExit, +}: EditMessageSelectorProps) { + // Filter to only show user messages + const userMessages = useMemo(() => { + return chatHistory + .map((item, originalIndex) => ({ item, originalIndex })) + .filter(({ item }) => item.message.role === "user"); + }, [chatHistory]); + + const [selectedIndex, setSelectedIndex] = useState(0); + const [isEditing, setIsEditing] = useState(false); + const [textBuffer] = useState(() => new TextBuffer()); + const [editText, setEditText] = useState(""); + const [cursorPosition, setCursorPosition] = useState(0); + + // Initialize edit text when selection changes + React.useEffect(() => { + if (!isEditing && userMessages[selectedIndex]) { + const content = + typeof userMessages[selectedIndex].item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } + }, [selectedIndex, isEditing, userMessages, textBuffer]); + + useInput((input, key) => { + // If not editing, handle navigation + if (!isEditing) { + if (key.upArrow || input === "k") { + setSelectedIndex((prev) => + prev > 0 ? prev - 1 : userMessages.length - 1, + ); + } else if (key.downArrow || input === "j") { + setSelectedIndex((prev) => + prev < userMessages.length - 1 ? prev + 1 : 0, + ); + } else if (key.return) { + setIsEditing(true); + } else if (key.escape || (key.ctrl && input === "d")) { + onExit(); + } + } else { + // In edit mode, handle text input + if (key.escape) { + setIsEditing(false); + // Reset text to original + const content = + typeof userMessages[selectedIndex].item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setText(content); + setEditText(content); + setCursorPosition(content.length); + } else if (key.return && !key.shift) { + // Submit the edit + const trimmedText = textBuffer.text.trim(); + if (trimmedText && userMessages[selectedIndex]) { + onEdit(userMessages[selectedIndex].originalIndex, trimmedText); + } + } else if (key.return && key.shift) { + // Handle newline + textBuffer.handleInput("\n", key); + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + } else { + // Let TextBuffer handle the input + textBuffer.handleInput(input, key); + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + } + } + }); + + if (userMessages.length === 0) { + return ( + + No user messages to edit. + Press Esc to exit + + ); + } + + const renderEditText = () => { + if (editText.length === 0) { + return ( + + ▋(empty message) + + ); + } + + // Handle multi-line text with cursor + const lines = editText.split("\n"); + let charCount = 0; + let cursorLine = 0; + let cursorCol = 0; + + // Find which line and column the cursor is on + for (let i = 0; i < lines.length; i++) { + if (cursorPosition <= charCount + lines[i].length) { + cursorLine = i; + cursorCol = cursorPosition - charCount; + break; + } + charCount += lines[i].length + 1; // +1 for the newline character + } + + // Handle cursor at the very end + if (cursorPosition >= editText.length) { + cursorLine = lines.length - 1; + cursorCol = lines[cursorLine].length; + } + + return ( + + {lines.map((line, lineIndex) => { + if (lineIndex === cursorLine) { + // Line with cursor + const beforeCursor = line.slice(0, cursorCol); + const atCursor = line.slice(cursorCol, cursorCol + 1); + const afterCursor = line.slice(cursorCol + 1); + + return ( + + {beforeCursor} + {atCursor || " "} + {afterCursor} + + ); + } else { + // Regular line - ensure empty lines still render + return {line || " "}; + } + })} + + ); + }; + + const selectedMessage = userMessages[selectedIndex]; + const messageContent = + typeof selectedMessage?.item.message.content === "string" + ? selectedMessage.item.message.content + : ""; + + return ( + + + Edit Message (Rewind Conversation) + + + {isEditing + ? "Enter to submit, Esc to cancel, Shift+Enter for newline" + : "↑/↓ to navigate, Enter to edit, Esc to exit"} + + + + {!isEditing && ( + <> + Select a message to edit: + + {userMessages.map((msg, index) => { + const isSelected = index === selectedIndex; + const indicator = isSelected ? "➤ " : " "; + const color = isSelected ? "yellow" : "white"; + const content = + typeof msg.item.message.content === "string" + ? msg.item.message.content + : ""; + const preview = content.split("\n")[0].slice(0, 60); + const truncated = content.length > 60 ? "..." : ""; + + return ( + + + {indicator}Message {index + 1}: {preview} + {truncated} + + + ); + })} + + )} + + {isEditing && ( + <> + + Editing Message {selectedIndex + 1} (will rewind to this point): + + + + {renderEditText()} + + + )} + + ); +} diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 555c32829..9b96bdef7 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -227,6 +227,7 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, } = useChat({ assistant: services.config?.config || undefined, @@ -242,6 +243,7 @@ const TUIChat: React.FC = ({ onShowMCPSelector: () => navigateTo("mcp"), onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), + onShowEditSelector: () => navigateTo("edit"), onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, @@ -377,6 +379,9 @@ const TUIChat: React.FC = ({ isRemoteMode={isRemoteMode} onImageInClipboardChange={setHasImageInClipboard} diffContent={diffContent} + chatHistory={chatHistory} + handleEditMessage={handleEditMessage} + onShowEditSelector={() => navigateTo("edit")} /> {/* Resource debug bar - only in verbose mode */} diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 834bd68e4..7e6abd34a 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -109,6 +109,7 @@ interface UserInputProps { hideNormalUI?: boolean; isRemoteMode?: boolean; onImageInClipboardChange?: (hasImage: boolean) => void; + onShowEditSelector?: () => void; } const UserInput: React.FC = ({ @@ -125,9 +126,11 @@ const UserInput: React.FC = ({ hideNormalUI = false, isRemoteMode = false, onImageInClipboardChange, + onShowEditSelector, }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); + const [lastEscapePress, setLastEscapePress] = useState(0); // Stable callback for TextBuffer state changes to prevent race conditions const onStateChange = useCallback(() => { @@ -625,6 +628,25 @@ const UserInput: React.FC = ({ return true; } + // Handle double Esc to open edit message selector + const now = Date.now(); + if ( + inputMode && + !showSlashCommands && + !showFileSearch && + !showBashMode && + onShowEditSelector && + now - lastEscapePress < 500 + ) { + // Double escape detected + onShowEditSelector(); + setLastEscapePress(0); // Reset to prevent triple-escape + return true; + } + + // Track single escape press + setLastEscapePress(now); + return false; }; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 977d6954a..3be048246 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -1,11 +1,13 @@ import { Box, Text } from "ink"; import React from "react"; +import type { ChatHistoryItem } from "../../../../../core/index.js"; import { UpdateServiceState } from "src/services/types.js"; import { ConfigSelector } from "../ConfigSelector.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; +import { EditMessageSelector } from "../EditMessageSelector.js"; import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; @@ -44,6 +46,9 @@ interface ScreenContentProps { isRemoteMode: boolean; onImageInClipboardChange?: (hasImage: boolean) => void; diffContent?: string; + chatHistory?: ChatHistoryItem[]; + handleEditMessage?: (messageIndex: number, newContent: string) => void; + onShowEditSelector?: () => void; } function hideScreenContent(state?: UpdateServiceState) { @@ -77,6 +82,9 @@ export const ScreenContent: React.FC = ({ isRemoteMode, onImageInClipboardChange, diffContent, + chatHistory = [], + handleEditMessage, + onShowEditSelector, }) => { if (hideScreenContent(services.update)) { return null; @@ -162,6 +170,22 @@ export const ScreenContent: React.FC = ({ ); } + // Edit message selector + if (isScreenActive("edit")) { + return ( + { + if (handleEditMessage) { + handleEditMessage(messageIndex, newContent); + } + closeCurrentScreen(); + }} + onExit={closeCurrentScreen} + /> + ); + } + // Chat screen with input area if (isScreenActive("chat")) { if (activePermissionRequest) { @@ -189,6 +213,7 @@ export const ScreenContent: React.FC = ({ disabled={isInputDisabled} isRemoteMode={isRemoteMode} onImageInClipboardChange={onImageInClipboardChange} + onShowEditSelector={onShowEditSelector} /> ); } diff --git a/extensions/cli/src/ui/context/NavigationContext.tsx b/extensions/cli/src/ui/context/NavigationContext.tsx index fd922ca51..6d43414dd 100644 --- a/extensions/cli/src/ui/context/NavigationContext.tsx +++ b/extensions/cli/src/ui/context/NavigationContext.tsx @@ -20,6 +20,7 @@ export type NavigationScreen = | "session" // Session selector | "diff" // Full-screen diff overlay | "update" // Update selector + | "edit" // Edit message selector | "session"; // Session selector interface NavigationState { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 4503bae53..5029435f1 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -58,6 +58,7 @@ export function useChat({ onShowUpdateSelector, onShowMCPSelector, onShowSessionSelector, + onShowEditSelector, onLoginPrompt: _onLoginPrompt, onClear, isRemoteMode = false, @@ -721,6 +722,34 @@ export function useChat({ setQueuedMessages([]); }; + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + // Close the edit selector if callback is available + if (onShowEditSelector) { + // The screen will be closed automatically by the navigation system + } + + // Rewind chat history to the selected message index + const rewindedHistory = chatHistory.slice(0, messageIndex); + + // Update the chat history with the rewound version + setChatHistory(rewindedHistory); + + // Clear any queued messages + setQueuedMessages([]); + + // Clear attached files + setAttachedFiles([]); + + // Update the session with the rewound history + updateSessionHistory(rewindedHistory); + + // Resubmit the edited message + await processMessage(newContent, undefined, false); + }; + const handleToolPermissionResponse = async ( requestId: string, approved: boolean, @@ -803,6 +832,7 @@ export function useChat({ handleInterrupt, handleFileAttached, resetChatHistory, + handleEditMessage, handleToolPermissionResponse, }; } diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index bf449191b..d85962b78 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -18,6 +18,7 @@ export interface UseChatProps { onShowUpdateSelector: () => void; onShowModelSelector?: () => void; onShowSessionSelector?: () => void; + onShowEditSelector?: () => void; onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; From 23ba9a54007ec60f40feabdf82fce7afb9189d7f Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 11:42:23 -0700 Subject: [PATCH 02/18] improv: message history ux --- extensions/cli/src/ui/EditMessageSelector.tsx | 17 ++++++- extensions/cli/src/ui/TUIChat.tsx | 3 ++ .../cli/src/ui/components/ScreenContent.tsx | 3 ++ extensions/cli/src/ui/hooks/useChat.ts | 50 +++++++++++++++---- extensions/cli/src/ui/hooks/useChat.types.ts | 1 + 5 files changed, 64 insertions(+), 10 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index ef86afd6c..7797b297f 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -9,12 +9,14 @@ import { defaultBoxStyles } from "./styles.js"; interface EditMessageSelectorProps { chatHistory: ChatHistoryItem[]; onEdit: (messageIndex: number, newContent: string) => void; + onMessageSelected?: (originalIndex: number) => void; onExit: () => void; } export function EditMessageSelector({ chatHistory, onEdit, + onMessageSelected, onExit, }: EditMessageSelectorProps) { // Filter to only show user messages @@ -24,7 +26,9 @@ export function EditMessageSelector({ .filter(({ item }) => item.message.role === "user"); }, [chatHistory]); - const [selectedIndex, setSelectedIndex] = useState(0); + const [selectedIndex, setSelectedIndex] = useState( + Math.max(0, userMessages.length - 1), + ); const [isEditing, setIsEditing] = useState(false); const [textBuffer] = useState(() => new TextBuffer()); const [editText, setEditText] = useState(""); @@ -55,6 +59,17 @@ export function EditMessageSelector({ prev < userMessages.length - 1 ? prev + 1 : 0, ); } else if (key.return) { + // Notify parent that a message was selected for editing + if (onMessageSelected && userMessages[selectedIndex]) { + const originalIndex = userMessages[selectedIndex].originalIndex; + console.log("EditMessageSelector: User pressed Enter", { + selectedIndex, + originalIndex, + totalUserMessages: userMessages.length, + totalChatHistory: chatHistory.length, + }); + onMessageSelected(originalIndex); + } setIsEditing(true); } else if (key.escape || (key.ctrl && input === "d")) { onExit(); diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 9b96bdef7..bf8414cc2 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -227,6 +227,7 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, + handleSelectMessageForEdit, handleEditMessage, handleToolPermissionResponse, } = useChat({ @@ -247,6 +248,7 @@ const TUIChat: React.FC = ({ onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, + onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1), // Remote mode configuration isRemoteMode, remoteUrl, @@ -380,6 +382,7 @@ const TUIChat: React.FC = ({ onImageInClipboardChange={setHasImageInClipboard} diffContent={diffContent} chatHistory={chatHistory} + handleSelectMessageForEdit={handleSelectMessageForEdit} handleEditMessage={handleEditMessage} onShowEditSelector={() => navigateTo("edit")} /> diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 3be048246..77aa58ee4 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -47,6 +47,7 @@ interface ScreenContentProps { onImageInClipboardChange?: (hasImage: boolean) => void; diffContent?: string; chatHistory?: ChatHistoryItem[]; + handleSelectMessageForEdit?: (originalIndex: number) => void; handleEditMessage?: (messageIndex: number, newContent: string) => void; onShowEditSelector?: () => void; } @@ -83,6 +84,7 @@ export const ScreenContent: React.FC = ({ onImageInClipboardChange, diffContent, chatHistory = [], + handleSelectMessageForEdit, handleEditMessage, onShowEditSelector, }) => { @@ -175,6 +177,7 @@ export const ScreenContent: React.FC = ({ return ( { if (handleEditMessage) { handleEditMessage(messageIndex, newContent); diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 5029435f1..6c7fd65e4 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -61,6 +61,7 @@ export function useChat({ onShowEditSelector, onLoginPrompt: _onLoginPrompt, onClear, + onRefreshStatic, isRemoteMode = false, remoteUrl, onShowDiff, @@ -722,17 +723,22 @@ export function useChat({ setQueuedMessages([]); }; - const handleEditMessage = async ( - messageIndex: number, - newContent: string, + const handleSelectMessageForEdit = ( + originalIndex: number, + onComplete?: () => void, ) => { - // Close the edit selector if callback is available - if (onShowEditSelector) { - // The screen will be closed automatically by the navigation system - } + logger.debug("handleSelectMessageForEdit called", { + originalIndex, + currentHistoryLength: chatHistory.length, + }); - // Rewind chat history to the selected message index - const rewindedHistory = chatHistory.slice(0, messageIndex); + // Rewind chat history to the selected message index (up to and including the message) + const rewindedHistory = chatHistory.slice(0, originalIndex + 1); + + logger.debug("Rewinding history", { + from: chatHistory.length, + to: rewindedHistory.length, + }); // Update the chat history with the rewound version setChatHistory(rewindedHistory); @@ -746,6 +752,31 @@ export function useChat({ // Update the session with the rewound history updateSessionHistory(rewindedHistory); + // Force refresh of StaticChatContent to show truncated history + if (onRefreshStatic) { + onRefreshStatic(); + } + + // Call onComplete callback if provided + if (onComplete) { + onComplete(); + } + }; + + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + // At this point, history is already rewound to the selected message + // We need to rewind one more step to exclude the original message, then resubmit + const rewindedHistory = chatHistory.slice(0, messageIndex); + + // Update the chat history to exclude the message being edited + setChatHistory(rewindedHistory); + + // Update the session + updateSessionHistory(rewindedHistory); + // Resubmit the edited message await processMessage(newContent, undefined, false); }; @@ -832,6 +863,7 @@ export function useChat({ handleInterrupt, handleFileAttached, resetChatHistory, + handleSelectMessageForEdit, handleEditMessage, handleToolPermissionResponse, }; diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index d85962b78..fa0e6fd13 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -22,6 +22,7 @@ export interface UseChatProps { onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; + onRefreshStatic?: () => void; // Remote mode props isRemoteMode?: boolean; remoteUrl?: string; From 9de20396ce1faebbae555f93b69d0ca918faad21 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 13:22:19 -0700 Subject: [PATCH 03/18] improv: architecture --- extensions/cli/src/ui/EditMessageSelector.tsx | 14 +---- extensions/cli/src/ui/TUIChat.tsx | 2 - .../cli/src/ui/components/ScreenContent.tsx | 3 -- extensions/cli/src/ui/hooks/useChat.ts | 53 ++++++------------- 4 files changed, 18 insertions(+), 54 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 7797b297f..24fdcc408 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -9,14 +9,12 @@ import { defaultBoxStyles } from "./styles.js"; interface EditMessageSelectorProps { chatHistory: ChatHistoryItem[]; onEdit: (messageIndex: number, newContent: string) => void; - onMessageSelected?: (originalIndex: number) => void; onExit: () => void; } export function EditMessageSelector({ chatHistory, onEdit, - onMessageSelected, onExit, }: EditMessageSelectorProps) { // Filter to only show user messages @@ -59,17 +57,7 @@ export function EditMessageSelector({ prev < userMessages.length - 1 ? prev + 1 : 0, ); } else if (key.return) { - // Notify parent that a message was selected for editing - if (onMessageSelected && userMessages[selectedIndex]) { - const originalIndex = userMessages[selectedIndex].originalIndex; - console.log("EditMessageSelector: User pressed Enter", { - selectedIndex, - originalIndex, - totalUserMessages: userMessages.length, - totalChatHistory: chatHistory.length, - }); - onMessageSelected(originalIndex); - } + // Start editing the selected message setIsEditing(true); } else if (key.escape || (key.ctrl && input === "d")) { onExit(); diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index bf8414cc2..0ecaa0fe8 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -227,7 +227,6 @@ const TUIChat: React.FC = ({ handleInterrupt, handleFileAttached, resetChatHistory, - handleSelectMessageForEdit, handleEditMessage, handleToolPermissionResponse, } = useChat({ @@ -382,7 +381,6 @@ const TUIChat: React.FC = ({ onImageInClipboardChange={setHasImageInClipboard} diffContent={diffContent} chatHistory={chatHistory} - handleSelectMessageForEdit={handleSelectMessageForEdit} handleEditMessage={handleEditMessage} onShowEditSelector={() => navigateTo("edit")} /> diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 77aa58ee4..3be048246 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -47,7 +47,6 @@ interface ScreenContentProps { onImageInClipboardChange?: (hasImage: boolean) => void; diffContent?: string; chatHistory?: ChatHistoryItem[]; - handleSelectMessageForEdit?: (originalIndex: number) => void; handleEditMessage?: (messageIndex: number, newContent: string) => void; onShowEditSelector?: () => void; } @@ -84,7 +83,6 @@ export const ScreenContent: React.FC = ({ onImageInClipboardChange, diffContent, chatHistory = [], - handleSelectMessageForEdit, handleEditMessage, onShowEditSelector, }) => { @@ -177,7 +175,6 @@ export const ScreenContent: React.FC = ({ return ( { if (handleEditMessage) { handleEditMessage(messageIndex, newContent); diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 6c7fd65e4..2b1028be1 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -457,7 +457,11 @@ export function useChat({ message: string, imageMap?: Map, isQueuedMessage: boolean = false, + baseHistory?: ChatHistoryItem[], ) => { + // Use baseHistory if provided (e.g., when editing a message), + // otherwise use current chatHistory + const currentHistory = baseHistory ?? chatHistory; // Handle special commands const handled = await handleSpecialCommands({ message, @@ -526,7 +530,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -593,7 +597,7 @@ export function useChat({ let currentChatHistory, currentCompactionIndex; try { const result = await handleAutoCompaction({ - chatHistory, + chatHistory: currentHistory, model, llmApi, compactionIndex, @@ -723,26 +727,23 @@ export function useChat({ setQueuedMessages([]); }; - const handleSelectMessageForEdit = ( - originalIndex: number, - onComplete?: () => void, + const handleEditMessage = async ( + messageIndex: number, + newContent: string, ) => { - logger.debug("handleSelectMessageForEdit called", { - originalIndex, + logger.debug("handleEditMessage called", { + messageIndex, currentHistoryLength: chatHistory.length, }); - // Rewind chat history to the selected message index (up to and including the message) - const rewindedHistory = chatHistory.slice(0, originalIndex + 1); + // Rewind chat history to exclude the message being edited + const rewindedHistory = chatHistory.slice(0, messageIndex); - logger.debug("Rewinding history", { + logger.debug("Rewinding history for edit", { from: chatHistory.length, to: rewindedHistory.length, }); - // Update the chat history with the rewound version - setChatHistory(rewindedHistory); - // Clear any queued messages setQueuedMessages([]); @@ -757,28 +758,9 @@ export function useChat({ onRefreshStatic(); } - // Call onComplete callback if provided - if (onComplete) { - onComplete(); - } - }; - - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - // At this point, history is already rewound to the selected message - // We need to rewind one more step to exclude the original message, then resubmit - const rewindedHistory = chatHistory.slice(0, messageIndex); - - // Update the chat history to exclude the message being edited - setChatHistory(rewindedHistory); - - // Update the session - updateSessionHistory(rewindedHistory); - - // Resubmit the edited message - await processMessage(newContent, undefined, false); + // Resubmit the edited message with the rewound history as the base + // This ensures processMessage uses the correct base history + await processMessage(newContent, undefined, false, rewindedHistory); }; const handleToolPermissionResponse = async ( @@ -863,7 +845,6 @@ export function useChat({ handleInterrupt, handleFileAttached, resetChatHistory, - handleSelectMessageForEdit, handleEditMessage, handleToolPermissionResponse, }; From 82a681bc8420df5a361b282602766ca4ef3ec058 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 13:38:32 -0700 Subject: [PATCH 04/18] fix: message input --- extensions/cli/src/ui/EditMessageSelector.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 24fdcc408..9aa876e1e 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -57,7 +57,13 @@ export function EditMessageSelector({ prev < userMessages.length - 1 ? prev + 1 : 0, ); } else if (key.return) { - // Start editing the selected message + // Start editing the selected message - set cursor to end + const content = + typeof userMessages[selectedIndex]?.item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setCursor(content.length); + setCursorPosition(content.length); setIsEditing(true); } else if (key.escape || (key.ctrl && input === "d")) { onExit(); From 5247d08f59f051c4d54472e38c2262b5b8482e37 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 13:55:00 -0700 Subject: [PATCH 05/18] test: message history edits --- .../cli/src/ui/EditMessageSelector.test.tsx | 238 +++++++++++++ .../ui/__tests__/TUIChat.editMessage.test.tsx | 265 ++++++++++++++ .../cli/src/ui/hooks/useChat.edit.test.ts | 337 ++++++++++++++++++ 3 files changed, 840 insertions(+) create mode 100644 extensions/cli/src/ui/EditMessageSelector.test.tsx create mode 100644 extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx create mode 100644 extensions/cli/src/ui/hooks/useChat.edit.test.ts diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx new file mode 100644 index 000000000..06d090ae9 --- /dev/null +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -0,0 +1,238 @@ +/** + * @vitest-environment jsdom + */ +import { render } from "@testing-library/react"; +import type { ChatHistoryItem } from "core/index.js"; +import { Box } from "ink"; +import React from "react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +import { EditMessageSelector } from "./EditMessageSelector.js"; +import { TextBuffer } from "./TextBuffer.js"; + +// Mock TextBuffer for controlled testing +vi.mock("./TextBuffer.js", () => { + return { + TextBuffer: vi.fn().mockImplementation(() => ({ + text: "", + cursor: 0, + setText: vi.fn(), + setCursor: vi.fn(), + handleInput: vi.fn(), + })), + }; +}); + +describe("EditMessageSelector", () => { + const createMockChatHistory = (count: number): ChatHistoryItem[] => { + const history: ChatHistoryItem[] = []; + for (let i = 0; i < count; i++) { + // Alternate between user and assistant messages + if (i % 2 === 0) { + history.push({ + message: { role: "user", content: `User message ${i + 1}` }, + contextItems: [], + }); + } else { + history.push({ + message: { role: "assistant", content: `Assistant message ${i + 1}` }, + contextItems: [], + }); + } + } + return history; + }; + + let mockOnEdit: ReturnType; + let mockOnExit: ReturnType; + + beforeEach(() => { + mockOnEdit = vi.fn(); + mockOnExit = vi.fn(); + vi.clearAllMocks(); + }); + + describe("Initialization", () => { + it("should render 'no user messages' when chat history is empty", () => { + const { container } = render( + , + ); + + expect(container.textContent).toContain("No user messages to edit"); + }); + + it("should render 'no user messages' when chat history has only assistant messages", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "assistant", content: "Hello" }, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + expect(container.textContent).toContain("No user messages to edit"); + }); + + it("should render user messages list", () => { + const chatHistory = createMockChatHistory(4); // Will have 2 user messages + + const { container } = render( + , + ); + + expect(container.textContent).toContain("Message 1:"); + expect(container.textContent).toContain("Message 2:"); + expect(container.textContent).toContain("User message 1"); + expect(container.textContent).toContain("User message 3"); + }); + + it("should filter out non-user messages", () => { + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: "User 1" }, contextItems: [] }, + { + message: { role: "assistant", content: "Assistant 1" }, + contextItems: [], + }, + { message: { role: "system", content: "System 1" }, contextItems: [] }, + { message: { role: "user", content: "User 2" }, contextItems: [] }, + ]; + + const { container } = render( + , + ); + + // Should only show 2 user messages + expect(container.textContent).toContain("User 1"); + expect(container.textContent).toContain("User 2"); + expect(container.textContent).not.toContain("Assistant 1"); + expect(container.textContent).not.toContain("System 1"); + }); + + it("should show instruction text in selection mode", () => { + const chatHistory = createMockChatHistory(2); + + const { container } = render( + , + ); + + expect(container.textContent).toContain("↑/↓ to navigate"); + expect(container.textContent).toContain("Enter to edit"); + expect(container.textContent).toContain("Esc to exit"); + }); + }); + + describe("Message preview", () => { + it("should truncate long messages in preview", () => { + const longMessage = "a".repeat(100); + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: longMessage }, contextItems: [] }, + ]; + + const { container } = render( + , + ); + + // Should show truncation indicator + expect(container.textContent).toContain("..."); + // Should not show full message (preview is limited to 60 chars) + expect(container.textContent).not.toContain(longMessage); + }); + + it("should show only first line in multiline message preview", () => { + const multilineMessage = "First line\nSecond line\nThird line"; + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: multilineMessage }, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + expect(container.textContent).toContain("First line"); + expect(container.textContent).not.toContain("Second line"); + }); + }); + + describe("Cursor positioning bug fix", () => { + it("should position cursor at end when entering edit mode", () => { + const chatHistory: ChatHistoryItem[] = [ + { message: { role: "user", content: "Hello world" }, contextItems: [] }, + ]; + + const mockTextBuffer = new TextBuffer(); + const mockSetCursor = vi.fn(); + mockTextBuffer.setCursor = mockSetCursor; + + // This test verifies the fix: when Enter is pressed to start editing, + // setCursor should be called with content.length + // The actual implementation test would require simulating Enter keypress + // which is complex with Ink components + + // For now, this test documents the expected behavior + const messageContent = "Hello world"; + expect(messageContent.length).toBe(11); + }); + }); + + describe("Complex message content", () => { + it("should handle message parts array", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { + role: "user", + content: [ + { type: "text", text: "Hello" }, + { type: "text", text: " world" }, + ], + } as any, + contextItems: [], + }, + ]; + + const { container } = render( + , + ); + + // Should render something (component handles non-string content gracefully) + expect(container.textContent).toBeDefined(); + }); + }); +}); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx new file mode 100644 index 000000000..21e62c7b2 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -0,0 +1,265 @@ +import { testBothModes, renderInMode } from "./TUIChat.dualModeHelper.js"; + +/** + * Integration tests for the message edit feature in TUIChat + * + * Tests the full flow: + * 1. Double Esc opens EditMessageSelector + * 2. User navigates and selects a message + * 3. User edits the message + * 4. History is rewound and new message is submitted + * 5. Chat updates correctly + */ + +describe("TUIChat - Message Edit Feature", () => { + testBothModes("double Esc should open edit selector", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Press Esc twice quickly (within 500ms) + stdin.write("\u001b"); // First Esc + stdin.write("\u001b"); // Second Esc + + // Wait for UI to update + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should show edit message selector + // The exact text depends on implementation, but should indicate edit mode + if (mode === "local") { + // In local mode, edit selector should be available + expect(frame).toBeDefined(); + // Note: The actual UI content will depend on chat history + // This test verifies the component doesn't crash + } + }); + + testBothModes("edit selector should handle navigation", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector (double Esc) + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Try navigation keys + stdin.write("j"); // Down + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("k"); // Up + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle navigation without crashing + expect(frame).toBeDefined(); + }); + + testBothModes("edit selector should exit with Esc", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Press Esc to exit + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should return to normal chat view + expect(frame).toBeDefined(); + expect(frame).toContain("Ask anything"); + }); + + testBothModes("should handle edit flow without crashing", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // This test verifies the basic flow doesn't crash + // Actual behavior depends on having chat history + + // Open edit selector + stdin.write("\u001b"); + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Try to edit (Enter) + stdin.write("\r"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Type something + stdin.write("Test edit"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Exit without submitting (Esc) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should not crash + expect(frame).toBeDefined(); + }); + + testBothModes( + "should maintain UI stability during edit operations", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Perform various operations + stdin.write("\u001b\u001b"); // Open edit + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("k"); // Navigate + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b"); // Close + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // UI should remain stable + expect(frame).toBeDefined(); + expect(frame.length).toBeGreaterThan(0); + + // Should still show chat interface + if (mode === "local") { + expect(frame).toContain("Continue CLI"); + } else { + expect(frame).toContain("Remote Mode"); + } + }, + ); +}); + +describe("TUIChat - Edit Selector Navigation", () => { + testBothModes("should handle rapid navigation commands", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Rapid navigation + stdin.write("jjjjkkk"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle rapid input without crashing + expect(frame).toBeDefined(); + }); + + testBothModes("should handle arrow keys in edit selector", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Open edit selector + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Use arrow keys (ANSI escape sequences) + stdin.write("\u001b[A"); // Up arrow + await new Promise((resolve) => setTimeout(resolve, 50)); + + stdin.write("\u001b[B"); // Down arrow + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should handle arrow keys + expect(frame).toBeDefined(); + }); +}); + +describe("TUIChat - Edit Feature Edge Cases", () => { + testBothModes( + "should handle opening edit selector with no chat history", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Try to open edit selector immediately (no history) + stdin.write("\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should either show "no messages" or handle gracefully + expect(frame).toBeDefined(); + expect(frame.length).toBeGreaterThan(0); + }, + ); + + testBothModes("should handle single Esc (not double)", async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Single Esc (should not open edit selector) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 600)); // Wait longer than 500ms threshold + + stdin.write("\u001b"); // Another single Esc after timeout + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should not open edit selector (requires double Esc within 500ms) + // Instead should just remain in normal mode + expect(frame).toBeDefined(); + }); + + testBothModes( + "should prevent triple escape from causing issues", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Triple Esc quickly + stdin.write("\u001b\u001b\u001b"); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const frame = lastFrame(); + + // Should handle gracefully (open then close, or just open) + expect(frame).toBeDefined(); + }, + ); +}); + +describe("TUIChat - Edit Feature Compatibility", () => { + testBothModes( + "edit feature should not interfere with normal input", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Type normal input + stdin.write("Hello world"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frame = lastFrame(); + + // Should show typed text + expect(frame).toBeDefined(); + // Normal input should work + }, + ); + + testBothModes( + "should not conflict with other Esc-based features", + async (mode) => { + const { lastFrame, stdin } = renderInMode(mode); + + // Type something + stdin.write("test"); + await new Promise((resolve) => setTimeout(resolve, 50)); + + // Single Esc (might clear input or do other things) + stdin.write("\u001b"); + await new Promise((resolve) => setTimeout(resolve, 600)); + + const frame = lastFrame(); + + // Should handle without conflicts + expect(frame).toBeDefined(); + }, + ); +}); diff --git a/extensions/cli/src/ui/hooks/useChat.edit.test.ts b/extensions/cli/src/ui/hooks/useChat.edit.test.ts new file mode 100644 index 000000000..c45259dc4 --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.edit.test.ts @@ -0,0 +1,337 @@ +import type { ChatHistoryItem } from "core/index.js"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +/** + * Tests for the message edit feature in useChat hook + * + * This test suite covers: + * - handleEditMessage: Rewinds history and resubmits edited message + * - processMessage with baseHistory: Uses explicit base history instead of state + * - Integration: Full edit flow produces correct final history + */ + +describe("useChat - Message Edit Feature", () => { + const createMockChatHistory = (count: number): ChatHistoryItem[] => { + return Array.from({ length: count }, (_, i) => ({ + message: { + role: i % 2 === 0 ? "user" : "assistant", + content: `Message ${i + 1}`, + }, + contextItems: [], + })); + }; + + describe("handleEditMessage", () => { + it("should rewind history to exclude the message being edited", () => { + const chatHistory = createMockChatHistory(5); // [user, asst, user, asst, user] + let currentHistory = chatHistory; + + const setChatHistory = vi.fn(); + const setQueuedMessages = vi.fn(); + const setAttachedFiles = vi.fn(); + const updateSessionHistory = vi.fn(); + const onRefreshStatic = vi.fn(); + const processMessage = vi.fn(); + + // Mock handleEditMessage behavior + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + const rewindedHistory = currentHistory.slice(0, messageIndex); + setQueuedMessages([]); + setAttachedFiles([]); + updateSessionHistory(rewindedHistory); + if (onRefreshStatic) { + onRefreshStatic(); + } + await processMessage(newContent, undefined, false, rewindedHistory); + }; + + // Edit message at index 2 (third message) + handleEditMessage(2, "Edited message"); + + // Verify history was rewound to [0, 1] + expect(updateSessionHistory).toHaveBeenCalledWith( + chatHistory.slice(0, 2), + ); + + // Verify state was cleared + expect(setQueuedMessages).toHaveBeenCalledWith([]); + expect(setAttachedFiles).toHaveBeenCalledWith([]); + + // Verify refresh was called + expect(onRefreshStatic).toHaveBeenCalled(); + + // Verify processMessage was called with correct baseHistory + expect(processMessage).toHaveBeenCalledWith( + "Edited message", + undefined, + false, + chatHistory.slice(0, 2), + ); + }); + + it("should handle editing the first message", () => { + const chatHistory = createMockChatHistory(5); + let currentHistory = chatHistory; + + const updateSessionHistory = vi.fn(); + const processMessage = vi.fn(); + + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + const rewindedHistory = currentHistory.slice(0, messageIndex); + updateSessionHistory(rewindedHistory); + await processMessage(newContent, undefined, false, rewindedHistory); + }; + + // Edit first message (index 0) + handleEditMessage(0, "New first message"); + + // Should rewind to empty history + expect(updateSessionHistory).toHaveBeenCalledWith([]); + expect(processMessage).toHaveBeenCalledWith( + "New first message", + undefined, + false, + [], + ); + }); + + it("should handle editing the last message", () => { + const chatHistory = createMockChatHistory(5); + let currentHistory = chatHistory; + + const updateSessionHistory = vi.fn(); + const processMessage = vi.fn(); + + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + const rewindedHistory = currentHistory.slice(0, messageIndex); + updateSessionHistory(rewindedHistory); + await processMessage(newContent, undefined, false, rewindedHistory); + }; + + // Edit last message (index 4) + handleEditMessage(4, "Edited last message"); + + // Should rewind to [0, 1, 2, 3] + expect(updateSessionHistory).toHaveBeenCalledWith( + chatHistory.slice(0, 4), + ); + expect(processMessage).toHaveBeenCalledWith( + "Edited last message", + undefined, + false, + chatHistory.slice(0, 4), + ); + }); + }); + + describe("processMessage with baseHistory", () => { + it("should use baseHistory instead of chatHistory when provided", () => { + // Simulate the scenario where chatHistory state hasn't updated yet + const oldChatHistory = createMockChatHistory(5); + const baseHistory = oldChatHistory.slice(0, 2); // Rewound history + + // Mock processMessage that uses baseHistory parameter + const processMessage = ( + message: string, + imageMap?: Map, + isQueuedMessage: boolean = false, + baseHistory?: ChatHistoryItem[], + ) => { + const currentHistory = baseHistory ?? oldChatHistory; + return currentHistory; + }; + + // Call with baseHistory + const result = processMessage( + "New message", + undefined, + false, + baseHistory, + ); + + // Should use baseHistory, not oldChatHistory + expect(result).toEqual(baseHistory); + expect(result).not.toEqual(oldChatHistory); + }); + + it("should fall back to chatHistory when baseHistory is not provided", () => { + const chatHistory = createMockChatHistory(3); + + const processMessage = ( + message: string, + imageMap?: Map, + isQueuedMessage: boolean = false, + baseHistory?: ChatHistoryItem[], + ) => { + const currentHistory = baseHistory ?? chatHistory; + return currentHistory; + }; + + // Call without baseHistory + const result = processMessage("New message"); + + // Should use chatHistory + expect(result).toEqual(chatHistory); + }); + }); + + describe("Edit flow integration", () => { + it("should produce correct history after edit and resubmit", async () => { + // Initial history: [user1, asst1, user2, asst2, user3] + const initialHistory = createMockChatHistory(5); + let chatHistory = initialHistory; + + const setChatHistory = vi.fn((updater: any) => { + if (typeof updater === "function") { + chatHistory = updater(chatHistory); + } else { + chatHistory = updater; + } + }); + + // Simulate editing user2 (index 2) + const messageIndexToEdit = 2; + const newContent = "Edited user2"; + + // Step 1: Rewind history + const rewindedHistory = initialHistory.slice(0, messageIndexToEdit); + // Result: [user1, asst1] + + // Step 2: Simulate processMessage adding new user message + const newUserMessage: ChatHistoryItem = { + message: { role: "user", content: newContent }, + contextItems: [], + }; + + const expectedHistory = [...rewindedHistory, newUserMessage]; + // Expected: [user1, asst1, edited_user2] + + setChatHistory(expectedHistory); + + // Verify final history + expect(chatHistory).toHaveLength(3); + expect(chatHistory[0]).toEqual(initialHistory[0]); // user1 + expect(chatHistory[1]).toEqual(initialHistory[1]); // asst1 + expect(chatHistory[2].message.content).toBe(newContent); // edited message + + // Verify old messages are gone + expect(chatHistory).not.toContain(initialHistory[2]); // old user2 + expect(chatHistory).not.toContain(initialHistory[3]); // asst2 + expect(chatHistory).not.toContain(initialHistory[4]); // user3 + }); + + it("should handle editing with queued messages", () => { + const chatHistory = createMockChatHistory(3); + const queuedMessages = ["queued1", "queued2"]; + + const setQueuedMessages = vi.fn(); + const setAttachedFiles = vi.fn(); + + // When editing, should clear queued messages + const handleEdit = () => { + setQueuedMessages([]); + setAttachedFiles([]); + }; + + handleEdit(); + + expect(setQueuedMessages).toHaveBeenCalledWith([]); + expect(setAttachedFiles).toHaveBeenCalledWith([]); + }); + + it("should handle editing with attached files", () => { + const attachedFiles = [ + { path: "/test.txt", content: "test" }, + { path: "/test2.txt", content: "test2" }, + ]; + + const setAttachedFiles = vi.fn(); + + // When editing, should clear attached files + const handleEdit = () => { + setAttachedFiles([]); + }; + + handleEdit(); + + expect(setAttachedFiles).toHaveBeenCalledWith([]); + }); + }); + + describe("Edge cases", () => { + it("should handle editing with empty chat history", () => { + const chatHistory: ChatHistoryItem[] = []; + + const updateSessionHistory = vi.fn(); + const processMessage = vi.fn(); + + const handleEditMessage = async ( + messageIndex: number, + newContent: string, + ) => { + const rewindedHistory = chatHistory.slice(0, messageIndex); + updateSessionHistory(rewindedHistory); + await processMessage(newContent, undefined, false, rewindedHistory); + }; + + // Attempt to edit (should handle gracefully) + handleEditMessage(0, "New message"); + + expect(updateSessionHistory).toHaveBeenCalledWith([]); + expect(processMessage).toHaveBeenCalledWith( + "New message", + undefined, + false, + [], + ); + }); + + it("should handle editing with out-of-bounds index", () => { + const chatHistory = createMockChatHistory(3); + + const updateSessionHistory = vi.fn(); + + const handleEditMessage = (messageIndex: number) => { + const rewindedHistory = chatHistory.slice(0, messageIndex); + updateSessionHistory(rewindedHistory); + }; + + // Index beyond history length + handleEditMessage(10); + + // slice(0, 10) on array of length 3 returns full array + expect(updateSessionHistory).toHaveBeenCalledWith(chatHistory); + }); + + it("should preserve message structure during edit", () => { + const chatHistory: ChatHistoryItem[] = [ + { + message: { role: "user", content: "Original" }, + contextItems: [{ name: "file.txt", content: "data" }], + }, + ]; + + const rewindedHistory = chatHistory.slice(0, 0); // Empty + const newMessage: ChatHistoryItem = { + message: { role: "user", content: "Edited" }, + contextItems: [], // New message may have different contextItems + }; + + const expectedHistory = [...rewindedHistory, newMessage]; + + expect(expectedHistory).toHaveLength(1); + expect(expectedHistory[0].message.content).toBe("Edited"); + // Original message with its contextItems is gone + expect(expectedHistory[0]).not.toEqual(chatHistory[0]); + }); + }); +}); From b76212fc703d09ee6a34c77ebc972fdb859db8e5 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:06:05 -0700 Subject: [PATCH 06/18] improv: tests --- .../src/ui/__tests__/TUIChat.editMessage.test.tsx | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx index 21e62c7b2..6d2c0885f 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -63,15 +63,19 @@ describe("TUIChat - Message Edit Feature", () => { stdin.write("\u001b"); await new Promise((resolve) => setTimeout(resolve, 100)); + // Verify edit selector is open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + // Press Esc to exit stdin.write("\u001b"); await new Promise((resolve) => setTimeout(resolve, 100)); - const frame = lastFrame(); - - // Should return to normal chat view + // Verify edit selector is closed + frame = lastFrame(); expect(frame).toBeDefined(); - expect(frame).toContain("Ask anything"); + expect(frame).not.toContain("No user messages to edit"); }); testBothModes("should handle edit flow without crashing", async (mode) => { From 8d119691235c17ba575adf95824ce122d2948189 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:15:52 -0700 Subject: [PATCH 07/18] improv: tests --- .../ui/__tests__/TUIChat.editMessage.test.tsx | 52 ++++++++++--------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx index 6d2c0885f..e50f59948 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -15,6 +15,11 @@ describe("TUIChat - Message Edit Feature", () => { testBothModes("double Esc should open edit selector", async (mode) => { const { lastFrame, stdin } = renderInMode(mode); + // Verify selector is not open initially + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + // Press Esc twice quickly (within 500ms) stdin.write("\u001b"); // First Esc stdin.write("\u001b"); // Second Esc @@ -22,16 +27,10 @@ describe("TUIChat - Message Edit Feature", () => { // Wait for UI to update await new Promise((resolve) => setTimeout(resolve, 100)); - const frame = lastFrame(); - - // Should show edit message selector - // The exact text depends on implementation, but should indicate edit mode - if (mode === "local") { - // In local mode, edit selector should be available - expect(frame).toBeDefined(); - // Note: The actual UI content will depend on chat history - // This test verifies the component doesn't crash - } + // Verify selector is now open + frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); }); testBothModes("edit selector should handle navigation", async (mode) => { @@ -42,6 +41,11 @@ describe("TUIChat - Message Edit Feature", () => { stdin.write("\u001b"); await new Promise((resolve) => setTimeout(resolve, 100)); + // Verify selector is open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + // Try navigation keys stdin.write("j"); // Down await new Promise((resolve) => setTimeout(resolve, 50)); @@ -49,10 +53,10 @@ describe("TUIChat - Message Edit Feature", () => { stdin.write("k"); // Up await new Promise((resolve) => setTimeout(resolve, 50)); - const frame = lastFrame(); - - // Should handle navigation without crashing + // Verify selector is still open after navigation + frame = lastFrame(); expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); }); testBothModes("edit selector should exit with Esc", async (mode) => { @@ -124,16 +128,10 @@ describe("TUIChat - Message Edit Feature", () => { const frame = lastFrame(); - // UI should remain stable + // UI should remain stable and edit selector should be closed expect(frame).toBeDefined(); expect(frame.length).toBeGreaterThan(0); - - // Should still show chat interface - if (mode === "local") { - expect(frame).toContain("Continue CLI"); - } else { - expect(frame).toContain("Remote Mode"); - } + expect(frame).not.toContain("No user messages to edit"); }, ); }); @@ -202,14 +200,18 @@ describe("TUIChat - Edit Feature Edge Cases", () => { stdin.write("\u001b"); await new Promise((resolve) => setTimeout(resolve, 600)); // Wait longer than 500ms threshold + // Verify selector did not open + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); + stdin.write("\u001b"); // Another single Esc after timeout await new Promise((resolve) => setTimeout(resolve, 100)); - const frame = lastFrame(); - - // Should not open edit selector (requires double Esc within 500ms) - // Instead should just remain in normal mode + // Verify selector still did not open + frame = lastFrame(); expect(frame).toBeDefined(); + expect(frame).not.toContain("No user messages to edit"); }); testBothModes( From 45e9a944e74d7197e5610e47d6331ba344443c85 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:24:33 -0700 Subject: [PATCH 08/18] fix: linter errors --- .../cli/src/ui/__tests__/TUIChat.editMessage.test.tsx | 4 ++-- extensions/cli/src/ui/hooks/useChat.edit.test.ts | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx index e50f59948..1f33fb1be 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -130,7 +130,7 @@ describe("TUIChat - Message Edit Feature", () => { // UI should remain stable and edit selector should be closed expect(frame).toBeDefined(); - expect(frame.length).toBeGreaterThan(0); + expect(frame!.length).toBeGreaterThan(0); expect(frame).not.toContain("No user messages to edit"); }, ); @@ -189,7 +189,7 @@ describe("TUIChat - Edit Feature Edge Cases", () => { // Should either show "no messages" or handle gracefully expect(frame).toBeDefined(); - expect(frame.length).toBeGreaterThan(0); + expect(frame!.length).toBeGreaterThan(0); }, ); diff --git a/extensions/cli/src/ui/hooks/useChat.edit.test.ts b/extensions/cli/src/ui/hooks/useChat.edit.test.ts index c45259dc4..b1fc2adb3 100644 --- a/extensions/cli/src/ui/hooks/useChat.edit.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.edit.test.ts @@ -316,7 +316,14 @@ describe("useChat - Message Edit Feature", () => { const chatHistory: ChatHistoryItem[] = [ { message: { role: "user", content: "Original" }, - contextItems: [{ name: "file.txt", content: "data" }], + contextItems: [ + { + name: "file.txt", + content: "data", + description: "file.txt", + id: { providerTitle: "file", itemId: "file.txt" }, + }, + ], }, ]; From 7b82f4fc3d791c335ee2ced3b06c533bdc71de80 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:30:36 -0700 Subject: [PATCH 09/18] fix: linter errors --- extensions/cli/src/ui/EditMessageSelector.test.tsx | 1 - extensions/cli/src/ui/EditMessageSelector.tsx | 2 +- extensions/cli/src/ui/components/ScreenContent.tsx | 2 +- extensions/cli/src/ui/hooks/useChat.edit.test.ts | 8 ++++---- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 06d090ae9..06c7f8358 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -3,7 +3,6 @@ */ import { render } from "@testing-library/react"; import type { ChatHistoryItem } from "core/index.js"; -import { Box } from "ink"; import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 9aa876e1e..ce898afe5 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -3,8 +3,8 @@ import React, { useMemo, useState } from "react"; import type { ChatHistoryItem } from "../../../../core/index.js"; -import { TextBuffer } from "./TextBuffer.js"; import { defaultBoxStyles } from "./styles.js"; +import { TextBuffer } from "./TextBuffer.js"; interface EditMessageSelectorProps { chatHistory: ChatHistoryItem[]; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 3be048246..ab963b62c 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -1,9 +1,9 @@ import { Box, Text } from "ink"; import React from "react"; -import type { ChatHistoryItem } from "../../../../../core/index.js"; import { UpdateServiceState } from "src/services/types.js"; +import type { ChatHistoryItem } from "../../../../../core/index.js"; import { ConfigSelector } from "../ConfigSelector.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; diff --git a/extensions/cli/src/ui/hooks/useChat.edit.test.ts b/extensions/cli/src/ui/hooks/useChat.edit.test.ts index b1fc2adb3..dd4020021 100644 --- a/extensions/cli/src/ui/hooks/useChat.edit.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.edit.test.ts @@ -1,5 +1,5 @@ import type { ChatHistoryItem } from "core/index.js"; -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { describe, it, expect, vi } from "vitest"; /** * Tests for the message edit feature in useChat hook @@ -24,7 +24,7 @@ describe("useChat - Message Edit Feature", () => { describe("handleEditMessage", () => { it("should rewind history to exclude the message being edited", () => { const chatHistory = createMockChatHistory(5); // [user, asst, user, asst, user] - let currentHistory = chatHistory; + const currentHistory = chatHistory; const setChatHistory = vi.fn(); const setQueuedMessages = vi.fn(); @@ -74,7 +74,7 @@ describe("useChat - Message Edit Feature", () => { it("should handle editing the first message", () => { const chatHistory = createMockChatHistory(5); - let currentHistory = chatHistory; + const currentHistory = chatHistory; const updateSessionHistory = vi.fn(); const processMessage = vi.fn(); @@ -103,7 +103,7 @@ describe("useChat - Message Edit Feature", () => { it("should handle editing the last message", () => { const chatHistory = createMockChatHistory(5); - let currentHistory = chatHistory; + const currentHistory = chatHistory; const updateSessionHistory = vi.fn(); const processMessage = vi.fn(); From 4582ab2df3eed7b3608d8b3fdefac25b9f827203 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 14:44:25 -0700 Subject: [PATCH 10/18] fix: linter errors --- extensions/cli/src/ui/EditMessageSelector.tsx | 53 ++++++------- .../src/ui/components/ChatScreenContent.tsx | 76 +++++++++++++++++++ .../cli/src/ui/components/ScreenContent.tsx | 29 +++---- extensions/cli/src/ui/hooks/useChat.ts | 2 +- extensions/cli/src/ui/hooks/useChat.types.ts | 1 + 5 files changed, 112 insertions(+), 49 deletions(-) create mode 100644 extensions/cli/src/ui/components/ChatScreenContent.tsx diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index ce898afe5..02219261c 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -46,29 +46,8 @@ export function EditMessageSelector({ }, [selectedIndex, isEditing, userMessages, textBuffer]); useInput((input, key) => { - // If not editing, handle navigation - if (!isEditing) { - if (key.upArrow || input === "k") { - setSelectedIndex((prev) => - prev > 0 ? prev - 1 : userMessages.length - 1, - ); - } else if (key.downArrow || input === "j") { - setSelectedIndex((prev) => - prev < userMessages.length - 1 ? prev + 1 : 0, - ); - } else if (key.return) { - // Start editing the selected message - set cursor to end - const content = - typeof userMessages[selectedIndex]?.item.message.content === "string" - ? userMessages[selectedIndex].item.message.content - : ""; - textBuffer.setCursor(content.length); - setCursorPosition(content.length); - setIsEditing(true); - } else if (key.escape || (key.ctrl && input === "d")) { - onExit(); - } - } else { + // If editing, handle text input + if (isEditing) { // In edit mode, handle text input if (key.escape) { setIsEditing(false); @@ -97,6 +76,28 @@ export function EditMessageSelector({ setEditText(textBuffer.text); setCursorPosition(textBuffer.cursor); } + } else { + // If not editing, handle navigation + if (key.upArrow || input === "k") { + setSelectedIndex((prev) => + prev > 0 ? prev - 1 : userMessages.length - 1, + ); + } else if (key.downArrow || input === "j") { + setSelectedIndex((prev) => + prev < userMessages.length - 1 ? prev + 1 : 0, + ); + } else if (key.return) { + // Start editing the selected message - set cursor to end + const content = + typeof userMessages[selectedIndex]?.item.message.content === "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setCursor(content.length); + setCursorPosition(content.length); + setIsEditing(true); + } else if (key.escape || (key.ctrl && input === "d")) { + onExit(); + } } }); @@ -165,12 +166,6 @@ export function EditMessageSelector({ ); }; - const selectedMessage = userMessages[selectedIndex]; - const messageContent = - typeof selectedMessage?.item.message.content === "string" - ? selectedMessage.item.message.content - : ""; - return ( diff --git a/extensions/cli/src/ui/components/ChatScreenContent.tsx b/extensions/cli/src/ui/components/ChatScreenContent.tsx new file mode 100644 index 000000000..7c3225da6 --- /dev/null +++ b/extensions/cli/src/ui/components/ChatScreenContent.tsx @@ -0,0 +1,76 @@ +import type { AssistantConfig } from "@continuedev/sdk"; +import React from "react"; + +import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; +import { UserInput } from "../UserInput.js"; + +import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; + +interface ChatScreenContentProps { + activePermissionRequest: ActivePermissionRequest | null; + handleToolPermissionResponse: ( + requestId: string, + approved: boolean, + createPolicy?: boolean, + stopStream?: boolean, + ) => void; + handleUserMessage: (message: string, imageMap?: Map) => void; + isWaitingForResponse: boolean; + isCompacting: boolean; + inputMode: boolean; + handleInterrupt: () => void; + assistant?: AssistantConfig; + wasInterrupted: boolean; + handleFileAttached: (filePath: string, content: string) => void; + isInputDisabled: boolean; + isRemoteMode: boolean; + onImageInClipboardChange?: (hasImage: boolean) => void; + onShowEditSelector?: () => void; +} + +export const ChatScreenContent: React.FC = ({ + activePermissionRequest, + handleToolPermissionResponse, + handleUserMessage, + isWaitingForResponse, + isCompacting, + inputMode, + handleInterrupt, + assistant, + wasInterrupted, + handleFileAttached, + isInputDisabled, + isRemoteMode, + onImageInClipboardChange, + onShowEditSelector, +}) => { + if (activePermissionRequest) { + return ( + + ); + } + + return ( + + ); +}; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index ab963b62c..694c8f215 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -9,14 +9,15 @@ import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; import { EditMessageSelector } from "../EditMessageSelector.js"; import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; +import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; import type { ConfigOption, ModelOption } from "../types/selectorTypes.js"; import { UpdateSelector } from "../UpdateSelector.js"; import { UserInput } from "../UserInput.js"; +import { ChatScreenContent } from "./ChatScreenContent.js"; import { SessionSelectorWithLoading } from "./SessionSelectorWithLoading.js"; -import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; interface ScreenContentProps { isScreenActive: (screen: NavigationScreen) => boolean; @@ -28,7 +29,7 @@ interface ScreenContentProps { handleSessionSelect: (sessionId: string) => Promise; handleReload: () => Promise; closeCurrentScreen: () => void; - activePermissionRequest: any; + activePermissionRequest: ActivePermissionRequest | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, @@ -188,29 +189,19 @@ export const ScreenContent: React.FC = ({ // Chat screen with input area if (isScreenActive("chat")) { - if (activePermissionRequest) { - return ( - - ); - } return ( - Date: Tue, 7 Oct 2025 14:46:20 -0700 Subject: [PATCH 11/18] improv: clean up code --- extensions/cli/src/ui/TUIChat.tsx | 4 +--- extensions/cli/src/ui/hooks/useChat.ts | 2 -- extensions/cli/src/ui/hooks/useChat.types.ts | 2 -- 3 files changed, 1 insertion(+), 7 deletions(-) diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 0ecaa0fe8..30729d35e 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -173,7 +173,7 @@ const TUIChat: React.FC = ({ ); // Use login handlers - const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers( + const { handleLoginTokenSubmit } = useLoginHandlers( navigateTo, navState, closeCurrentScreen, @@ -243,8 +243,6 @@ const TUIChat: React.FC = ({ onShowMCPSelector: () => navigateTo("mcp"), onShowUpdateSelector: () => navigateTo("update"), onShowSessionSelector: () => navigateTo("session"), - onShowEditSelector: () => navigateTo("edit"), - onLoginPrompt: handleLoginPrompt, onReload: handleReload, onClear: handleClear, onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1), diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 09d7cf8a6..fe3dc8d05 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -58,8 +58,6 @@ export function useChat({ onShowUpdateSelector, onShowMCPSelector, onShowSessionSelector, - onShowEditSelector: _onShowEditSelector, - onLoginPrompt: _onLoginPrompt, onClear, onRefreshStatic, isRemoteMode = false, diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index 6340355fe..2fe0b0b81 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -18,8 +18,6 @@ export interface UseChatProps { onShowUpdateSelector: () => void; onShowModelSelector?: () => void; onShowSessionSelector?: () => void; - onShowEditSelector?: () => void; - onLoginPrompt?: (promptText: string) => Promise; onReload?: () => Promise; onClear?: () => void; onRefreshStatic?: () => void; From 0858aa41b00a3598602664c7301e96ef8f5a0cd3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 15:53:25 -0700 Subject: [PATCH 12/18] fix: failing tests --- extensions/cli/src/ui/EditMessageSelector.tsx | 38 ++++++++++++------- extensions/cli/src/ui/UserInput.tsx | 10 ++--- .../ui/__tests__/TUIChat.editMessage.test.tsx | 16 +++++--- 3 files changed, 40 insertions(+), 24 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 02219261c..00d043cce 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -53,7 +53,7 @@ export function EditMessageSelector({ setIsEditing(false); // Reset text to original const content = - typeof userMessages[selectedIndex].item.message.content === "string" + typeof userMessages[selectedIndex]?.item.message.content === "string" ? userMessages[selectedIndex].item.message.content : ""; textBuffer.setText(content); @@ -79,22 +79,32 @@ export function EditMessageSelector({ } else { // If not editing, handle navigation if (key.upArrow || input === "k") { - setSelectedIndex((prev) => - prev > 0 ? prev - 1 : userMessages.length - 1, - ); + // Only navigate if there are messages + if (userMessages.length > 0) { + setSelectedIndex((prev) => + prev > 0 ? prev - 1 : userMessages.length - 1, + ); + } } else if (key.downArrow || input === "j") { - setSelectedIndex((prev) => - prev < userMessages.length - 1 ? prev + 1 : 0, - ); + // Only navigate if there are messages + if (userMessages.length > 0) { + setSelectedIndex((prev) => + prev < userMessages.length - 1 ? prev + 1 : 0, + ); + } } else if (key.return) { // Start editing the selected message - set cursor to end - const content = - typeof userMessages[selectedIndex]?.item.message.content === "string" - ? userMessages[selectedIndex].item.message.content - : ""; - textBuffer.setCursor(content.length); - setCursorPosition(content.length); - setIsEditing(true); + // Only allow editing if there are messages + if (userMessages.length > 0) { + const content = + typeof userMessages[selectedIndex]?.item.message.content === + "string" + ? userMessages[selectedIndex].item.message.content + : ""; + textBuffer.setCursor(content.length); + setCursorPosition(content.length); + setIsEditing(true); + } } else if (key.escape || (key.ctrl && input === "d")) { onExit(); } diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 7e6abd34a..fb31e4e5c 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -1,7 +1,7 @@ /* eslint-disable max-lines */ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text, useApp, useInput } from "ink"; -import React, { useCallback, useState } from "react"; +import React, { useCallback, useRef, useState } from "react"; import { getAllSlashCommands } from "../commands/commands.js"; import { useServices } from "../hooks/useService.js"; @@ -130,7 +130,7 @@ const UserInput: React.FC = ({ }) => { const [textBuffer] = useState(() => new TextBuffer()); const [inputHistory] = useState(() => new InputHistory()); - const [lastEscapePress, setLastEscapePress] = useState(0); + const lastEscapePressRef = useRef(0); // Stable callback for TextBuffer state changes to prevent race conditions const onStateChange = useCallback(() => { @@ -636,16 +636,16 @@ const UserInput: React.FC = ({ !showFileSearch && !showBashMode && onShowEditSelector && - now - lastEscapePress < 500 + now - lastEscapePressRef.current < 500 ) { // Double escape detected onShowEditSelector(); - setLastEscapePress(0); // Reset to prevent triple-escape + lastEscapePressRef.current = 0; // Reset to prevent triple-escape return true; } // Track single escape press - setLastEscapePress(now); + lastEscapePressRef.current = now; return false; }; diff --git a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx index 1f33fb1be..9e6a92874 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.editMessage.test.tsx @@ -117,16 +117,22 @@ describe("TUIChat - Message Edit Feature", () => { const { lastFrame, stdin } = renderInMode(mode); // Perform various operations - stdin.write("\u001b\u001b"); // Open edit - await new Promise((resolve) => setTimeout(resolve, 50)); + stdin.write("\u001b"); + stdin.write("\u001b"); // Open edit with separate Esc presses + await new Promise((resolve) => setTimeout(resolve, 100)); - stdin.write("k"); // Navigate + // Verify selector opened + let frame = lastFrame(); + expect(frame).toBeDefined(); + expect(frame).toContain("No user messages to edit"); + + stdin.write("k"); // Navigate (no-op with 0 messages) await new Promise((resolve) => setTimeout(resolve, 50)); stdin.write("\u001b"); // Close - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => setTimeout(resolve, 100)); - const frame = lastFrame(); + frame = lastFrame(); // UI should remain stable and edit selector should be closed expect(frame).toBeDefined(); From c8f5df90cb54ca015a52f08a1f710501a406ffe8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 15:57:52 -0700 Subject: [PATCH 13/18] fix: lint --- extensions/cli/src/ui/EditMessageSelector.tsx | 65 ++++++++++++++----- 1 file changed, 50 insertions(+), 15 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 00d043cce..e1d8eb5b9 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -1,4 +1,5 @@ import { Box, Text, useInput } from "ink"; +import type { Key } from "ink/build/hooks/use-input.js"; import React, { useMemo, useState } from "react"; import type { ChatHistoryItem } from "../../../../core/index.js"; @@ -45,17 +46,23 @@ export function EditMessageSelector({ } }, [selectedIndex, isEditing, userMessages, textBuffer]); - useInput((input, key) => { - // If editing, handle text input - if (isEditing) { - // In edit mode, handle text input + // Helper to get message content safely + const getMessageContent = React.useCallback( + (index: number): string => { + return typeof userMessages[index]?.item.message.content === "string" + ? userMessages[index].item.message.content + : ""; + }, + [userMessages], + ); + + // Handle input when in editing mode + const handleEditModeInput = React.useCallback( + (input: string, key: Key) => { if (key.escape) { setIsEditing(false); // Reset text to original - const content = - typeof userMessages[selectedIndex]?.item.message.content === "string" - ? userMessages[selectedIndex].item.message.content - : ""; + const content = getMessageContent(selectedIndex); textBuffer.setText(content); setEditText(content); setCursorPosition(content.length); @@ -76,8 +83,22 @@ export function EditMessageSelector({ setEditText(textBuffer.text); setCursorPosition(textBuffer.cursor); } - } else { - // If not editing, handle navigation + }, + [ + getMessageContent, + selectedIndex, + textBuffer, + userMessages, + onEdit, + setIsEditing, + setEditText, + setCursorPosition, + ], + ); + + // Handle input when in navigation mode + const handleNavigationInput = React.useCallback( + (input: string, key: Key) => { if (key.upArrow || input === "k") { // Only navigate if there are messages if (userMessages.length > 0) { @@ -96,11 +117,7 @@ export function EditMessageSelector({ // Start editing the selected message - set cursor to end // Only allow editing if there are messages if (userMessages.length > 0) { - const content = - typeof userMessages[selectedIndex]?.item.message.content === - "string" - ? userMessages[selectedIndex].item.message.content - : ""; + const content = getMessageContent(selectedIndex); textBuffer.setCursor(content.length); setCursorPosition(content.length); setIsEditing(true); @@ -108,6 +125,24 @@ export function EditMessageSelector({ } else if (key.escape || (key.ctrl && input === "d")) { onExit(); } + }, + [ + userMessages.length, + getMessageContent, + selectedIndex, + textBuffer, + onExit, + setSelectedIndex, + setCursorPosition, + setIsEditing, + ], + ); + + useInput((input, key) => { + if (isEditing) { + handleEditModeInput(input, key); + } else { + handleNavigationInput(input, key); } }); From db4f590dce8f15d4f1dabc9fef9a0a265b78e7a0 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 7 Oct 2025 16:05:50 -0700 Subject: [PATCH 14/18] fix: lint --- extensions/cli/src/ui/EditMessageSelector.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index e1d8eb5b9..311197cb5 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -1,5 +1,4 @@ import { Box, Text, useInput } from "ink"; -import type { Key } from "ink/build/hooks/use-input.js"; import React, { useMemo, useState } from "react"; import type { ChatHistoryItem } from "../../../../core/index.js"; @@ -7,6 +6,10 @@ import type { ChatHistoryItem } from "../../../../core/index.js"; import { defaultBoxStyles } from "./styles.js"; import { TextBuffer } from "./TextBuffer.js"; +// Infer the Key type from useInput's callback parameters +type UseInputHandler = Parameters[0]; +type Key = Parameters[1]; + interface EditMessageSelectorProps { chatHistory: ChatHistoryItem[]; onEdit: (messageIndex: number, newContent: string) => void; From 3a5f1886a842ac3952ca2159893fc7ebe8d69bd3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 8 Oct 2025 10:10:49 -0700 Subject: [PATCH 15/18] improv: clean up tests, fix paste block behavior --- .../cli/src/ui/EditMessageSelector.test.tsx | 21 -- extensions/cli/src/ui/EditMessageSelector.tsx | 2 + .../cli/src/ui/hooks/useChat.edit.test.ts | 344 ------------------ 3 files changed, 2 insertions(+), 365 deletions(-) delete mode 100644 extensions/cli/src/ui/hooks/useChat.edit.test.ts diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 06c7f8358..4577d6339 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -186,27 +186,6 @@ describe("EditMessageSelector", () => { }); }); - describe("Cursor positioning bug fix", () => { - it("should position cursor at end when entering edit mode", () => { - const chatHistory: ChatHistoryItem[] = [ - { message: { role: "user", content: "Hello world" }, contextItems: [] }, - ]; - - const mockTextBuffer = new TextBuffer(); - const mockSetCursor = vi.fn(); - mockTextBuffer.setCursor = mockSetCursor; - - // This test verifies the fix: when Enter is pressed to start editing, - // setCursor should be called with content.length - // The actual implementation test would require simulating Enter keypress - // which is complex with Ink components - - // For now, this test documents the expected behavior - const messageContent = "Hello world"; - expect(messageContent.length).toBe(11); - }); - }); - describe("Complex message content", () => { it("should handle message parts array", () => { const chatHistory: ChatHistoryItem[] = [ diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index 311197cb5..e1e9bc19b 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -71,6 +71,8 @@ export function EditMessageSelector({ setCursorPosition(content.length); } else if (key.return && !key.shift) { // Submit the edit + // Expand all paste blocks before submission to restore original content + textBuffer.expandAllPasteBlocks(); const trimmedText = textBuffer.text.trim(); if (trimmedText && userMessages[selectedIndex]) { onEdit(userMessages[selectedIndex].originalIndex, trimmedText); diff --git a/extensions/cli/src/ui/hooks/useChat.edit.test.ts b/extensions/cli/src/ui/hooks/useChat.edit.test.ts deleted file mode 100644 index dd4020021..000000000 --- a/extensions/cli/src/ui/hooks/useChat.edit.test.ts +++ /dev/null @@ -1,344 +0,0 @@ -import type { ChatHistoryItem } from "core/index.js"; -import { describe, it, expect, vi } from "vitest"; - -/** - * Tests for the message edit feature in useChat hook - * - * This test suite covers: - * - handleEditMessage: Rewinds history and resubmits edited message - * - processMessage with baseHistory: Uses explicit base history instead of state - * - Integration: Full edit flow produces correct final history - */ - -describe("useChat - Message Edit Feature", () => { - const createMockChatHistory = (count: number): ChatHistoryItem[] => { - return Array.from({ length: count }, (_, i) => ({ - message: { - role: i % 2 === 0 ? "user" : "assistant", - content: `Message ${i + 1}`, - }, - contextItems: [], - })); - }; - - describe("handleEditMessage", () => { - it("should rewind history to exclude the message being edited", () => { - const chatHistory = createMockChatHistory(5); // [user, asst, user, asst, user] - const currentHistory = chatHistory; - - const setChatHistory = vi.fn(); - const setQueuedMessages = vi.fn(); - const setAttachedFiles = vi.fn(); - const updateSessionHistory = vi.fn(); - const onRefreshStatic = vi.fn(); - const processMessage = vi.fn(); - - // Mock handleEditMessage behavior - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - const rewindedHistory = currentHistory.slice(0, messageIndex); - setQueuedMessages([]); - setAttachedFiles([]); - updateSessionHistory(rewindedHistory); - if (onRefreshStatic) { - onRefreshStatic(); - } - await processMessage(newContent, undefined, false, rewindedHistory); - }; - - // Edit message at index 2 (third message) - handleEditMessage(2, "Edited message"); - - // Verify history was rewound to [0, 1] - expect(updateSessionHistory).toHaveBeenCalledWith( - chatHistory.slice(0, 2), - ); - - // Verify state was cleared - expect(setQueuedMessages).toHaveBeenCalledWith([]); - expect(setAttachedFiles).toHaveBeenCalledWith([]); - - // Verify refresh was called - expect(onRefreshStatic).toHaveBeenCalled(); - - // Verify processMessage was called with correct baseHistory - expect(processMessage).toHaveBeenCalledWith( - "Edited message", - undefined, - false, - chatHistory.slice(0, 2), - ); - }); - - it("should handle editing the first message", () => { - const chatHistory = createMockChatHistory(5); - const currentHistory = chatHistory; - - const updateSessionHistory = vi.fn(); - const processMessage = vi.fn(); - - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - const rewindedHistory = currentHistory.slice(0, messageIndex); - updateSessionHistory(rewindedHistory); - await processMessage(newContent, undefined, false, rewindedHistory); - }; - - // Edit first message (index 0) - handleEditMessage(0, "New first message"); - - // Should rewind to empty history - expect(updateSessionHistory).toHaveBeenCalledWith([]); - expect(processMessage).toHaveBeenCalledWith( - "New first message", - undefined, - false, - [], - ); - }); - - it("should handle editing the last message", () => { - const chatHistory = createMockChatHistory(5); - const currentHistory = chatHistory; - - const updateSessionHistory = vi.fn(); - const processMessage = vi.fn(); - - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - const rewindedHistory = currentHistory.slice(0, messageIndex); - updateSessionHistory(rewindedHistory); - await processMessage(newContent, undefined, false, rewindedHistory); - }; - - // Edit last message (index 4) - handleEditMessage(4, "Edited last message"); - - // Should rewind to [0, 1, 2, 3] - expect(updateSessionHistory).toHaveBeenCalledWith( - chatHistory.slice(0, 4), - ); - expect(processMessage).toHaveBeenCalledWith( - "Edited last message", - undefined, - false, - chatHistory.slice(0, 4), - ); - }); - }); - - describe("processMessage with baseHistory", () => { - it("should use baseHistory instead of chatHistory when provided", () => { - // Simulate the scenario where chatHistory state hasn't updated yet - const oldChatHistory = createMockChatHistory(5); - const baseHistory = oldChatHistory.slice(0, 2); // Rewound history - - // Mock processMessage that uses baseHistory parameter - const processMessage = ( - message: string, - imageMap?: Map, - isQueuedMessage: boolean = false, - baseHistory?: ChatHistoryItem[], - ) => { - const currentHistory = baseHistory ?? oldChatHistory; - return currentHistory; - }; - - // Call with baseHistory - const result = processMessage( - "New message", - undefined, - false, - baseHistory, - ); - - // Should use baseHistory, not oldChatHistory - expect(result).toEqual(baseHistory); - expect(result).not.toEqual(oldChatHistory); - }); - - it("should fall back to chatHistory when baseHistory is not provided", () => { - const chatHistory = createMockChatHistory(3); - - const processMessage = ( - message: string, - imageMap?: Map, - isQueuedMessage: boolean = false, - baseHistory?: ChatHistoryItem[], - ) => { - const currentHistory = baseHistory ?? chatHistory; - return currentHistory; - }; - - // Call without baseHistory - const result = processMessage("New message"); - - // Should use chatHistory - expect(result).toEqual(chatHistory); - }); - }); - - describe("Edit flow integration", () => { - it("should produce correct history after edit and resubmit", async () => { - // Initial history: [user1, asst1, user2, asst2, user3] - const initialHistory = createMockChatHistory(5); - let chatHistory = initialHistory; - - const setChatHistory = vi.fn((updater: any) => { - if (typeof updater === "function") { - chatHistory = updater(chatHistory); - } else { - chatHistory = updater; - } - }); - - // Simulate editing user2 (index 2) - const messageIndexToEdit = 2; - const newContent = "Edited user2"; - - // Step 1: Rewind history - const rewindedHistory = initialHistory.slice(0, messageIndexToEdit); - // Result: [user1, asst1] - - // Step 2: Simulate processMessage adding new user message - const newUserMessage: ChatHistoryItem = { - message: { role: "user", content: newContent }, - contextItems: [], - }; - - const expectedHistory = [...rewindedHistory, newUserMessage]; - // Expected: [user1, asst1, edited_user2] - - setChatHistory(expectedHistory); - - // Verify final history - expect(chatHistory).toHaveLength(3); - expect(chatHistory[0]).toEqual(initialHistory[0]); // user1 - expect(chatHistory[1]).toEqual(initialHistory[1]); // asst1 - expect(chatHistory[2].message.content).toBe(newContent); // edited message - - // Verify old messages are gone - expect(chatHistory).not.toContain(initialHistory[2]); // old user2 - expect(chatHistory).not.toContain(initialHistory[3]); // asst2 - expect(chatHistory).not.toContain(initialHistory[4]); // user3 - }); - - it("should handle editing with queued messages", () => { - const chatHistory = createMockChatHistory(3); - const queuedMessages = ["queued1", "queued2"]; - - const setQueuedMessages = vi.fn(); - const setAttachedFiles = vi.fn(); - - // When editing, should clear queued messages - const handleEdit = () => { - setQueuedMessages([]); - setAttachedFiles([]); - }; - - handleEdit(); - - expect(setQueuedMessages).toHaveBeenCalledWith([]); - expect(setAttachedFiles).toHaveBeenCalledWith([]); - }); - - it("should handle editing with attached files", () => { - const attachedFiles = [ - { path: "/test.txt", content: "test" }, - { path: "/test2.txt", content: "test2" }, - ]; - - const setAttachedFiles = vi.fn(); - - // When editing, should clear attached files - const handleEdit = () => { - setAttachedFiles([]); - }; - - handleEdit(); - - expect(setAttachedFiles).toHaveBeenCalledWith([]); - }); - }); - - describe("Edge cases", () => { - it("should handle editing with empty chat history", () => { - const chatHistory: ChatHistoryItem[] = []; - - const updateSessionHistory = vi.fn(); - const processMessage = vi.fn(); - - const handleEditMessage = async ( - messageIndex: number, - newContent: string, - ) => { - const rewindedHistory = chatHistory.slice(0, messageIndex); - updateSessionHistory(rewindedHistory); - await processMessage(newContent, undefined, false, rewindedHistory); - }; - - // Attempt to edit (should handle gracefully) - handleEditMessage(0, "New message"); - - expect(updateSessionHistory).toHaveBeenCalledWith([]); - expect(processMessage).toHaveBeenCalledWith( - "New message", - undefined, - false, - [], - ); - }); - - it("should handle editing with out-of-bounds index", () => { - const chatHistory = createMockChatHistory(3); - - const updateSessionHistory = vi.fn(); - - const handleEditMessage = (messageIndex: number) => { - const rewindedHistory = chatHistory.slice(0, messageIndex); - updateSessionHistory(rewindedHistory); - }; - - // Index beyond history length - handleEditMessage(10); - - // slice(0, 10) on array of length 3 returns full array - expect(updateSessionHistory).toHaveBeenCalledWith(chatHistory); - }); - - it("should preserve message structure during edit", () => { - const chatHistory: ChatHistoryItem[] = [ - { - message: { role: "user", content: "Original" }, - contextItems: [ - { - name: "file.txt", - content: "data", - description: "file.txt", - id: { providerTitle: "file", itemId: "file.txt" }, - }, - ], - }, - ]; - - const rewindedHistory = chatHistory.slice(0, 0); // Empty - const newMessage: ChatHistoryItem = { - message: { role: "user", content: "Edited" }, - contextItems: [], // New message may have different contextItems - }; - - const expectedHistory = [...rewindedHistory, newMessage]; - - expect(expectedHistory).toHaveLength(1); - expect(expectedHistory[0].message.content).toBe("Edited"); - // Original message with its contextItems is gone - expect(expectedHistory[0]).not.toEqual(chatHistory[0]); - }); - }); -}); From a3a35f67331edd9479f54767469d2acc93d43d50 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 8 Oct 2025 10:16:44 -0700 Subject: [PATCH 16/18] fix: linter errors --- extensions/cli/src/ui/EditMessageSelector.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 4577d6339..8a5282b6b 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -7,7 +7,6 @@ import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { EditMessageSelector } from "./EditMessageSelector.js"; -import { TextBuffer } from "./TextBuffer.js"; // Mock TextBuffer for controlled testing vi.mock("./TextBuffer.js", () => { From 1acc648a90919ebe8ee825ade83ff30b5a71d397 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 8 Oct 2025 10:45:08 -0700 Subject: [PATCH 17/18] fix: text buffer handling --- .../cli/src/ui/EditMessageSelector.test.tsx | 14 +------------- extensions/cli/src/ui/EditMessageSelector.tsx | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 8a5282b6b..81acd28c2 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -7,19 +7,7 @@ import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { EditMessageSelector } from "./EditMessageSelector.js"; - -// Mock TextBuffer for controlled testing -vi.mock("./TextBuffer.js", () => { - return { - TextBuffer: vi.fn().mockImplementation(() => ({ - text: "", - cursor: 0, - setText: vi.fn(), - setCursor: vi.fn(), - handleInput: vi.fn(), - })), - }; -}); +import { TextBuffer } from "./TextBuffer.js"; describe("EditMessageSelector", () => { const createMockChatHistory = (count: number): ChatHistoryItem[] => { diff --git a/extensions/cli/src/ui/EditMessageSelector.tsx b/extensions/cli/src/ui/EditMessageSelector.tsx index e1e9bc19b..60c8a23c0 100644 --- a/extensions/cli/src/ui/EditMessageSelector.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.tsx @@ -36,6 +36,22 @@ export function EditMessageSelector({ const [editText, setEditText] = useState(""); const [cursorPosition, setCursorPosition] = useState(0); + // Stable callback for TextBuffer state changes (e.g., paste finalization) + const onStateChange = React.useCallback(() => { + setEditText(textBuffer.text); + setCursorPosition(textBuffer.cursor); + }, [textBuffer]); + + // Set up callback for when TextBuffer state changes asynchronously + React.useEffect(() => { + textBuffer.setStateChangeCallback(onStateChange); + + return () => { + // Clear any pending timers on unmount + textBuffer.clear(); + }; + }, [textBuffer, onStateChange]); + // Initialize edit text when selection changes React.useEffect(() => { if (!isEditing && userMessages[selectedIndex]) { From 8f116b15340c33a046e65274a0fd2f6916b89138 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 8 Oct 2025 10:47:40 -0700 Subject: [PATCH 18/18] fix: lint --- extensions/cli/src/ui/EditMessageSelector.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/extensions/cli/src/ui/EditMessageSelector.test.tsx b/extensions/cli/src/ui/EditMessageSelector.test.tsx index 81acd28c2..c56bec21a 100644 --- a/extensions/cli/src/ui/EditMessageSelector.test.tsx +++ b/extensions/cli/src/ui/EditMessageSelector.test.tsx @@ -7,7 +7,6 @@ import React from "react"; import { describe, it, expect, vi, beforeEach } from "vitest"; import { EditMessageSelector } from "./EditMessageSelector.js"; -import { TextBuffer } from "./TextBuffer.js"; describe("EditMessageSelector", () => { const createMockChatHistory = (count: number): ChatHistoryItem[] => {