Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(chat): keep the corrected-retry path as on main; restore drafts per thread

M3gA-Mind8f5272def4df
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsx
index df61669c0d..dae6151237 100644
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@ -91,6 +91,7 @@ import {
truncateMessagesFrom,
updateThreadTitle,
} from '../../store/threadSlice';
+import { userScopedStorage } from '../../store/userScopedStorage';
import type { ConfirmationModal as ConfirmationModalType } from '../../types/intelligence';
import type { ThreadMessage } from '../../types/thread';
import { chatThreadPath } from '../../utils/chatRoutes';
@@ -110,7 +111,7 @@ import { StallWarning } from './aui/StallWarning';
import { ThreadWorkspaceChip } from './aui/ThreadWorkspaceChip';
import { useChatSurfaceRegistration } from './hooks/useChatSurfaceRegistration';
import { useThreadArtifactsHydration } from './hooks/useThreadArtifactsHydration';
-import { useThreadDraft } from './hooks/useThreadDraft';
+import { draftStorageKey, useThreadDraft } from './hooks/useThreadDraft';
import { ThreadList } from './threadList/ThreadList';
import { useThreadPins } from './threadList/useThreadPins';
import { useUnreadThreads } from './threadList/useUnreadThreads';
@@ -287,6 +288,10 @@ const Conversations = ({
// Per-thread, reload-surviving draft (`useThreadDraft`): switching threads
// swaps it instead of carrying half-typed text into the next conversation.
const [inputValue, setInputValue] = useThreadDraft(selectedThreadId ?? null);
+ // The live selection, for async send paths that finish after the user may
+ // have switched threads.
+ const selectedThreadIdRef = useRef(selectedThreadId);
+ selectedThreadIdRef.current = selectedThreadId;
const [attachments, setAttachments] = useState<Attachment[]>([]);
// Failed sends retain their attachments by originating thread. A send may
// reject after the user has navigated elsewhere, so restoring into the
@@ -1306,13 +1311,6 @@ const Conversations = ({
// A corrected retry must replace the already-persisted failed prompt;
// appending it would leave both prompts in the transcript. The edit
// operation truncates the failed tail and starts the corrected turn.
- await editMessage({
- threadId: sendingThreadId,
- messageId: previousFailedMessage.id,
- content: messageText,
- });
- // Only once the core accepted the edit: a failed edit leaves the
- // failed prompt in the core, so the transcript must keep it too.
dispatch(
truncateMessagesFrom({
threadId: sendingThreadId,
@@ -1320,6 +1318,11 @@ const Conversations = ({
inclusive: true,
})
);
+ await editMessage({
+ threadId: sendingThreadId,
+ messageId: previousFailedMessage.id,
+ content: messageText,
+ });
setInputValue('');
setAttachments([]);
attachmentsRef.current = [];
@@ -1350,14 +1353,17 @@ const Conversations = ({
}
const msg = error instanceof Error ? error.message : String(error);
setSendError(chatSendError('cloud_send_failed', msg));
- // assistant-ui already cleared the composer; restore the draft so a
- // failed persist or edit doesn't lose what the user typed.
- preserveSendErrorForRestoredDraftRef.current = true;
+ // assistant-ui already cleared the composer; give the draft back to its
+ // own thread so a failed persist doesn't lose what the user typed.
failedAttachmentsByThreadRef.current.set(sendingThreadId, pendingAttachments);
- setInputValue(normalized);
- if (selectedThreadId === sendingThreadId) {
+ if (selectedThreadIdRef.current === sendingThreadId) {
+ preserveSendErrorForRestoredDraftRef.current = true;
+ setInputValue(normalized);
attachmentsRef.current = pendingAttachments.slice();
setAttachments(pendingAttachments);
+ } else {
+ // The user moved on: keep it as that thread's draft, not this one's.
+ void userScopedStorage.setItem(draftStorageKey(sendingThreadId), normalized);
}
pendingSendsRef.current.delete(sendingThreadId);
removePendingSendingThread(sendingThreadId);
@@ -1367,6 +1373,7 @@ const Conversations = ({
setAttachments([]);
attachmentsRef.current = [];
failedAttachmentsByThreadRef.current.delete(sendingThreadId);
+ persistedFailedMessageByThreadRef.current.delete(sendingThreadId);
setSendError(null);
setAttachError(null);
// Silence watchdog: fires only if 120s pass without ANY inference signal
@@ -1400,10 +1407,6 @@ const Conversations = ({
send_mode: 'standard',
has_attachments: pendingAttachments.length > 0,
});
- // Only a send the core accepted retires the persisted prompt; after a
- // failed send it stays, so a corrected retry replaces it (edit) instead
- // of appending a second copy.
- persistedFailedMessageByThreadRef.current.delete(sendingThreadId);
// Backend accepted the send; lifecycle ('started' → 'streaming') now
// owns the `isSending` UI lock. Release the pending guard so the next
// user turn isn't blocked by a stale ref/state.
diff --git a/app/src/pages/__tests__/Conversations.render.test.tsx b/app/src/pages/__tests__/Conversations.render.test.tsx
index 00b2448dce..a7f6b6de2e 100644
--- a/app/src/pages/__tests__/Conversations.render.test.tsx
+++ b/app/src/pages/__tests__/Conversations.render.test.tsx
@@ -15,8 +15,9 @@ import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { SidebarSlotOutlet, SidebarSlotProvider } from '../../components/layout/shell/SidebarSlot';
+import { draftStorageKey } from '../../features/conversations/hooks/useThreadDraft';
import { threadApi } from '../../services/api/threadApi';
-import { chatCancel, chatRemoveQueueItem, chatSend, editMessage } from '../../services/chatService';
+import { chatCancel, chatRemoveQueueItem, chatSend } from '../../services/chatService';
import { CoreRpcError } from '../../services/coreRpcClient';
import chatRuntimeReducer, {
beginInferenceTurn,
@@ -34,8 +35,9 @@ import runModeReducer from '../../store/runModeSlice';
import socketReducer from '../../store/socketSlice';
import themeReducer from '../../store/themeSlice';
import threadGoalReducer from '../../store/threadGoalSlice';
-import threadReducer from '../../store/threadSlice';
+import threadReducer, { setSelectedThread } from '../../store/threadSlice';
import threadTodosReducer from '../../store/threadTodosSlice';
+import { userScopedStorage } from '../../store/userScopedStorage';
import type { Thread, ThreadMessage } from '../../types/thread';
// ── Hoisted mock state ─────────────────────────────────────────────────────
@@ -78,7 +80,6 @@ vi.mock('../../services/chatService', () => ({
chatClearQueue: vi.fn().mockResolvedValue(0),
chatRemoveQueueItem: vi.fn().mockResolvedValue(true),
chatSend: vi.fn().mockResolvedValue(undefined),
- editMessage: vi.fn().mockResolvedValue(undefined),
subscribeChatEvents: vi.fn(() => () => {}),
useRustChat: vi.fn(() => true),
}));
@@ -2262,30 +2263,39 @@ describe('Conversations — smoke render (#1123 welcome-lock removal)', () => {
await waitFor(() => expect(textarea).toHaveTextContent('do not lose me'));
});
- it('keeps the failed prompt in the transcript when the corrected retry edit fails', async () => {
- vi.mocked(chatSend).mockRejectedValueOnce(new Error('emit failed'));
+ it('gives a failed draft back to its own thread after the user switched away', async () => {
+ const saveDraft = vi.spyOn(userScopedStorage, 'setItem').mockResolvedValue(undefined);
+ let rejectPersist!: (reason: unknown) => void;
+ vi.mocked(threadApi.appendMessage).mockReturnValueOnce(
+ new Promise((_resolve, reject) => {
+ rejectPersist = reject;
+ })
+ );
const { store, textarea, thread } = await renderSelectedConversation();
await act(async () => {
- setComposerText(textarea, 'first try');
+ setComposerText(textarea, 'draft for the first thread');
});
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
});
- await waitFor(() => expect(chatSend).toHaveBeenCalledTimes(1));
- const transcript = () =>
- (store!.getState().thread.messagesByThreadId[thread.id] ?? []).map(m => m.content);
- await waitFor(() => expect(transcript()).toContain('first try'));
+ await waitFor(() => expect(threadApi.appendMessage).toHaveBeenCalled());
- vi.mocked(editMessage).mockRejectedValueOnce(new Error('edit failed'));
await act(async () => {
- setComposerText(textarea, 'second try');
+ store!.dispatch(setSelectedThread('another-thread'));
});
await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Send message' }));
+ rejectPersist(new Error('disk full'));
});
- await waitFor(() => expect(editMessage).toHaveBeenCalledTimes(1));
- expect(transcript()).toContain('first try');
- await waitFor(() => expect(textarea).toHaveTextContent('second try'));
+
+ const composer = await screen.findByRole('textbox', { name: 'Message input' });
+ expect(composer).not.toHaveTextContent('draft for the first thread');
+ await waitFor(() =>
+ expect(saveDraft).toHaveBeenCalledWith(
+ draftStorageKey(thread.id),
+ 'draft for the first thread'
+ )
+ );
+ saveDraft.mockRestore();
});
it('sends with Enter when the composer is not composing text', async () => {