Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions site/src/pages/AgentsPage/AgentChatPage.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3488,6 +3488,92 @@ export const QueuedSendPromotesPreviousHead: Story = {
},
};

const queuedEditChat: TypesGen.Chat = {
id: CHAT_ID,
...baseChatFields,
title: "Queued message edit",
status: "running",
};

const queuedEditMessages: TypesGen.ChatMessagesResponse = {
messages: compactCommandMessages.messages,
queued_messages: [
{
...MockChatQueuedMessage,
id: 61,
chat_id: CHAT_ID,
content: [{ type: "text", text: "Queued prompt" }],
},
],
has_more: false,
};

export const EditQueuedMessageReturnsItToComposer: Story = {
parameters: {
queries: buildQueries(queuedEditChat, queuedEditMessages, {
diffUrl: undefined,
}),
},
beforeEach: () => {
spyOn(API.experimental, "getUserSkills").mockResolvedValue([]);
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const deleteSpy = spyOn(
API.experimental,
"deleteChatQueuedMessage",
).mockResolvedValue(undefined);
// The delete invalidates the messages query; the refetch must show
// the drained queue.
spyOn(API.experimental, "getChatMessages").mockResolvedValue({
...queuedEditMessages,
queued_messages: [],
});
const sendSpy = spyOn(
API.experimental,
"createChatMessage",
).mockResolvedValue({
queued: true,
messages: [],
queued_message: {
...MockChatQueuedMessage,
id: 62,
chat_id: CHAT_ID,
content: [{ type: "text", text: "Queued prompt edited" }],
},
});

await userEvent.click(
await canvas.findByRole("button", { name: "Edit queued message" }),
);

await waitFor(() => {
expect(deleteSpy).toHaveBeenCalledWith(CHAT_ID, 61);
});
const editor = await canvas.findByTestId("chat-message-input");
await waitFor(() => expect(editor).toHaveTextContent("Queued prompt"));
expect(
canvas.queryByRole("button", { name: "Cancel editing" }),
).not.toBeInTheDocument();
expect(
canvas.queryByRole("button", { name: "Edit queued message" }),
).not.toBeInTheDocument();

await userEvent.click(editor);
await userEvent.type(editor, " edited");
await userEvent.keyboard("{Enter}");

await waitFor(() => {
expect(sendSpy).toHaveBeenCalledWith(
CHAT_ID,
expect.objectContaining({
content: [{ type: "text", text: "Queued prompt edited" }],
}),
);
});
},
};

const switchedChat: TypesGen.Chat = {
id: SWITCHED_CHAT_ID,
...baseChatFields,
Expand Down
49 changes: 49 additions & 0 deletions site/src/pages/AgentsPage/AgentChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ import {
useChatSelector,
useChatStore,
} from "./components/ChatConversation/chatStore";
import { getEditableContentPayload } from "./components/ChatConversation/messageParsing";
import { useChatToolInvalidations } from "./components/ChatConversation/useChatToolInvalidations";
import type { PendingAttachment } from "./components/ChatPageContent";
import { workspaceSkillsFromChat } from "./components/ChatPageContent";
Expand Down Expand Up @@ -585,6 +586,30 @@ export function useConversationEditingState(deps: {
setEditingFileBlocks(fileBlocks ?? []);
};

const loadDraftIntoComposer = (text: string) => {
setDraftState({
editorInitialValue: text,
initialEditorState: undefined,
});
serializedEditorStateRef.current = undefined;
setRemountKey((k) => k + 1);
inputValueRef.current = text;
if (draftStorageKey) {
try {
// Plain text is the legacy draft format parseStoredDraft still reads.
localStorage.setItem(draftStorageKey, text);
} catch {
// QuotaExceededError, silently discard the draft.
}
}
// Focus after the remount swaps in the new editor instance.
setTimeout(() => {
if (!isMobileViewport()) {
chatInputRef.current?.focus();
}
}, 0);
};

const handleCancelHistoryEdit = () => {
const savedText = draftBeforeHistoryEdit?.text ?? "";
const savedState = draftBeforeHistoryEdit?.editorState;
Expand Down Expand Up @@ -725,6 +750,7 @@ export function useConversationEditingState(deps: {
editingMessageId,
editingFileBlocks,
handleEditUserMessage,
loadDraftIntoComposer,
handleCancelHistoryEdit,
handleSendFromInput,
handleContentChange,
Expand Down Expand Up @@ -1498,6 +1524,28 @@ const AgentChatPage: FC = () => {
editing.handleEditUserMessage(...args);
};

const handleEditQueuedMessage = async (id: number) => {
const queuedMessage = store
.getSnapshot()
.queuedMessages.find((message) => message.id === id);
if (!queuedMessage) {
return;
}
const { text, fileBlocks } = getEditableContentPayload(
queuedMessage.content,
);
if (fileBlocks && fileBlocks.length > 0) {
return;
}
try {
await handleDeleteQueuedMessage(id);
} catch (error) {
toast.error(getErrorMessage(error, "Failed to edit queued message."));
throw error;
}
editing.loadDraftIntoComposer(text);
};

const chatTitle = chatQuery.data?.title;

const titleElement = (
Expand Down Expand Up @@ -2062,6 +2110,7 @@ const AgentChatPage: FC = () => {
handleInterrupt={handleInterrupt}
handleDeleteQueuedMessage={handleDeleteQueuedMessage}
handlePromoteQueuedMessage={handlePromoteQueuedMessage}
handleEditQueuedMessage={handleEditQueuedMessage}
onImplementPlan={handleImplementPlan}
onSendAskUserQuestionResponse={handleSendAskUserQuestionResponse}
handleArchiveAgentAction={handleArchiveAgentAction}
Expand Down
1 change: 1 addition & 0 deletions site/src/pages/AgentsPage/AgentChatPageView.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ const StoryAgentChatPageView: FC<StoryProps> = ({ editing, ...overrides }) => {
handleInterrupt: fn(),
handleDeleteQueuedMessage: fn(),
handlePromoteQueuedMessage: fn(),
handleEditQueuedMessage: fn(),
handleArchiveAgentAction: fn(),
handleUnarchiveAgentAction: fn(),
handleArchiveAndDeleteWorkspaceAction: fn(),
Expand Down
3 changes: 3 additions & 0 deletions site/src/pages/AgentsPage/AgentChatPageView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ interface AgentChatPageViewProps {
handleInterrupt: () => void;
handleDeleteQueuedMessage: (id: number) => Promise<void>;
handlePromoteQueuedMessage: (id: number) => Promise<void>;
handleEditQueuedMessage: (id: number) => Promise<void>;

onImplementPlan?: () => Promise<void> | void;
onSendAskUserQuestionResponse?: (message: string) => Promise<void> | void;
Expand Down Expand Up @@ -373,6 +374,7 @@ export const AgentChatPageView: FC<AgentChatPageViewProps> = ({
handleInterrupt,
handleDeleteQueuedMessage,
handlePromoteQueuedMessage,
handleEditQueuedMessage,
onImplementPlan,
onSendAskUserQuestionResponse,
handleArchiveAgentAction,
Expand Down Expand Up @@ -999,6 +1001,7 @@ export const AgentChatPageView: FC<AgentChatPageViewProps> = ({
onSend={editing.handleSendFromInput}
onDeleteQueuedMessage={handleDeleteQueuedMessage}
onPromoteQueuedMessage={handlePromoteQueuedMessage}
onEditQueuedMessage={handleEditQueuedMessage}
onInterrupt={handleInterrupt}
isInputDisabled={isInputDisabled}
isSendPending={isSubmissionPending}
Expand Down
8 changes: 8 additions & 0 deletions site/src/pages/AgentsPage/components/AgentChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ interface AgentChatInputProps {
queuedMessages?: readonly ChatQueuedMessage[];
onDeleteQueuedMessage?: (id: number) => Promise<void> | void;
onPromoteQueuedMessage?: (id: number) => Promise<void> | void;
onEditQueuedMessage?: (id: number) => Promise<void> | void;
// History editing state, owned by the parent.
isEditingHistoryMessage?: boolean;
onCancelHistoryEdit?: () => void;
Expand Down Expand Up @@ -376,6 +377,7 @@ export const AgentChatInput: FC<AgentChatInputProps> = ({
queuedMessages = [],
onDeleteQueuedMessage,
onPromoteQueuedMessage,
onEditQueuedMessage,
isEditingHistoryMessage = false,
onCancelHistoryEdit,
userPromptHistory = [],
Expand Down Expand Up @@ -1062,6 +1064,12 @@ export const AgentChatInput: FC<AgentChatInputProps> = ({
messages={queuedMessages}
onDelete={(id) => onDeleteQueuedMessage?.(id)}
onPromote={(id) => onPromoteQueuedMessage?.(id)}
onEdit={onEditQueuedMessage}
editDisabledReason={
isComposerEffectivelyEmpty
? undefined
: "Send or clear the composer to edit a queued message."
}
className="mb-2"
/>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -325,14 +325,21 @@ export const getEditableUserMessagePayload = (
): {
text: string;
fileBlocks: readonly TypesGen.ChatMessagePart[] | undefined;
} => getEditableContentPayload(message.content);

export const getEditableContentPayload = (
content: readonly TypesGen.ChatMessagePart[] | undefined,
): {
text: string;
fileBlocks: readonly TypesGen.ChatMessagePart[] | undefined;
} => {
// Concatenate text parts verbatim to match the server-side string_agg in
// GetChatUserPromptsByChatID; parseMessageContent/appendText is for streaming and drops whitespace-only chunks.
const text = (message.content ?? [])
const text = (content ?? [])
.filter((part): part is TypesGen.ChatTextPart => part.type === "text")
.map((part) => part.text)
.join("");
const parsed = parseMessageContent(message.content);
const parsed = parseMessageContent(content);
const fileBlocks = parsed.blocks.filter(isEditableUserMessageFileBlock);
return {
text,
Expand Down
3 changes: 3 additions & 0 deletions site/src/pages/AgentsPage/components/ChatPageContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ interface ChatPageInputProps {
sendShortcut: AgentChatSendShortcut;
onDeleteQueuedMessage: (id: number) => Promise<void>;
onPromoteQueuedMessage: (id: number) => Promise<void>;
onEditQueuedMessage?: (id: number) => Promise<void>;
onInterrupt: () => void;
isInputDisabled: boolean;
isSendPending: boolean;
Expand Down Expand Up @@ -317,6 +318,7 @@ export const ChatPageInput: FC<ChatPageInputProps> = ({
sendShortcut,
onDeleteQueuedMessage,
onPromoteQueuedMessage,
onEditQueuedMessage,
onInterrupt,
isInputDisabled,
isSendPending,
Expand Down Expand Up @@ -567,6 +569,7 @@ export const ChatPageInput: FC<ChatPageInputProps> = ({
queuedMessages={queuedMessages}
onDeleteQueuedMessage={onDeleteQueuedMessage}
onPromoteQueuedMessage={onPromoteQueuedMessage}
onEditQueuedMessage={onEditQueuedMessage}
isEditingHistoryMessage={isEditing}
onCancelHistoryEdit={onCancelHistoryEdit}
userPromptHistory={userPromptHistory}
Expand Down
Loading
Loading