Merge pull request #8127 from continuedev/tomasz/con-4265

Make it easy to edit messages in the CLI and to go back to an older message
This commit is contained in:
Tomasz Stefaniak 2025-10-09 12:25:30 -07:00 • committed by GitHub
commit 7318af41c1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 958 additions and 26 deletions

View file

@ -0,0 +1,202 @@
/**
* @vitest-environment jsdom
*/
import { render } from "@testing-library/react";
import type { ChatHistoryItem } from "core/index.js";
import React from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { EditMessageSelector } from "./EditMessageSelector.js";
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<typeof vi.fn>;
let mockOnExit: ReturnType<typeof vi.fn>;
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(
<EditMessageSelector
chatHistory={[]}
onEdit={mockOnEdit}
onExit={mockOnExit}
/>,
);
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(
<EditMessageSelector
chatHistory={chatHistory}
onEdit={mockOnEdit}
onExit={mockOnExit}
/>,
);
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(
<EditMessageSelector
chatHistory={chatHistory}
onEdit={mockOnEdit}
onExit={mockOnExit}
/>,
);
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(
<EditMessageSelector
chatHistory={chatHistory}
onEdit={mockOnEdit}
onExit={mockOnExit}
/>,
);
// 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(
<EditMessageSelector
chatHistory={chatHistory}
onEdit={mockOnEdit}
onExit={mockOnExit}
/>,
);
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(
<EditMessageSelector
chatHistory={chatHistory}
onEdit={mockOnEdit}
onExit={mockOnExit}
/>,
);
// 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(
<EditMessageSelector
chatHistory={chatHistory}
onEdit={mockOnEdit}
onExit={mockOnExit}
/>,
);
expect(container.textContent).toContain("First line");
expect(container.textContent).not.toContain("Second line");
});
});
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(
<EditMessageSelector
chatHistory={chatHistory}
onEdit={mockOnEdit}
onExit={mockOnExit}
/>,
);
// Should render something (component handles non-string content gracefully)
expect(container.textContent).toBeDefined();
});
});
});

View file

@ -0,0 +1,292 @@
import { Box, Text, useInput } from "ink";
import React, { useMemo, useState } from "react";
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<typeof useInput>[0];
type Key = Parameters<UseInputHandler>[1];
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(
Math.max(0, userMessages.length - 1),
);
const [isEditing, setIsEditing] = useState(false);
const [textBuffer] = useState(() => new TextBuffer());
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]) {
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]);
// 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 = getMessageContent(selectedIndex);
textBuffer.setText(content);
setEditText(content);
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);
}
} 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);
}
},
[
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) {
setSelectedIndex((prev) =>
prev > 0 ? prev - 1 : userMessages.length - 1,
);
}
} else if (key.downArrow || input === "j") {
// 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
// Only allow editing if there are messages
if (userMessages.length > 0) {
const content = getMessageContent(selectedIndex);
textBuffer.setCursor(content.length);
setCursorPosition(content.length);
setIsEditing(true);
}
} 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);
}
});
if (userMessages.length === 0) {
return (
<Box {...defaultBoxStyles("yellow")}>
<Text color="yellow">No user messages to edit.</Text>
<Text color="gray">Press Esc to exit</Text>
</Box>
);
}
const renderEditText = () => {
if (editText.length === 0) {
return (
<Text italic color="gray">
▋(empty message)
</Text>
);
}
// 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 (
<Box flexDirection="column">
{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 (
<Text key={lineIndex}>
{beforeCursor}
<Text inverse>{atCursor || " "}</Text>
{afterCursor}
</Text>
);
} else {
// Regular line - ensure empty lines still render
return <Text key={lineIndex}>{line || " "}</Text>;
}
})}
</Box>
);
};
return (
<Box {...defaultBoxStyles("yellow")}>
<Text color="yellow" bold>
Edit Message (Rewind Conversation)
</Text>
<Text color="gray">
{isEditing
? "Enter to submit, Esc to cancel, Shift+Enter for newline"
: "↑/↓ to navigate, Enter to edit, Esc to exit"}
</Text>
<Text> </Text>
{!isEditing && (
<>
<Text color="blue">Select a message to edit:</Text>
<Text> </Text>
{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 (
<Box key={msg.originalIndex} flexDirection="column">
<Text bold={isSelected} color={color}>
{indicator}Message {index + 1}: {preview}
{truncated}
</Text>
</Box>
);
})}
</>
)}
{isEditing && (
<>
<Text color="blue">
Editing Message {selectedIndex + 1} (will rewind to this point):
</Text>
<Text> </Text>
<Box
borderStyle="round"
borderColor="yellow"
paddingX={1}
flexDirection="column"
>
{renderEditText()}
</Box>
</>
)}
</Box>
);
}

View file

@ -212,7 +212,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
);
// Use login handlers
const { handleLoginPrompt, handleLoginTokenSubmit } = useLoginHandlers(
const { handleLoginTokenSubmit } = useLoginHandlers(
navigateTo,
navState,
closeCurrentScreen,
@ -266,6 +266,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
handleInterrupt,
handleFileAttached,
resetChatHistory,
handleEditMessage,
handleToolPermissionResponse,
} = useChat({
assistant: services.config?.config || undefined,
@ -281,9 +282,9 @@ const TUIChat: React.FC<TUIChatProps> = ({
onShowMCPSelector: () => navigateTo("mcp"),
onShowUpdateSelector: () => navigateTo("update"),
onShowSessionSelector: () => navigateTo("session"),
onLoginPrompt: handleLoginPrompt,
onReload: handleReload,
onClear: handleClear,
onRefreshStatic: () => setStaticRefreshTrigger((prev) => prev + 1),
// Remote mode configuration
isRemoteMode,
remoteUrl,
@ -420,6 +421,9 @@ const TUIChat: React.FC<TUIChatProps> = ({
isRemoteMode={isRemoteMode}
onImageInClipboardChange={setHasImageInClipboard}
diffContent={diffContent}
chatHistory={chatHistory}
handleEditMessage={handleEditMessage}
onShowEditSelector={() => navigateTo("edit")}
/>
{/* Resource debug bar - only in verbose mode */}

View file

@ -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";
@ -109,6 +109,7 @@ interface UserInputProps {
hideNormalUI?: boolean;
isRemoteMode?: boolean;
onImageInClipboardChange?: (hasImage: boolean) => void;
onShowEditSelector?: () => void;
}
const UserInput: React.FC<UserInputProps> = ({
@ -125,9 +126,11 @@ const UserInput: React.FC<UserInputProps> = ({
hideNormalUI = false,
isRemoteMode = false,
onImageInClipboardChange,
onShowEditSelector,
}) => {
const [textBuffer] = useState(() => new TextBuffer());
const [inputHistory] = useState(() => new InputHistory());
const lastEscapePressRef = useRef<number>(0);
// Stable callback for TextBuffer state changes to prevent race conditions
const onStateChange = useCallback(() => {
@ -625,6 +628,25 @@ const UserInput: React.FC<UserInputProps> = ({
return true;
}
// Handle double Esc to open edit message selector
const now = Date.now();
if (
inputMode &&
!showSlashCommands &&
!showFileSearch &&
!showBashMode &&
onShowEditSelector &&
now - lastEscapePressRef.current < 500
) {
// Double escape detected
onShowEditSelector();
lastEscapePressRef.current = 0; // Reset to prevent triple-escape
return true;
}
// Track single escape press
lastEscapePressRef.current = now;
return false;
};

View file

@ -0,0 +1,277 @@
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);
// 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
// Wait for UI to update
await new Promise((resolve) => setTimeout(resolve, 100));
// 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) => {
const { lastFrame, stdin } = renderInMode(mode);
// Open edit selector (double Esc)
stdin.write("\u001b");
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));
stdin.write("k"); // Up
await new Promise((resolve) => setTimeout(resolve, 50));
// 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) => {
const { lastFrame, stdin } = renderInMode(mode);
// Open edit selector
stdin.write("\u001b");
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));
// Verify edit selector is closed
frame = lastFrame();
expect(frame).toBeDefined();
expect(frame).not.toContain("No user messages to edit");
});
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");
stdin.write("\u001b"); // Open edit with separate Esc presses
await new Promise((resolve) => setTimeout(resolve, 100));
// 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, 100));
frame = lastFrame();
// UI should remain stable and edit selector should be closed
expect(frame).toBeDefined();
expect(frame!.length).toBeGreaterThan(0);
expect(frame).not.toContain("No user messages to edit");
},
);
});
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
// 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));
// Verify selector still did not open
frame = lastFrame();
expect(frame).toBeDefined();
expect(frame).not.toContain("No user messages to edit");
});
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();
},
);
});

View file

@ -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<string, Buffer>) => 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<ChatScreenContentProps> = ({
activePermissionRequest,
handleToolPermissionResponse,
handleUserMessage,
isWaitingForResponse,
isCompacting,
inputMode,
handleInterrupt,
assistant,
wasInterrupted,
handleFileAttached,
isInputDisabled,
isRemoteMode,
onImageInClipboardChange,
onShowEditSelector,
}) => {
if (activePermissionRequest) {
return (
<ToolPermissionSelector
toolName={activePermissionRequest.toolName}
toolArgs={activePermissionRequest.toolArgs}
requestId={activePermissionRequest.requestId}
toolCallPreview={activePermissionRequest.toolCallPreview}
hasDynamicEvaluation={activePermissionRequest.hasDynamicEvaluation}
onResponse={handleToolPermissionResponse}
/>
);
}
return (
<UserInput
onSubmit={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
isCompacting={isCompacting}
inputMode={inputMode}
onInterrupt={handleInterrupt}
assistant={assistant}
wasInterrupted={wasInterrupted}
onFileAttached={handleFileAttached}
disabled={isInputDisabled}
isRemoteMode={isRemoteMode}
onImageInClipboardChange={onImageInClipboardChange}
onShowEditSelector={onShowEditSelector}
/>
);
};

View file

@ -3,18 +3,21 @@ import React from "react";
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";
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;
@ -26,7 +29,7 @@ interface ScreenContentProps {
handleSessionSelect: (sessionId: string) => Promise<void>;
handleReload: () => Promise<void>;
closeCurrentScreen: () => void;
activePermissionRequest: any;
activePermissionRequest: ActivePermissionRequest | null;
handleToolPermissionResponse: (
requestId: string,
approved: boolean,
@ -44,6 +47,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 +83,9 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
isRemoteMode,
onImageInClipboardChange,
diffContent,
chatHistory = [],
handleEditMessage,
onShowEditSelector,
}) => {
if (hideScreenContent(services.update)) {
return null;
@ -162,33 +171,40 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
);
}
// Edit message selector
if (isScreenActive("edit")) {
return (
<EditMessageSelector
chatHistory={chatHistory}
onEdit={(messageIndex, newContent) => {
if (handleEditMessage) {
handleEditMessage(messageIndex, newContent);
}
closeCurrentScreen();
}}
onExit={closeCurrentScreen}
/>
);
}
// Chat screen with input area
if (isScreenActive("chat")) {
if (activePermissionRequest) {
return (
<ToolPermissionSelector
toolName={activePermissionRequest.toolName}
toolArgs={activePermissionRequest.toolArgs}
requestId={activePermissionRequest.requestId}
toolCallPreview={activePermissionRequest.toolCallPreview}
hasDynamicEvaluation={activePermissionRequest.hasDynamicEvaluation}
onResponse={handleToolPermissionResponse}
/>
);
}
return (
<UserInput
onSubmit={handleUserMessage}
<ChatScreenContent
activePermissionRequest={activePermissionRequest}
handleToolPermissionResponse={handleToolPermissionResponse}
handleUserMessage={handleUserMessage}
isWaitingForResponse={isWaitingForResponse}
isCompacting={isCompacting}
inputMode={inputMode}
onInterrupt={handleInterrupt}
handleInterrupt={handleInterrupt}
assistant={services.config?.config || undefined}
wasInterrupted={wasInterrupted}
onFileAttached={handleFileAttached}
disabled={isInputDisabled}
handleFileAttached={handleFileAttached}
isInputDisabled={isInputDisabled}
isRemoteMode={isRemoteMode}
onImageInClipboardChange={onImageInClipboardChange}
onShowEditSelector={onShowEditSelector}
/>
);
}

View file

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

View file

@ -58,8 +58,8 @@ export function useChat({
onShowUpdateSelector,
onShowMCPSelector,
onShowSessionSelector,
onLoginPrompt: _onLoginPrompt,
onClear,
onRefreshStatic,
isRemoteMode = false,
remoteUrl,
onShowDiff,
@ -455,7 +455,11 @@ export function useChat({
message: string,
imageMap?: Map<string, Buffer>,
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,
@ -524,7 +528,7 @@ export function useChat({
let currentChatHistory, currentCompactionIndex;
try {
const result = await handleAutoCompaction({
chatHistory,
chatHistory: currentHistory,
model,
llmApi,
compactionIndex,
@ -591,7 +595,7 @@ export function useChat({
let currentChatHistory, currentCompactionIndex;
try {
const result = await handleAutoCompaction({
chatHistory,
chatHistory: currentHistory,
model,
llmApi,
compactionIndex,
@ -721,6 +725,42 @@ export function useChat({
setQueuedMessages([]);
};
const handleEditMessage = async (
messageIndex: number,
newContent: string,
) => {
logger.debug("handleEditMessage called", {
messageIndex,
currentHistoryLength: chatHistory.length,
});
// Rewind chat history to exclude the message being edited
const rewindedHistory = chatHistory.slice(0, messageIndex);
logger.debug("Rewinding history for edit", {
from: chatHistory.length,
to: rewindedHistory.length,
});
// Clear any queued messages
setQueuedMessages([]);
// Clear attached files
setAttachedFiles([]);
// Update the session with the rewound history
updateSessionHistory(rewindedHistory);
// Force refresh of StaticChatContent to show truncated history
if (onRefreshStatic) {
onRefreshStatic();
}
// 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 (
requestId: string,
approved: boolean,
@ -803,6 +843,7 @@ export function useChat({
handleInterrupt,
handleFileAttached,
resetChatHistory,
handleEditMessage,
handleToolPermissionResponse,
};
}

View file

@ -18,9 +18,9 @@ export interface UseChatProps {
onShowUpdateSelector: () => void;
onShowModelSelector?: () => void;
onShowSessionSelector?: () => void;
onLoginPrompt?: (promptText: string) => Promise<string>;
onReload?: () => Promise<void>;
onClear?: () => void;
onRefreshStatic?: () => void;
// Remote mode props
isRemoteMode?: boolean;
remoteUrl?: string;
@ -38,6 +38,7 @@ export interface ActivePermissionRequest {
toolArgs: any;
requestId: string;
toolCallPreview?: ToolCallPreview[];
hasDynamicEvaluation?: boolean;
}
export interface RemoteServerState {