fix(desktop): start the agent only once after a fork (#13139)
Signed-off-by: Seydi Charyyev <seydi.charyev@gmail.com>
This commit is contained in:
@@ -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> = {}): Session {
|
||||
@@ -25,6 +25,57 @@ const initialMessage: UserInput = {
|
||||
images: [],
|
||||
};
|
||||
|
||||
type AutoSubmitProps = Parameters<typeof useAutoSubmit>[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' ? <AutoSubmitChat {...chatProps} /> : null;
|
||||
}
|
||||
|
||||
const view = render(
|
||||
<MemoryRouter initialEntries={[forkedChatUrl]}>
|
||||
<ChatRoute chatProps={props} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const rerender = (nextProps: AutoSubmitProps) =>
|
||||
view.rerender(
|
||||
<MemoryRouter initialEntries={[forkedChatUrl]}>
|
||||
<ChatRoute chatProps={nextProps} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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());
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user