From a2598819bb7d04b1edcbedccbf591f29d71336b7 Mon Sep 17 00:00:00 2001 From: Seydi Charyyev Date: Mon, 26 Oct 2026 11:59:14 +0000 Subject: [PATCH] fix(desktop): start the agent only once after a fork (#13139) Signed-off-by: Seydi Charyyev --- ui/desktop/src/hooks/useAutoSubmit.test.tsx | 125 ++++++++++++++++++- ui/desktop/src/hooks/useAutoSubmit.ts | 25 +++- ui/desktop/src/hooks/useChatSession.test.tsx | 80 ++++++++++++ ui/desktop/src/hooks/useChatSession.ts | 11 +- 4 files changed, 231 insertions(+), 10 deletions(-) create mode 100644 ui/desktop/src/hooks/useChatSession.test.tsx diff --git a/ui/desktop/src/hooks/useAutoSubmit.test.tsx b/ui/desktop/src/hooks/useAutoSubmit.test.tsx index b99a1b920..a961a881d 100644 --- a/ui/desktop/src/hooks/useAutoSubmit.test.tsx +++ b/ui/desktop/src/hooks/useAutoSubmit.test.tsx @@ -1,10 +1,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { renderHook } from '@testing-library/react'; -import { MemoryRouter } from 'react-router'; +import { act, render, renderHook } from '@testing-library/react'; +import { MemoryRouter, useLocation, useNavigate, type NavigateFunction } from 'react-router'; import type { PropsWithChildren } from 'react'; import { useAutoSubmit } from './useAutoSubmit'; import { ChatState } from '../types/chatState'; -import type { UserInput } from '../types/message'; +import { createUserMessage, type UserInput } from '../types/message'; import type { Session } from '../types/session'; function makeSession(overrides: Partial = {}): Session { @@ -25,6 +25,57 @@ const initialMessage: UserInput = { images: [], }; +type AutoSubmitProps = Parameters[0]; + +const forkedChatUrl = '/pair?resumeSessionId=sess-1&shouldStartAgent=true'; + +function AutoSubmitChat(props: AutoSubmitProps) { + useAutoSubmit(props); + return null; +} + +interface RouterHandle { + navigate: NavigateFunction; + search: string; +} + +// AppLayout renders the chats under a different parent while Settings is open, +// so they unmount there and mount again on the way back. +function renderChatWithSettingsRoute(props: AutoSubmitProps) { + const router = {} as RouterHandle; + + function ChatRoute({ chatProps }: { chatProps: AutoSubmitProps }) { + const location = useLocation(); + router.navigate = useNavigate(); + router.search = location.search; + return location.pathname === '/pair' ? : null; + } + + const view = render( + + + + ); + + const rerender = (nextProps: AutoSubmitProps) => + view.rerender( + + + + ); + + return { router, rerender }; +} + +function openSettingsAndGoBack(router: RouterHandle) { + act(() => { + void router.navigate('/settings'); + }); + act(() => { + void router.navigate(-1); + }); +} + describe('useAutoSubmit', () => { beforeEach(() => { vi.clearAllMocks(); @@ -90,4 +141,72 @@ describe('useAutoSubmit', () => { expect(handleSubmit).toHaveBeenCalledWith(initialMessage); expect(dispatchEventSpy).toHaveBeenCalledTimes(1); }); + + it('resumes once and does not resume again after Settings and Back', () => { + const handleSubmit = vi.fn(); + const { router } = renderChatWithSettingsRoute({ + sessionId: 'sess-1', + session: makeSession({ message_count: 2 }), + messages: [], + chatState: ChatState.Idle, + initialMessage: undefined, + canAutoSubmit: true, + handleSubmit, + }); + + expect(handleSubmit).toHaveBeenCalledTimes(1); + expect(handleSubmit).toHaveBeenCalledWith({ msg: '', images: [] }); + + openSettingsAndGoBack(router); + + expect(handleSubmit).toHaveBeenCalledTimes(1); + expect(router.search).toBe('?resumeSessionId=sess-1'); + }); + + it('sends the edited message of a fork once, also after Settings and Back', () => { + const handleSubmit = vi.fn(); + const props: AutoSubmitProps = { + sessionId: 'sess-1', + session: makeSession({ message_count: 1 }), + messages: [createUserMessage('Earlier question')], + chatState: ChatState.Idle, + initialMessage, + canAutoSubmit: true, + handleSubmit, + }; + const { router, rerender } = renderChatWithSettingsRoute(props); + + expect(handleSubmit).toHaveBeenCalledTimes(1); + expect(handleSubmit).toHaveBeenCalledWith(initialMessage); + + rerender({ ...props, initialMessage: undefined }); + openSettingsAndGoBack(router); + + expect(handleSubmit).toHaveBeenCalledTimes(1); + expect(router.search).toBe('?resumeSessionId=sess-1'); + }); + + it('sends the edited first message of a fork once, also after Settings and Back', () => { + // Editing the first message forks an empty session, so the new-session branch sends it. + const handleSubmit = vi.fn(); + const props: AutoSubmitProps = { + sessionId: 'sess-1', + session: makeSession({ message_count: 0 }), + messages: [], + chatState: ChatState.Idle, + initialMessage, + canAutoSubmit: true, + handleSubmit, + }; + const { router, rerender } = renderChatWithSettingsRoute(props); + + expect(handleSubmit).toHaveBeenCalledTimes(1); + expect(handleSubmit).toHaveBeenCalledWith(initialMessage); + + rerender({ ...props, session: makeSession({ message_count: 2 }), initialMessage: undefined }); + openSettingsAndGoBack(router); + + expect(handleSubmit).toHaveBeenCalledTimes(1); + expect(router.search).toBe('?resumeSessionId=sess-1'); + }); }); diff --git a/ui/desktop/src/hooks/useAutoSubmit.ts b/ui/desktop/src/hooks/useAutoSubmit.ts index 07c48a55e..c141e1d36 100644 --- a/ui/desktop/src/hooks/useAutoSubmit.ts +++ b/ui/desktop/src/hooks/useAutoSubmit.ts @@ -35,7 +35,7 @@ export function useAutoSubmit({ canAutoSubmit, handleSubmit, }: UseAutoSubmitProps): UseAutoSubmitReturn { - const [searchParams] = useSearchParams(); + const [searchParams, setSearchParams] = useSearchParams(); const hasAutoSubmittedRef = useRef(false); // Reset auto-submit flag when session changes @@ -69,10 +69,26 @@ export function useAutoSubmit({ return; } + // The ref resets when the chat remounts (opening Settings does that), so + // shouldStartAgent must also leave the URL to stay a one-shot trigger. + const markAutoSubmitted = () => { + hasAutoSubmittedRef.current = true; + if (shouldStartAgent) { + setSearchParams( + (prev) => { + const next = new URLSearchParams(prev); + next.delete('shouldStartAgent'); + return next; + }, + { replace: true } + ); + } + }; + // Scenario 1: New session with initial message from Hub // Hub always creates new sessions, so message_count will be 0 if (initialMessage && session.message_count === 0 && messages.length === 0) { - hasAutoSubmittedRef.current = true; + markAutoSubmitted(); handleSubmit(initialMessage); clearInitialMessage(); return; @@ -81,7 +97,7 @@ export function useAutoSubmit({ // Scenario 2: Forked session with edited message if (shouldStartAgent && initialMessage) { if (messages.length > 0) { - hasAutoSubmittedRef.current = true; + markAutoSubmitted(); handleSubmit(initialMessage); clearInitialMessage(); return; @@ -91,7 +107,7 @@ export function useAutoSubmit({ // Scenario 3: Resume with shouldStartAgent (continue existing conversation) if (shouldStartAgent) { - hasAutoSubmittedRef.current = true; + markAutoSubmitted(); handleSubmit({ msg: '', images: [] }); return; } @@ -99,6 +115,7 @@ export function useAutoSubmit({ session, initialMessage, searchParams, + setSearchParams, handleSubmit, sessionId, messages.length, diff --git a/ui/desktop/src/hooks/useChatSession.test.tsx b/ui/desktop/src/hooks/useChatSession.test.tsx new file mode 100644 index 000000000..a7a99a06f --- /dev/null +++ b/ui/desktop/src/hooks/useChatSession.test.tsx @@ -0,0 +1,80 @@ +import { act, renderHook } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + snapshot: undefined as unknown, + submitMessage: vi.fn(), +})); + +vi.mock('../acp/chatSessionController', () => ({ + acpChatSessionController: { + submitMessage: mocks.submitMessage, + loadSession: vi.fn(), + restoreSession: vi.fn(), + }, +})); + +vi.mock('../acp/chatSessionStore', () => ({ + useAcpChatSessionSnapshot: () => mocks.snapshot, + acpChatSessionStore: { getSnapshot: () => mocks.snapshot }, + acpChatSessionActions: { setMessages: vi.fn() }, +})); + +vi.mock('../acp/acpConnection', () => ({ + isAcpRecovering: () => false, +})); + +import { useChatSession } from './useChatSession'; +import { IntlTestWrapper } from '../i18n/test-utils'; +import { ChatState } from '../types/chatState'; +import { createUserMessage, type Message } from '../types/message'; + +function assistantMessage(text: string): Message { + return { + id: 'assistant-1', + role: 'assistant', + created: 0, + content: [{ type: 'text', text }], + metadata: { userVisible: true, agentVisible: true }, + }; +} + +function renderChatSession(messages: Message[]) { + mocks.snapshot = { + session: { id: 'sess-1' }, + messages, + chatState: ChatState.Idle, + pendingCancelPromptAttemptId: null, + activeRunId: null, + }; + return renderHook(() => useChatSession({ sessionId: 'sess-1', onStreamFinish: vi.fn() }), { + wrapper: IntlTestWrapper, + }); +} + +describe('useChatSession handleSubmit', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('does not send the last assistant message as a new prompt on an empty submit', async () => { + const { result } = renderChatSession([ + createUserMessage('Question'), + assistantMessage('Answer'), + ]); + + await act(() => result.current.handleSubmit({ msg: '', images: [] })); + + expect(mocks.submitMessage).not.toHaveBeenCalled(); + }); + + it('sends the last user message again on an empty submit', async () => { + const question = createUserMessage('Question'); + const { result } = renderChatSession([question]); + + await act(() => result.current.handleSubmit({ msg: '', images: [] })); + + expect(mocks.submitMessage).toHaveBeenCalledTimes(1); + expect(mocks.submitMessage).toHaveBeenCalledWith('sess-1', question, expect.anything()); + }); +}); diff --git a/ui/desktop/src/hooks/useChatSession.ts b/ui/desktop/src/hooks/useChatSession.ts index 50aed766c..c7748f350 100644 --- a/ui/desktop/src/hooks/useChatSession.ts +++ b/ui/desktop/src/hooks/useChatSession.ts @@ -198,9 +198,14 @@ export function useChatSession({ window.dispatchEvent(new CustomEvent(AppEvents.SESSION_CREATED)); } - const newMessage = hasNewMessage - ? createUserMessage(userMessage, images) - : currentMessages[currentMessages.length - 1]; + const lastMessage = currentMessages[currentMessages.length - 1]; + // An empty submit sends the last message again as the prompt; an assistant + // reply sent that way reaches the model as if the user had pasted it. + if (!hasNewMessage && lastMessage.role !== 'user') { + return; + } + + const newMessage = hasNewMessage ? createUserMessage(userMessage, images) : lastMessage; const messagesForStore = clearsConversation ? [] : hasNewMessage