Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(chat): retry after a failed turn sends the attached files again (#17095)

Hazem Adel53cd8c865856
diff --git a/packages/web/src/app/routes/chat-with-ai/ai-chat-box.tsx b/packages/web/src/app/routes/chat-with-ai/ai-chat-box.tsx
index c0af6155ed4..4ff239227de 100644
--- a/packages/web/src/app/routes/chat-with-ai/ai-chat-box.tsx
+++ b/packages/web/src/app/routes/chat-with-ai/ai-chat-box.tsx
@@ -137,6 +137,7 @@ function ChatBoxContent({
isLoadingHistory,
error,
sendMessage,
+ retryLastMessage,
cancelStream,
setConversationId,
setModelPick,
@@ -255,8 +256,8 @@ function ChatBoxContent({
const handleRetry = useCallback(() => {
const lastUser = messages.findLast((m) => m.role === 'user');
if (lastUser && !pickUnavailable)
- void sendMessage(getTextFromParts(lastUser.parts));
- }, [messages, sendMessage, pickUnavailable]);
+ retryLastMessage(getTextFromParts(lastUser.parts)).catch(() => undefined);
+ }, [messages, retryLastMessage, pickUnavailable]);
const lastMessage = messages[messages.length - 1];
const lastAssistantMessage = useMemo(
diff --git a/packages/web/src/features/chat/lib/use-chat.ts b/packages/web/src/features/chat/lib/use-chat.ts
index 6339084f70b..4a65c8f8491 100644
--- a/packages/web/src/features/chat/lib/use-chat.ts
+++ b/packages/web/src/features/chat/lib/use-chat.ts
@@ -387,6 +387,7 @@ export function useAgentChat({
{ name: string; mimeType: AgentAllowedMimeType; data: string }[] | undefined
>(undefined);
const lastSentFileNamesRef = useRef<string[]>([]);
+ const lastSentRef = useRef<{ content: string; files?: File[] } | null>(null);
const conversationIdRef = useRef<string | null>(null);
const modelPickRef = useRef<ChatModelPick | null>(null);
const savedPickRef = useRef<ChatModelPick | null>(null);
@@ -810,6 +811,7 @@ export function useAgentChat({
const fileNames = files?.map((f) => f.name) ?? [];
lastSentFileNamesRef.current = fileNames;
+ lastSentRef.current = { content, files };
const optimisticUser: ChatUIMessage = {
id: `optimistic-${Date.now()}`,
@@ -950,6 +952,16 @@ export function useAgentChat({
],
);
+ const retryLastMessage = useCallback(
+ (fallbackContent: string) => {
+ const lastSent = lastSentRef.current;
+ return isNil(lastSent)
+ ? sendMessage(fallbackContent)
+ : sendMessage(lastSent.content, lastSent.files);
+ },
+ [sendMessage],
+ );
+
const setConversationId = useCallback(
async (id: string) => {
if (
@@ -969,6 +981,7 @@ export function useAgentChat({
pendingFilesRef.current = undefined;
lastSentFileNamesRef.current = [];
+ lastSentRef.current = null;
setOptimisticUserMessage(null);
setIsLoadingHistory(true);
@@ -1136,6 +1149,7 @@ export function useAgentChat({
isLoadingHistory,
error,
sendMessage,
+ retryLastMessage,
cancelStream,
setConversationId,
setModelPick,
diff --git a/packages/web/test/features/chat/lib/use-chat-retry.test.tsx b/packages/web/test/features/chat/lib/use-chat-retry.test.tsx
new file mode 100644
index 00000000000..e50641a970b
--- /dev/null
+++ b/packages/web/test/features/chat/lib/use-chat-retry.test.tsx
@@ -0,0 +1,89 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import React from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { chatApi } from '@/features/chat/lib/chat-api';
+import { ChatStoreProvider } from '@/features/chat/lib/chat-store-context';
+import { useAgentChat } from '@/features/chat/lib/use-chat';
+
+vi.mock('@/components/providers/socket-provider', () => ({
+ useSocket: () => ({ on: vi.fn(), off: vi.fn(), emit: vi.fn() }),
+}));
+
+vi.mock('@/features/chat/lib/chat-api', () => ({
+ chatApi: {
+ createConversation: vi.fn(async () => ({ id: 'conv-1' })),
+ getConversation: vi.fn(async () => ({ id: 'conv-1' })),
+ getMessages: vi.fn(async () => ({ data: [], next: null })),
+ sendMessage: vi.fn(async () => {
+ throw new Error('The model did not answer');
+ }),
+ cancelConversation: vi.fn(async () => undefined),
+ getPendingGate: vi.fn(async () => null),
+ getPickerConnections: vi.fn(async () => []),
+ },
+}));
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('useAgentChat retryLastMessage', () => {
+ it('resends the files of the last message', async () => {
+ const { result } = renderHook(() => useAgentChat(), { wrapper });
+ const file = new File(['hello'], 'notes.txt', { type: 'text/plain' });
+
+ await act(() => result.current.sendMessage('Summarise this file', [file]));
+ await act(() => result.current.retryLastMessage('Summarise this file'));
+
+ await waitFor(() => expect(sentFileNames()).toHaveLength(2));
+ expect(sentFileNames()).toEqual([['notes.txt'], ['notes.txt']]);
+ });
+
+ it('retries the message that failed, not an older one from the transcript', async () => {
+ const { result } = renderHook(() => useAgentChat(), { wrapper });
+ const file = new File(['hello'], 'notes.txt', { type: 'text/plain' });
+
+ await act(() => result.current.sendMessage('New question', [file]));
+ await act(() => result.current.retryLastMessage('Older question'));
+
+ await waitFor(() => expect(sentContents()).toHaveLength(2));
+ expect(sentContents()[1]).toBe('New question');
+ expect(sentFileNames()[1]).toEqual(['notes.txt']);
+ });
+
+ it('retries a message that only had a file', async () => {
+ const { result } = renderHook(() => useAgentChat(), { wrapper });
+ const file = new File(['hello'], 'notes.txt', { type: 'text/plain' });
+
+ await act(() => result.current.sendMessage('', [file]));
+ await act(() => result.current.retryLastMessage(''));
+
+ await waitFor(() => expect(sentFileNames()).toHaveLength(2));
+ expect(sentFileNames()[1]).toEqual(['notes.txt']);
+ });
+});
+
+function sentContents(): string[] {
+ return vi
+ .mocked(chatApi.sendMessage)
+ .mock.calls.map(([params]) => params.content);
+}
+
+function sentFileNames(): string[][] {
+ return vi
+ .mocked(chatApi.sendMessage)
+ .mock.calls.map(([params]) => (params.files ?? []).map((f) => f.name));
+}
+
+function wrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <QueryClientProvider client={new QueryClient()}>
+ <ChatStoreProvider>{children}</ChatStoreProvider>
+ </QueryClientProvider>
+ );
+}