Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🔓 fix: Keep Code Approval Mode Selectable Mid-Run (#15938)

Danny Avilad9c5d1c8d6f1
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 6bc3a9715b..b15d711652 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -855,7 +855,7 @@ const ChatForm = memo(function ChatForm({
conversation={conversation}
addedConversation={addedConvo}
setConversation={setConversation}
- disabled={disableInputs || isSubmitting}
+ disabled={disableInputs}
/>
{index === 0 && conversationId != null && (
<PendingToolApprovalButton conversationId={conversationId} />
diff --git a/client/src/components/Chat/Input/CodeApprovalMenu.tsx b/client/src/components/Chat/Input/CodeApprovalMenu.tsx
index d4e78ec4b7..85446bf57e 100644
--- a/client/src/components/Chat/Input/CodeApprovalMenu.tsx
+++ b/client/src/components/Chat/Input/CodeApprovalMenu.tsx
@@ -1,4 +1,6 @@
import * as Ariakit from '@ariakit/react';
+import { useQueryClient } from '@tanstack/react-query';
+import { QueryKeys, Constants } from 'librechat-data-provider';
import { TooltipAnchor, composerControlClasses } from '@librechat/client';
import { Check, ChevronDown, FilePen, FileQuestionMark, FileTerminal } from 'lucide-react';
import type { CodeApprovalMode, TConversation } from 'librechat-data-provider';
@@ -47,6 +49,7 @@ export default function CodeApprovalMenu({
disabled: boolean;
}) {
const localize = useLocalize();
+ const queryClient = useQueryClient();
const { available, modes, selected } = useCodeApprovalMode(conversation, addedConversation);
const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' });
const isOpen = menuStore.useState('open');
@@ -55,6 +58,11 @@ export default function CodeApprovalMenu({
return null;
}
+ /** Navigation and run recovery rebuild the conversation from its detail
+ * cache, so the pick lands there too, seeding the record from the live
+ * conversation when none exists yet (the resumable transport seeds the same
+ * key optimistically). A chat that has no id yet keeps the pick in
+ * conversation state alone until the run assigns one. */
const selectMode = (mode: CodeApprovalMode) => {
if (!modes.includes(mode)) {
return;
@@ -62,6 +70,15 @@ export default function CodeApprovalMenu({
setConversation((current) =>
current == null ? current : { ...current, codeApprovalMode: mode },
);
+ const record = conversation;
+ const conversationId = record?.conversationId;
+ if (record == null || conversationId == null || conversationId === Constants.NEW_CONVO) {
+ return;
+ }
+ queryClient.setQueryData<TConversation>([QueryKeys.conversation, conversationId], (cached) => ({
+ ...(cached ?? record),
+ codeApprovalMode: mode,
+ }));
};
const SelectedIcon = modeOptions[selected].icon;
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx
new file mode 100644
index 0000000000..b0d2ba31e9
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx
@@ -0,0 +1,122 @@
+import React, { useMemo, useState } from 'react';
+import '@testing-library/jest-dom';
+import { DndProvider } from 'react-dnd';
+import { useForm } from 'react-hook-form';
+import { RecoilRoot, useRecoilState } from 'recoil';
+import { HTML5Backend } from 'react-dnd-html5-backend';
+import { render, screen } from '@testing-library/react';
+import { BrowserRouter as Router } from 'react-router-dom';
+import { QueryKeys, EModelEndpoint } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TFile, TConversation } from 'librechat-data-provider';
+import type { ChatFormValues } from '~/common';
+import { ChatContext, ChatFormProvider } from '~/Providers';
+import { AuthContextProvider } from '~/hooks/AuthContext';
+import ChatForm from '../ChatForm';
+import store from '~/store';
+
+jest.mock('~/hooks/Agents/useCodeApprovalMode', () => ({
+ __esModule: true,
+ ...jest.requireActual('~/hooks/Agents/useCodeApprovalMode'),
+ default: () => ({
+ available: true,
+ modes: ['ask', 'acceptEdits'],
+ selected: 'ask',
+ }),
+}));
+
+const conversation = {
+ conversationId: 'conversation-1',
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent-1',
+ title: 'Code',
+} as TConversation;
+
+function Harness() {
+ const [files, setFiles] = useRecoilState(store.filesByIndex(0));
+ const [isSubmitting] = useRecoilState(store.isSubmittingFamily(0));
+ const [, setFilesLoading] = useState(false);
+ const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });
+
+ const chatHelpers = useMemo(
+ () =>
+ ({
+ index: 0,
+ conversation,
+ setConversation: () => undefined,
+ files,
+ setFiles,
+ isSubmitting,
+ setIsSubmitting: () => undefined,
+ filesLoading: false,
+ setFilesLoading,
+ newConversation: () => undefined,
+ handleStopGenerating: () => undefined,
+ stopGenerating: () => undefined,
+ getMessages: () => undefined,
+ setMessages: () => undefined,
+ ask: () => undefined,
+ regenerate: () => undefined,
+ setSiblingIdx: () => undefined,
+ showPopover: false,
+ setShowPopover: () => undefined,
+ abortScroll: false,
+ setAbortScroll: () => undefined,
+ preset: null,
+ setPreset: () => undefined,
+ optionSettings: {},
+ setOptionSettings: () => undefined,
+ handleRegenerate: () => undefined,
+ handleContinue: () => undefined,
+ }) as unknown as React.ContextType<typeof ChatContext>,
+ [files, setFiles, isSubmitting],
+ );
+
+ return (
+ <ChatFormProvider {...methods}>
+ <ChatContext.Provider value={chatHelpers}>
+ <ChatForm index={0} isLandingPage={false} footerBelow={false} centerFormOnLanding={false} />
+ </ChatContext.Provider>
+ </ChatFormProvider>
+ );
+}
+
+function renderComposer({ submitting }: { submitting: boolean }) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ queryClient.setQueryData<TFile[]>([QueryKeys.files], []);
+ queryClient.setQueryData([QueryKeys.endpoints], { [EModelEndpoint.agents]: { order: 0 } });
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot initializeState={({ set }) => set(store.isSubmittingFamily(0), submitting)}>
+ <Router>
+ <AuthContextProvider authConfig={{ loginRedirect: '', test: true }}>
+ <DndProvider backend={HTML5Backend}>
+ <Harness />
+ </DndProvider>
+ </AuthContextProvider>
+ </Router>
+ </RecoilRoot>
+ </QueryClientProvider>,
+ );
+}
+
+describe('ChatForm code approval mode', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ test('keeps the mode selector usable while a run is in flight', async () => {
+ renderComposer({ submitting: true });
+
+ expect(await screen.findByTestId('code-approval-mode')).toBeEnabled();
+ }, 20000);
+
+ test('keeps the mode selector usable between runs', async () => {
+ renderComposer({ submitting: false });
+
+ expect(await screen.findByTestId('code-approval-mode')).toBeEnabled();
+ }, 20000);
+});
diff --git a/client/src/components/Chat/Input/__tests__/CodeApprovalMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/CodeApprovalMenu.spec.tsx
index 753aa3df7c..4d48c8981e 100644
--- a/client/src/components/Chat/Input/__tests__/CodeApprovalMenu.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/CodeApprovalMenu.spec.tsx
@@ -1,5 +1,7 @@
import userEvent from '@testing-library/user-event';
+import { QueryKeys, Constants } from 'librechat-data-provider';
import { render, screen, within } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TConversation } from 'librechat-data-provider';
import CodeApprovalMenu from '../CodeApprovalMenu';
@@ -28,14 +30,20 @@ describe('CodeApprovalMenu', () => {
});
});
- const renderMenu = () =>
- render(
- <CodeApprovalMenu
- conversation={conversation}
- setConversation={mockSetConversation}
- disabled={false}
- />,
+ let queryClient: QueryClient;
+
+ const renderMenu = () => {
+ queryClient = new QueryClient();
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <CodeApprovalMenu
+ conversation={conversation}
+ setConversation={mockSetConversation}
+ disabled={false}
+ />
+ </QueryClientProvider>,
);
+ };
test('defaults to ask and stores accept-edits on the conversation', async () => {
renderMenu();
@@ -47,6 +55,46 @@ describe('CodeApprovalMenu', () => {
expect(update(conversation)).toEqual({ ...conversation, codeApprovalMode: 'acceptEdits' });
});
+ test('writes the pick into the conversation detail cache', async () => {
+ renderMenu();
+ const key = [QueryKeys.conversation, conversation.conversationId];
+ queryClient.setQueryData<TConversation>(key, { ...conversation, codeApprovalMode: 'ask' });
+
+ await userEvent.click(screen.getByTestId('code-approval-mode'));
+ await userEvent.click(await screen.findByText('com_ui_code_approval_accept_edits'));
+
+ expect(queryClient.getQueryData<TConversation>(key)?.codeApprovalMode).toBe('acceptEdits');
+ });
+
+ test('seeds a detail record from the live conversation when none exists yet', async () => {
+ renderMenu();
+
+ await userEvent.click(screen.getByTestId('code-approval-mode'));
+ await userEvent.click(await screen.findByText('com_ui_code_approval_accept_edits'));
+
+ expect(queryClient.getQueryData([QueryKeys.conversation, conversation.conversationId])).toEqual(
+ { ...conversation, codeApprovalMode: 'acceptEdits' },
+ );
+ });
+
+ test('leaves the detail cache alone for a chat that has no id yet', async () => {
+ queryClient = new QueryClient();
+ render(
+ <QueryClientProvider client={queryClient}>
+ <CodeApprovalMenu
+ conversation={{ ...conversation, conversationId: Constants.NEW_CONVO as string }}
+ setConversation={mockSetConversation}
+ disabled={false}
+ />
+ </QueryClientProvider>,
+ );
+
+ await userEvent.click(screen.getByTestId('code-approval-mode'));
+ await userEvent.click(await screen.findByText('com_ui_code_approval_accept_edits'));
+
+ expect(queryClient.getQueryData([QueryKeys.conversation, Constants.NEW_CONVO])).toBeUndefined();
+ });
+
test('offers every mode as a radio and marks the selected one', async () => {
renderMenu();
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index f922db8a3f..4ad5ab196b 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -168,6 +168,7 @@ describe('useChatFunctions ask', () => {
const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
expect(submission.codeApprovalMode).toBe('acceptEdits');
+ expect(submission.conversation.codeApprovalMode).toBe('acceptEdits');
});
it('preallocates a durable Agents user id for the optimistic response anchor', () => {
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index d1e8ab1499..80eca799dc 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -740,6 +740,7 @@ export default function useChatFunctions({
conversation: {
...conversation,
...(chatProjectId ? { chatProjectId } : {}),
+ ...(latestCodeApprovalMode != null ? { codeApprovalMode: latestCodeApprovalMode } : {}),
conversationId,
},
endpointOption,
diff --git a/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts b/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
index 08fb694367..524b696638 100644
--- a/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useEventHandlers.spec.ts
@@ -1,9 +1,11 @@
import { Constants } from 'librechat-data-provider';
-import type { EventSubmission, TMessage } from 'librechat-data-provider';
+import type { EventSubmission, TMessage, TConversation } from 'librechat-data-provider';
import {
buildCreatedInitialResponse,
getExistingConversationAbortMessages,
isInitialNewConversationSubmission,
+ keepLocalCodeApprovalMode,
+ buildRecoveryPreset,
mergeErrorMessages,
mergeRegenerateFinalMessages,
startedAsNewConversation,
@@ -289,3 +291,64 @@ describe('mergeErrorMessages', () => {
expect(merged[1]).toEqual(errorMessage);
});
});
+
+describe('keepLocalCodeApprovalMode', () => {
+ const server = { conversationId: 'conversation-1', codeApprovalMode: 'ask' } as TConversation;
+ const local = {
+ conversationId: 'conversation-1',
+ codeApprovalMode: 'acceptEdits',
+ } as TConversation;
+
+ it('keeps a locally picked mode over the server copy', () => {
+ expect(keepLocalCodeApprovalMode(server, local, 'conversation-1').codeApprovalMode).toBe(
+ 'acceptEdits',
+ );
+ });
+
+ it('lets the server copy win when nothing was picked locally', () => {
+ const unset = { conversationId: 'conversation-1' } as TConversation;
+ expect(keepLocalCodeApprovalMode(server, unset, 'conversation-1')).toBe(server);
+ expect(keepLocalCodeApprovalMode(server, null, 'conversation-1')).toBe(server);
+ });
+
+ it('ignores the mode of a conversation the user navigated to mid-run', () => {
+ const elsewhere = { conversationId: 'conversation-2', codeApprovalMode: 'fullAccess' };
+ expect(keepLocalCodeApprovalMode(server, elsewhere as TConversation, 'conversation-1')).toBe(
+ server,
+ );
+ });
+
+ it('follows a new chat to the id the server assigned', () => {
+ const assigned = { conversationId: 'server-id', codeApprovalMode: 'acceptEdits' };
+ expect(
+ keepLocalCodeApprovalMode(
+ { conversationId: 'server-id' } as TConversation,
+ assigned as TConversation,
+ 'server-id',
+ ).codeApprovalMode,
+ ).toBe('acceptEdits');
+ expect(keepLocalCodeApprovalMode(server, assigned as TConversation, Constants.NEW_CONVO)).toBe(
+ server,
+ );
+ });
+});
+
+describe('buildRecoveryPreset', () => {
+ const sent = {
+ conversationId: 'conversation-1',
+ endpoint: 'agents',
+ agent_id: 'agent-1',
+ codeApprovalMode: 'ask',
+ } as TConversation;
+
+ it('carries the mode the detail cache holds for the rebuilt conversation', () => {
+ const cached = { ...sent, codeApprovalMode: 'acceptEdits' } as TConversation;
+ const preset = buildRecoveryPreset(sent, cached, 'conversation-1');
+ expect(preset.codeApprovalMode).toBe('acceptEdits');
+ expect(preset.agent_id).toBe('agent-1');
+ });
+
+ it('falls back to the sent mode when no record exists', () => {
+ expect(buildRecoveryPreset(sent, undefined, '_fresh').codeApprovalMode).toBe('ask');
+ });
+});
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index a42af9fa7c..a0adf1d577 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -1470,6 +1470,44 @@ describe('useResumableSSE', () => {
unmount();
});
+ it('keeps a mode picked while a settled start was pending', async () => {
+ (request.post as jest.Mock).mockResolvedValue({
+ conversationId: CONV_ID,
+ status: 'settled',
+ generationProtocolVersion: 2,
+ });
+ mockGetConversationById.mockResolvedValue({
+ conversationId: CONV_ID,
+ endpoint: 'agents',
+ codeApprovalMode: 'fullAccess',
+ });
+ mockGetQueryData.mockImplementation((queryKey: unknown[]) =>
+ queryKey[0] === QueryKeys.conversation
+ ? { conversationId: CONV_ID, codeApprovalMode: 'ask' }
+ : undefined,
+ );
+ const chatHelpers = buildChatHelpers();
+
+ const { unmount } = renderHook(() => useResumableSSE(buildSubmission(), chatHelpers));
+
+ await waitFor(() => {
+ expect(chatHelpers.setConversation).toHaveBeenCalled();
+ });
+
+ const update = chatHelpers.setConversation.mock.calls.at(-1)?.[0];
+ expect(update({ conversationId: CONV_ID, codeApprovalMode: 'ask' }).codeApprovalMode).toBe(
+ 'ask',
+ );
+ expect(
+ update({ conversationId: 'conv-elsewhere', codeApprovalMode: 'ask' }).codeApprovalMode,
+ ).toBe('fullAccess');
+ expect(mockSetQueryData).toHaveBeenCalledWith(
+ [QueryKeys.conversation, CONV_ID],
+ expect.objectContaining({ codeApprovalMode: 'ask' }),
+ );
+ unmount();
+ });
+
it.each(['settled', 'replaced'] as const)(
'rejects an unnegotiated %s start control response',
async (status) => {
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index fcef419cf7..dbc285664c 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -14,6 +14,7 @@ import {
isAssistantsEndpoint,
} from 'librechat-data-provider';
import type {
+ TPreset,
TMessage,
TConversation,
EventSubmission,
@@ -298,6 +299,38 @@ const createErrorMessage = ({
return tMessageSchema.parse(errorMessage) as TMessage;
};
+/**
+ * A code approval mode picked locally is newer than any server copy of the
+ * conversation: the final and abort events return the mode the run STARTED
+ * with, and error recovery rebuilds from the pre-run capture. The local mode
+ * therefore survives every merge and the next send carries it. Identity is
+ * checked because the conversation atom is index-global: after navigating
+ * elsewhere mid-run, that conversation's mode must not land in this one.
+ */
+export const keepLocalCodeApprovalMode = <T extends Partial<TConversation>>(
+ merged: T,
+ local: Partial<TConversation> | null | undefined,
+ conversationId: string | null | undefined,
+): T => {
+ const localMode = local?.codeApprovalMode;
+ if (localMode == null || local?.conversationId !== conversationId) {
+ return merged;
+ }
+ return merged.codeApprovalMode === localMode
+ ? merged
+ : { ...merged, codeApprovalMode: localMode };
+};
+
+/** Preset for a conversation rebuilt after a failed or aborted run. The detail
+ * cache holds a mode picked while that run streamed; the capture only the
+ * pre-run one. */
+export const buildRecoveryPreset = (
+ submissionConvo: Partial<TConversation>,
+ cachedConvo: TConversation | null | undefined,
+ conversationId: string,
+): TPreset =>
+ tPresetSchema.parse(keepLocalCodeApprovalMode(submissionConvo, cachedConvo, conversationId));
+
export const getConvoTitle = ({
parentId,
queryClient,
@@ -349,6 +382,22 @@ export default function useEventHandlers({
* would inherit a stale baseline. Navigation teardown deliberately does not
* clear it — a reattach to a still-live run keeps its original start. */
const setSubmissionStart = useSetRecoilState(store.submissionStartFamily(runIndex));
+ const recoverConversation = useCallback(
+ (conversationId: string, submission: EventSubmission) => {
+ if (!newConversation) {
+ return;
+ }
+ const cachedConvo = queryClient.getQueryData<TConversation>([
+ QueryKeys.conversation,
+ conversationId,
+ ]);
+ newConversation({
+ template: { conversationId },
+ preset: buildRecoveryPreset(submission.conversation, cachedConvo, conversationId),
+ });
+ },
+ [newConversation, queryClient],
+ );
const navigate = useNavigate();
const location = useLocation();
@@ -510,10 +559,13 @@ export default function useEventHandlers({
}
if (setConversation && !isAddedRequest) {
- setConversation((prevState) => {
- const update = { ...prevState, ...convoUpdate };
- return update;
- });
+ setConversation((prevState) =>
+ keepLocalCodeApprovalMode(
+ { ...prevState, ...convoUpdate },
+ prevState,
+ convoUpdate.conversationId,
+ ),
+ );
}
setIsSubmitting(false);
@@ -923,10 +975,11 @@ export default function useEventHandlers({
* generating before the Stop, so the local one stays in sync. */
if (setConversation && isAddedRequest !== true) {
setConversation((prevState) => {
- const update = {
- ...prevState,
- ...(conversation as TConversation),
- };
+ const update = keepLocalCodeApprovalMode(
+ { ...prevState, ...(conversation as TConversation) },
+ prevState,
+ conversation.conversationId,
+ );
if (prevState?.model != null && prevState.model !== submissionConvo.model) {
update.model = prevState.model;
}
@@ -938,10 +991,13 @@ export default function useEventHandlers({
queryClient.setQueryData<TConversation>(
[QueryKeys.conversation, conversation.conversationId],
(cachedConvo) => {
- const merged = {
- ...cachedConvo,
- ...serverConversation,
- } as TConversation;
+ const merged = keepLocalCodeApprovalMode(
+ { ...cachedConvo, ...serverConversation } as TConversation,
+ prevState?.conversationId === conversation.conversationId
+ ? prevState
+ : cachedConvo,
+ conversation.conversationId,
+ );
const cachedTitle = cachedConvo?.title;
if (!hasRealTitle(serverConversation.title) && hasRealTitle(cachedTitle)) {
merged.title = cachedTitle;
@@ -1042,12 +1098,7 @@ export default function useEventHandlers({
submission,
});
setErrorMessages(convoId, errorResponse);
- if (newConversation) {
- newConversation({
- template: { conversationId: convoId },
- preset: tPresetSchema.parse(submission.conversation),
- });
- }
+ recoverConversation(convoId, submission);
setIsSubmitting(false);
return;
}
@@ -1057,12 +1108,7 @@ export default function useEventHandlers({
const convoId = `_${v4()}`;
const errorResponse = parseErrorResponse(data);
setErrorMessages(convoId, errorResponse);
- if (newConversation) {
- newConversation({
- template: { conversationId: convoId },
- preset: tPresetSchema.parse(submission.conversation),
- });
- }
+ recoverConversation(convoId, submission);
setIsSubmitting(false);
return;
} else if (!receivedConvoId) {
@@ -1079,11 +1125,8 @@ export default function useEventHandlers({
}) as TMessage;
setErrorMessages(receivedConvoId, errorResponse);
- if (receivedConvoId && paramId === Constants.NEW_CONVO && newConversation) {
- newConversation({
- template: { conversationId: receivedConvoId },
- preset: tPresetSchema.parse(submission.conversation),
- });
+ if (receivedConvoId && paramId === Constants.NEW_CONVO) {
+ recoverConversation(receivedConvoId, submission);
}
setIsSubmitting(false);
@@ -1093,11 +1136,11 @@ export default function useEventHandlers({
setCompleted,
setMessages,
paramId,
- newConversation,
setIsSubmitting,
setSubmissionStart,
getMessages,
queryClient,
+ recoverConversation,
],
);
@@ -1149,12 +1192,7 @@ export default function useEventHandlers({
} else if (!isAssistantsEndpoint(endpoint)) {
const convoId = conversationId || `_${v4()}`;
logger.log('conversation', 'Aborted conversation with minimal messages, ID: ' + convoId);
- if (newConversation) {
- newConversation({
- template: { conversationId: convoId },
- preset: tPresetSchema.parse(submission.conversation),
- });
- }
+ recoverConversation(convoId, submission);
setIsSubmitting(false);
return;
}
@@ -1202,12 +1240,7 @@ export default function useEventHandlers({
error,
});
setMessages([...submission.messages, submission.userMessage, errorResponse]);
- if (newConversation) {
- newConversation({
- template: { conversationId: conversationId || errorResponse.conversationId || v4() },
- preset: tPresetSchema.parse(submission.conversation),
- });
- }
+ recoverConversation(conversationId || errorResponse.conversationId || v4(), submission);
setIsSubmitting(false);
}
},
@@ -1217,10 +1250,10 @@ export default function useEventHandlers({
setMessages,
finalHandler,
cancelHandler,
- newConversation,
setIsSubmitting,
setShowStopButton,
setSubmissionStart,
+ recoverConversation,
],
);
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 737a065457..ae6a11c378 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -80,7 +80,10 @@ import {
supportsGenerationProtocolV2,
GENERATION_PROTOCOL_VERSION,
} from '~/data-provider';
-import useEventHandlers, { buildCreatedInitialResponse } from './useEventHandlers';
+import useEventHandlers, {
+ buildCreatedInitialResponse,
+ keepLocalCodeApprovalMode,
+} from './useEventHandlers';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import { useAuthContext } from '~/hooks/AuthContext';
@@ -4296,7 +4299,16 @@ export default function useResumableSSE(
replacementStart.conversationId,
]);
if (authoritativeConversation?.conversationId === replacementStart.conversationId) {
- setConversation?.(authoritativeConversation);
+ const localConversationId = isInitialNewConversation(submission)
+ ? Constants.NEW_CONVO
+ : replacementStart.conversationId;
+ setConversation?.((current) =>
+ keepLocalCodeApprovalMode(
+ authoritativeConversation,
+ current,
+ localConversationId,
+ ),
+ );
}
queryClient.setQueryData(streamStatusQueryKey(replacementStart.conversationId), {
...replacementStatus,
@@ -4394,12 +4406,30 @@ export default function useResumableSSE(
}
if (persistedConversation != null) {
+ /** The persisted copy carries the mode the settled turn started
+ * with; a pick made while the start was pending is newer. The
+ * live conversation still holds the new-chat id here because no
+ * stream event ran for this turn. */
+ const settledCopy = persistedConversation;
+ const localConversationId = startedAsNewConvo
+ ? Constants.NEW_CONVO
+ : settledConversationId;
+ const conversationRecord = keepLocalCodeApprovalMode(
+ settledCopy,
+ queryClient.getQueryData<TConversation>([
+ QueryKeys.conversation,
+ settledConversationId,
+ ]),
+ settledConversationId,
+ );
queryClient.setQueryData(
[QueryKeys.conversation, settledConversationId],
- persistedConversation,
+ conversationRecord,
+ );
+ upsertConvoInAllQueries(queryClient, conversationRecord);
+ setConversation?.((current) =>
+ keepLocalCodeApprovalMode(settledCopy, current, localConversationId),
);
- upsertConvoInAllQueries(queryClient, persistedConversation);
- setConversation?.(persistedConversation);
if (startedAsNewConvo) {
replaceNewConversationUrl(settledConversationId);
}