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: Anchor Post-Auth MCP Stream to Submission Message Tree (#13582)

Danny Avila3f4001fca1c2
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index a761fc2e0e..37e827b6ea 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -120,23 +120,28 @@ const mockTitleHandler = jest.fn();
const mockSetIsSubmitting = jest.fn();
const mockClearStepMaps = jest.fn();
-jest.mock('~/hooks/SSE/useEventHandlers', () =>
- jest.fn(() => ({
- errorHandler: mockErrorHandler,
- finalHandler: mockFinalHandler,
- createdHandler: mockCreatedHandler,
- attachmentHandler: jest.fn(),
- stepHandler: mockStepHandler,
- titleHandler: mockTitleHandler,
- contentHandler: jest.fn(),
- resetContentHandler: jest.fn(),
- syncStepMessage: jest.fn(),
- clearStepMaps: mockClearStepMaps,
- messageHandler: jest.fn(),
- setIsSubmitting: mockSetIsSubmitting,
- setShowStopButton: jest.fn(),
- })),
-);
+jest.mock('~/hooks/SSE/useEventHandlers', () => {
+ const actual = jest.requireActual('~/hooks/SSE/useEventHandlers');
+ return {
+ __esModule: true,
+ ...actual,
+ default: jest.fn(() => ({
+ errorHandler: mockErrorHandler,
+ finalHandler: mockFinalHandler,
+ createdHandler: mockCreatedHandler,
+ attachmentHandler: jest.fn(),
+ stepHandler: mockStepHandler,
+ titleHandler: mockTitleHandler,
+ contentHandler: jest.fn(),
+ resetContentHandler: jest.fn(),
+ syncStepMessage: jest.fn(),
+ clearStepMaps: mockClearStepMaps,
+ messageHandler: jest.fn(),
+ setIsSubmitting: mockSetIsSubmitting,
+ setShowStopButton: jest.fn(),
+ })),
+ };
+});
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
@@ -731,6 +736,162 @@ describe('useResumableSSE - 404 error path', () => {
unmount();
});
+ it('replays pre-created OAuth completion against the hydrated response id', async () => {
+ const previousUser = {
+ messageId: 'previous-user',
+ conversationId: CONV_ID,
+ text: 'hi',
+ isCreatedByUser: true,
+ sender: 'User',
+ parentMessageId: Constants.NO_PARENT,
+ } as TMessage;
+ const previousResponse = {
+ messageId: 'previous-response',
+ conversationId: CONV_ID,
+ text: 'hello',
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ parentMessageId: previousUser.messageId,
+ } as TMessage;
+ const submission = buildSubmission({
+ conversation: { conversationId: CONV_ID },
+ userMessage: {
+ messageId: 'optimistic-user',
+ conversationId: CONV_ID,
+ text: 'thanks!',
+ isCreatedByUser: true,
+ sender: 'User',
+ parentMessageId: previousResponse.messageId,
+ },
+ messages: [previousUser, previousResponse],
+ initialResponse: {
+ messageId: 'optimistic-user_',
+ conversationId: CONV_ID,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ parentMessageId: 'optimistic-user',
+ },
+ });
+ const chatHelpers = buildChatHelpers();
+
+ const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ const runStepEvent = {
+ event: StepEvents.ON_RUN_STEP,
+ data: {
+ id: 'step-oauth',
+ runId: Constants.USE_PRELIM_RESPONSE_MESSAGE_ID,
+ index: 0,
+ type: 'tool_calls',
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call-oauth', name: 'oauth_mcp_Google-Workspace', args: '' }],
+ },
+ },
+ };
+ const runStepDeltaEvent = {
+ event: StepEvents.ON_RUN_STEP_DELTA,
+ data: {
+ id: 'step-oauth',
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [{ id: 'call-oauth', name: 'oauth_mcp_Google-Workspace', args: '' }],
+ auth: 'https://auth.example.com/oauth',
+ expires_at: 1780791946,
+ },
+ },
+ };
+ const completedEvent = {
+ event: StepEvents.ON_RUN_STEP_COMPLETED,
+ data: {
+ result: {
+ id: 'step-oauth',
+ index: 0,
+ tool_call: {
+ id: 'call-oauth',
+ name: 'oauth_mcp_Google-Workspace',
+ args: '',
+ output: 'OAuth authentication completed',
+ type: 'tool_call',
+ },
+ },
+ },
+ };
+ const createdEvent = {
+ created: true,
+ message: {
+ messageId: 'server-user',
+ parentMessageId: previousResponse.messageId,
+ conversationId: CONV_ID,
+ sender: 'User',
+ text: 'thanks!',
+ isCreatedByUser: true,
+ },
+ streamId: CONV_ID,
+ };
+
+ const sse = getLastSSE();
+ await act(async () => {
+ sse._emit('message', { data: JSON.stringify(runStepEvent) });
+ sse._emit('message', { data: JSON.stringify(runStepDeltaEvent) });
+ sse._emit('message', { data: JSON.stringify(completedEvent) });
+ });
+
+ expect(mockStepHandler).toHaveBeenCalledTimes(3);
+ expect(mockStepHandler).toHaveBeenNthCalledWith(
+ 3,
+ completedEvent,
+ expect.objectContaining({
+ initialResponse: expect.objectContaining({
+ messageId: 'optimistic-user_',
+ parentMessageId: 'optimistic-user',
+ }),
+ }),
+ );
+
+ await act(async () => {
+ sse._emit('message', { data: JSON.stringify(createdEvent) });
+ });
+
+ expect(mockCreatedHandler).toHaveBeenCalledWith(
+ createdEvent,
+ expect.objectContaining({
+ userMessage: expect.objectContaining({
+ messageId: 'server-user',
+ parentMessageId: previousResponse.messageId,
+ }),
+ initialResponse: expect.objectContaining({
+ messageId: 'server-user_',
+ parentMessageId: 'server-user',
+ }),
+ }),
+ );
+ expect(mockStepHandler).toHaveBeenCalledTimes(6);
+ for (let callIndex = 4; callIndex <= 6; callIndex++) {
+ expect(mockStepHandler).toHaveBeenNthCalledWith(
+ callIndex,
+ expect.any(Object),
+ expect.objectContaining({
+ userMessage: expect.objectContaining({
+ messageId: 'server-user',
+ parentMessageId: previousResponse.messageId,
+ }),
+ initialResponse: expect.objectContaining({
+ messageId: 'server-user_',
+ parentMessageId: 'server-user',
+ }),
+ }),
+ );
+ }
+
+ unmount();
+ });
+
it('routes title stream events to the title handler', async () => {
const submission = buildSubmission();
const chatHelpers = buildChatHelpers();
diff --git a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
index bd697d5b5a..0ea220e966 100644
--- a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
@@ -565,6 +565,178 @@ describe('useStepHandler', () => {
);
});
+ it('keeps pending OAuth ancestry when content arrives after an orphaned refresh', () => {
+ const rootUser = createUserMessage({ messageId: 'root-user' });
+ const existingResponse = createResponseMessage({
+ messageId: 'existing-response',
+ parentMessageId: rootUser.messageId,
+ });
+ const pendingUser = createUserMessage({
+ messageId: 'pending-user',
+ parentMessageId: existingResponse.messageId,
+ });
+ const initialResponse = createResponseMessage({
+ messageId: 'pending-user_',
+ parentMessageId: pendingUser.messageId,
+ });
+
+ let currentMessages = [rootUser, existingResponse];
+ mockGetMessages.mockImplementation(() => currentMessages);
+ mockSetMessages.mockImplementation((messages) => {
+ currentMessages = messages;
+ });
+
+ const { result } = renderHook(() => useStepHandler(createHookParams()));
+ const submission = createSubmission({
+ userMessage: pendingUser,
+ messages: [rootUser, existingResponse],
+ initialResponse,
+ });
+
+ act(() => {
+ result.current.stepHandler(
+ {
+ event: StepEvents.ON_RUN_STEP,
+ data: createToolCallRunStep({
+ id: 'step-oauth-login',
+ runId: USE_PRELIM_RESPONSE_MESSAGE_ID,
+ stepDetails: {
+ type: StepTypes.TOOL_CALLS,
+ tool_calls: [
+ {
+ id: 'tool-call-oauth',
+ name: `oauth${Constants.mcp_delimiter}Google-Workspace`,
+ args: '',
+ type: ToolCallTypes.TOOL_CALL,
+ },
+ ],
+ },
+ }),
+ },
+ submission,
+ );
+ result.current.stepHandler(
+ {
+ event: StepEvents.ON_RUN_STEP,
+ data: createRunStep({
+ id: 'step-message',
+ runId: USE_PRELIM_RESPONSE_MESSAGE_ID,
+ index: 0,
+ }),
+ },
+ submission,
+ );
+ });
+
+ currentMessages = [initialResponse];
+
+ act(() => {
+ result.current.stepHandler(
+ { event: StepEvents.ON_MESSAGE_DELTA, data: createMessageDelta('step-message', 'Ready') },
+ submission,
+ );
+ });
+
+ expect(currentMessages.map((message) => message.messageId)).toEqual([
+ rootUser.messageId,
+ existingResponse.messageId,
+ pendingUser.messageId,
+ initialResponse.messageId,
+ ]);
+ expect(currentMessages.at(-1)).toEqual(
+ expect.objectContaining({
+ parentMessageId: pendingUser.messageId,
+ content: [{ type: ContentTypes.TEXT, text: 'Ready' }],
+ }),
+ );
+ });
+
+ it('replaces the preliminary OAuth response when post-auth streaming uses a stable response id', () => {
+ const rootUser = createUserMessage({ messageId: 'root-user' });
+ const existingResponse = createResponseMessage({
+ messageId: 'existing-response',
+ parentMessageId: rootUser.messageId,
+ });
+ const pendingUser = createUserMessage({
+ messageId: 'pending-user',
+ parentMessageId: existingResponse.messageId,
+ });
+ const preliminaryResponse = createResponseMessage({
+ messageId: 'pending-user_',
+ parentMessageId: pendingUser.messageId,
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'tool-call-oauth',
+ name: `oauth${Constants.mcp_delimiter}Google-Workspace`,
+ type: ToolCallTypes.TOOL_CALL,
+ args: '',
+ },
+ },
+ ],
+ });
+ const stableResponse = createResponseMessage({
+ messageId: 'stable-response',
+ parentMessageId: pendingUser.messageId,
+ });
+
+ let currentMessages = [rootUser, existingResponse, preliminaryResponse];
+ mockGetMessages.mockImplementation(() => currentMessages);
+ mockSetMessages.mockImplementation((messages) => {
+ currentMessages = messages;
+ });
+
+ const { result } = renderHook(() => useStepHandler(createHookParams()));
+ const submission = createSubmission({
+ userMessage: pendingUser,
+ messages: [rootUser, existingResponse],
+ initialResponse: preliminaryResponse,
+ });
+
+ act(() => {
+ result.current.stepHandler(
+ {
+ event: StepEvents.ON_RUN_STEP,
+ data: createRunStep({
+ id: 'step-message',
+ runId: stableResponse.messageId,
+ index: 0,
+ }),
+ },
+ submission,
+ );
+ });
+
+ expect(currentMessages.map((message) => message.messageId)).toEqual([
+ rootUser.messageId,
+ existingResponse.messageId,
+ pendingUser.messageId,
+ stableResponse.messageId,
+ ]);
+
+ act(() => {
+ result.current.stepHandler(
+ { event: StepEvents.ON_MESSAGE_DELTA, data: createMessageDelta('step-message', 'Ready') },
+ submission,
+ );
+ });
+
+ expect(currentMessages.map((message) => message.messageId)).toEqual([
+ rootUser.messageId,
+ existingResponse.messageId,
+ pendingUser.messageId,
+ stableResponse.messageId,
+ ]);
+ expect(currentMessages.at(-1)).toEqual(
+ expect.objectContaining({
+ messageId: stableResponse.messageId,
+ parentMessageId: pendingUser.messageId,
+ content: [{ type: ContentTypes.TEXT, text: 'Ready' }],
+ }),
+ );
+ });
+
it('should not insert regenerate transport userMessage before preliminary OAuth steps', () => {
const originalUser = createUserMessage({ messageId: 'original-user-message' });
const originalResponse = createResponseMessage({
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 73d2ba58b0..084eb6ab2c 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -37,8 +37,8 @@ import {
queueTitleGeneration,
streamStatusQueryKey,
} from '~/data-provider';
+import useEventHandlers, { buildCreatedInitialResponse } from './useEventHandlers';
import { useAuthContext } from '~/hooks/AuthContext';
-import useEventHandlers from './useEventHandlers';
import store from '~/store';
type ChatHelpers = Pick<
@@ -555,7 +555,18 @@ export default function useResumableSSE(
...data.message,
overrideParentMessageId: userMessage.overrideParentMessageId,
};
- createdHandler(data, { ...currentSubmission, userMessage } as EventSubmission);
+ const createdInitialResponse = buildCreatedInitialResponse({
+ initialResponse: currentSubmission.initialResponse as TMessage,
+ userMessage,
+ isRegenerate: currentSubmission.isRegenerate,
+ });
+ currentSubmission = {
+ ...currentSubmission,
+ userMessage,
+ initialResponse: createdInitialResponse,
+ };
+ submissionRef.current = currentSubmission;
+ createdHandler(data, currentSubmission as EventSubmission);
replayPreCreatedStepEvents();
return;
}
diff --git a/client/src/hooks/SSE/useStepHandler.ts b/client/src/hooks/SSE/useStepHandler.ts
index aa2980486d..b6f06305c0 100644
--- a/client/src/hooks/SSE/useStepHandler.ts
+++ b/client/src/hooks/SSE/useStepHandler.ts
@@ -467,6 +467,17 @@ export default function useStepHandler({
submission.isRegenerate &&
!message.isCreatedByUser &&
getRegenerateResponseIds(responseMessageId).has(message.messageId);
+ const shouldRemoveInitialResponse = (message: TMessage, responseMessageId: string) => {
+ const initialResponseId = submission.initialResponse?.messageId;
+ return (
+ !submission.isRegenerate &&
+ !message.isCreatedByUser &&
+ initialResponseId != null &&
+ initialResponseId !== responseMessageId &&
+ message.messageId === initialResponseId &&
+ message.parentMessageId === userMessage.messageId
+ );
+ };
const ensureUserMessagePresent = (
candidateMessages: TMessage[],
responseMessageId: string,
@@ -497,9 +508,12 @@ export default function useStepHandler({
) => {
const currentMessages = getEventMessages(candidateMessages);
if (!submission.isRegenerate) {
+ const nextMessages = currentMessages.filter(
+ (message) => !shouldRemoveInitialResponse(message, responseMessageId),
+ );
return ensureUserMessage
- ? ensureUserMessagePresent(currentMessages, responseMessageId)
- : currentMessages;
+ ? ensureUserMessagePresent(nextMessages, responseMessageId)
+ : nextMessages;
}
return currentMessages.filter(
(message) => !shouldRemoveRegenerateResponse(message, responseMessageId),
@@ -590,11 +604,14 @@ export default function useStepHandler({
// Get fresh messages to handle multi-tab scenarios where messages may have loaded
// after this handler started (Tab 2 may have more complete history now)
- const currentMessages = getResponseBaseMessages(messages, responseMessageId);
+ const currentMessages = getResponseBaseMessages(messages, responseMessageId, true);
// Remove any existing response placeholder
let updatedMessages = currentMessages.filter(
- (message) => !shouldRemoveRegenerateResponse(message, responseMessageId),
+ (message) =>
+ message.messageId !== responseMessageId &&
+ !shouldRemoveRegenerateResponse(message, responseMessageId) &&
+ !shouldRemoveInitialResponse(message, responseMessageId),
);
// Ensure userMessage is present (multi-tab: Tab 2 may not have it yet).
@@ -665,8 +682,11 @@ export default function useStepHandler({
);
messageMap.current.set(responseMessageId, updatedResponse);
- const currentMessages = submission.isRegenerate ? messages : getMessages() || [];
- setMessages(mergeResponseMessage(currentMessages, updatedResponse, responseMessageId));
+ setMessages(
+ mergeResponseMessage(messages, updatedResponse, responseMessageId, {
+ ensureUserMessage: true,
+ }),
+ );
}
const bufferedDeltas = pendingDeltaBuffer.current.get(runStep.id);
@@ -704,8 +724,11 @@ export default function useStepHandler({
agentUpdateMeta,
);
messageMap.current.set(responseMessageId, updatedResponse);
- const currentMessages = submission.isRegenerate ? messages : getMessages() || [];
- setMessages(mergeResponseMessage(currentMessages, updatedResponse, responseMessageId));
+ setMessages(
+ mergeResponseMessage(messages, updatedResponse, responseMessageId, {
+ ensureUserMessage: true,
+ }),
+ );
}
} else if (stepEvent.event === StepEvents.ON_MESSAGE_DELTA) {
const messageDelta = stepEvent.data;
@@ -747,8 +770,11 @@ export default function useStepHandler({
getStepMetadata(runStep),
);
messageMap.current.set(responseMessageId, updatedResponse);
- const currentMessages = submission.isRegenerate ? messages : getMessages() || [];
- setMessages(mergeResponseMessage(currentMessages, updatedResponse, responseMessageId));
+ setMessages(
+ mergeResponseMessage(messages, updatedResponse, responseMessageId, {
+ ensureUserMessage: true,
+ }),
+ );
}
} else if (stepEvent.event === StepEvents.ON_REASONING_DELTA) {
const reasoningDelta = stepEvent.data;
@@ -790,8 +816,11 @@ export default function useStepHandler({
getStepMetadata(runStep),
);
messageMap.current.set(responseMessageId, updatedResponse);
- const currentMessages = submission.isRegenerate ? messages : getMessages() || [];
- setMessages(mergeResponseMessage(currentMessages, updatedResponse, responseMessageId));
+ setMessages(
+ mergeResponseMessage(messages, updatedResponse, responseMessageId, {
+ ensureUserMessage: true,
+ }),
+ );
}
} else if (stepEvent.event === StepEvents.ON_RUN_STEP_DELTA) {
const runStepDelta = stepEvent.data;
@@ -955,8 +984,6 @@ export default function useStepHandler({
return;
}
- const currentMessages = submission.isRegenerate ? messages : getMessages() || [];
-
if (completeData.error) {
const filtered = targetMessage.content.filter(
(part) =>
@@ -965,6 +992,7 @@ export default function useStepHandler({
if (filtered.length !== targetMessage.content.length) {
announcePolite({ message: 'summarize_failed', isStatus: true });
const cleaned = { ...targetMessage, content: filtered };
+ const currentMessages = submission.isRegenerate ? messages : getMessages() || [];
messageMap.current.set(completeMessageId, cleaned);
setMessages(mergeResponseMessage(currentMessages, cleaned, completeMessageId));
}
@@ -983,6 +1011,7 @@ export default function useStepHandler({
if (didFinalize) {
announcePolite({ message: 'summarize_completed', isStatus: true });
const finalized = { ...targetMessage, content: updatedContent };
+ const currentMessages = submission.isRegenerate ? messages : getMessages() || [];
messageMap.current.set(completeMessageId, finalized);
setMessages(mergeResponseMessage(currentMessages, finalized, completeMessageId));
}
diff --git a/e2e/specs/mock/message-tree.spec.ts b/e2e/specs/mock/message-tree.spec.ts
index 17da4a751c..af56957c06 100644
--- a/e2e/specs/mock/message-tree.spec.ts
+++ b/e2e/specs/mock/message-tree.spec.ts
@@ -67,6 +67,10 @@ function messageText(message: E2EMessage): string {
return message.content?.map(contentText).filter(Boolean).join('\n') ?? '';
}
+function sseMessage(payload: unknown): string {
+ return `event: message\ndata: ${JSON.stringify(payload)}\n\n`;
+}
+
function findMessage(messages: E2EMessage[], text: string, isCreatedByUser?: boolean): E2EMessage {
const message = messages.find((candidate) => {
const roleMatches =
@@ -150,6 +154,8 @@ async function mockActiveOAuthResumeStream({
parentMessageId,
pendingPrompt,
pendingUserMessageId,
+ postAuthRunId,
+ postAuthText,
}: {
page: Page;
authUrl: string;
@@ -157,10 +163,13 @@ async function mockActiveOAuthResumeStream({
parentMessageId: string;
pendingPrompt: string;
pendingUserMessageId: string;
+ postAuthRunId?: string;
+ postAuthText?: string;
}) {
const pendingResponseMessageId = `${pendingUserMessageId}_`;
const toolCallId = `${pendingUserMessageId}:Google-Workspace`;
const stepId = 'step_oauth_login_Google-Workspace';
+ const messageStepId = 'step_post_auth_message';
const resumeState = {
runSteps: [],
aggregatedContent: [],
@@ -213,6 +222,48 @@ async function mockActiveOAuthResumeStream({
},
],
};
+ const streamPayloads: unknown[] = [
+ {
+ sync: true,
+ resumeState,
+ pendingEvents: [],
+ },
+ ];
+
+ if (postAuthText) {
+ streamPayloads.push(
+ {
+ event: 'on_run_step',
+ data: {
+ runId: postAuthRunId ?? 'USE_PRELIM_RESPONSE_MESSAGE_ID',
+ id: messageStepId,
+ type: 'message_creation',
+ index: 0,
+ stepDetails: {
+ type: 'message_creation',
+ message_creation: {
+ message_id: `${pendingResponseMessageId}-post-auth`,
+ },
+ },
+ usage: null,
+ },
+ },
+ {
+ event: 'on_message_delta',
+ data: {
+ id: messageStepId,
+ delta: {
+ content: [
+ {
+ type: 'text',
+ text: postAuthText,
+ },
+ ],
+ },
+ },
+ },
+ );
+ }
await page.route(`**/api/agents/chat/status/${conversationId}`, (route) =>
route.fulfill({
@@ -233,11 +284,169 @@ async function mockActiveOAuthResumeStream({
route.fulfill({
status: 200,
contentType: 'text/event-stream',
- body: `event: message\ndata: ${JSON.stringify({
- sync: true,
- resumeState,
- pendingEvents: [],
- })}\n\n`,
+ body: streamPayloads.map(sseMessage).join(''),
+ }),
+ );
+}
+
+async function mockPreCreatedOAuthStream({
+ page,
+ authUrl,
+ conversationId,
+ parentMessageId,
+ prompt,
+ serverUserMessageId,
+ responseMessageId,
+ postAuthText,
+}: {
+ page: Page;
+ authUrl: string;
+ conversationId: string;
+ parentMessageId: string;
+ prompt: string;
+ serverUserMessageId: string;
+ responseMessageId: string;
+ postAuthText: string;
+}) {
+ const toolCallId = `${serverUserMessageId}:Google-Workspace`;
+ const oauthStepId = 'step_oauth_login_Google-Workspace';
+ const reasoningStepId = 'step_post_auth_reasoning';
+ const messageStepId = 'step_post_auth_message';
+ const payloads = [
+ {
+ event: 'on_run_step',
+ data: {
+ runId: 'USE_PRELIM_RESPONSE_MESSAGE_ID',
+ id: oauthStepId,
+ type: 'tool_calls',
+ index: 0,
+ stepDetails: {
+ type: 'tool_calls',
+ tool_calls: [
+ {
+ id: toolCallId,
+ name: 'oauth_mcp_Google-Workspace',
+ type: 'tool_call_chunk',
+ },
+ ],
+ },
+ },
+ },
+ {
+ event: 'on_run_step_delta',
+ data: {
+ id: oauthStepId,
+ delta: {
+ type: 'tool_calls',
+ tool_calls: [
+ {
+ id: toolCallId,
+ name: 'oauth_mcp_Google-Workspace',
+ type: 'tool_call_chunk',
+ args: '',
+ },
+ ],
+ auth: authUrl,
+ expires_at: Date.now() + 120000,
+ },
+ },
+ },
+ {
+ event: 'on_run_step_completed',
+ data: {
+ result: {
+ id: oauthStepId,
+ index: 0,
+ tool_call: {
+ id: toolCallId,
+ name: 'oauth_mcp_Google-Workspace',
+ args: '',
+ output: 'OAuth authentication completed',
+ type: 'tool_call',
+ },
+ },
+ },
+ },
+ {
+ created: true,
+ message: {
+ messageId: serverUserMessageId,
+ parentMessageId,
+ conversationId,
+ sender: 'User',
+ text: prompt,
+ isCreatedByUser: true,
+ },
+ streamId: conversationId,
+ },
+ {
+ event: 'on_run_step',
+ data: {
+ runId: responseMessageId,
+ id: reasoningStepId,
+ type: 'message_creation',
+ index: 0,
+ stepDetails: {
+ type: 'message_creation',
+ message_creation: {
+ message_id: `${responseMessageId}-reasoning`,
+ },
+ },
+ usage: null,
+ },
+ },
+ {
+ event: 'on_reasoning_delta',
+ data: {
+ id: reasoningStepId,
+ delta: {
+ content: [
+ {
+ type: 'think',
+ think: 'The user completed OAuth.',
+ },
+ ],
+ },
+ },
+ },
+ {
+ event: 'on_run_step',
+ data: {
+ runId: responseMessageId,
+ id: messageStepId,
+ type: 'message_creation',
+ index: 1,
+ stepDetails: {
+ type: 'message_creation',
+ message_creation: {
+ message_id: `${responseMessageId}-message`,
+ },
+ },
+ usage: null,
+ },
+ },
+ {
+ event: 'on_message_delta',
+ data: {
+ id: messageStepId,
+ delta: {
+ content: [
+ {
+ type: 'text',
+ text: postAuthText,
+ index: 1,
+ },
+ ],
+ },
+ },
+ },
+ ];
+
+ await page.route(`**/api/agents/chat/stream/${conversationId}**`, (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'text/event-stream',
+ body: payloads.map(sseMessage).join(''),
}),
);
}
@@ -578,6 +787,77 @@ test.describe('message tree stream operations', () => {
await expect(messagesView(page).getByText(regeneratedReply)).toBeHidden();
});
+ test('keeps existing messages visible when resumed OAuth streams post-auth content', async ({
+ page,
+ }) => {
+ const label = uniqueLabel('oauth-post-auth');
+ const rootPrompt = replyPrompt(`${label}-root`);
+ const rootReply = replyText(`${label}-root`);
+ const pendingPrompt = replyPrompt(`${label}-pending`);
+ const postAuthText = `E2E post-auth OAuth reply ${label}`;
+
+ await openMockChat(page);
+ await sendAndExpectReply(page, rootPrompt, rootReply);
+ const conversationId = await conversationIdFromPage(page);
+
+ const messages = await waitForMessages(
+ page,
+ conversationId,
+ (items) => items.some((message) => messageText(message).includes(rootReply)),
+ 'root reply before OAuth resume',
+ );
+ const branchTail = findMessage(messages, rootReply, false);
+
+ await mockActiveOAuthResumeStream({
+ page,
+ conversationId,
+ parentMessageId: branchTail.messageId,
+ pendingPrompt,
+ pendingUserMessageId: `${label}-pending-user`,
+ authUrl: `https://auth.example.test/${label}`,
+ postAuthRunId: `${label}-stable-response`,
+ postAuthText,
+ });
+
+ await page.reload({ timeout: 10000 });
+ await expectVisibleMessages(page, [rootPrompt, rootReply, pendingPrompt, postAuthText]);
+ });
+
+ test('keeps existing messages visible when OAuth completes before created', async ({ page }) => {
+ const label = uniqueLabel('oauth-pre-created');
+ const rootPrompt = replyPrompt(`${label}-root`);
+ const rootReply = replyText(`${label}-root`);
+ const followPrompt = replyPrompt(`${label}-follow`);
+ const postAuthText = `E2E pre-created OAuth reply ${label}`;
+
+ await openMockChat(page);
+ await sendAndExpectReply(page, rootPrompt, rootReply);
+ const conversationId = await conversationIdFromPage(page);
+
+ const messages = await waitForMessages(
+ page,
+ conversationId,
+ (items) => items.some((message) => messageText(message).includes(rootReply)),
+ 'root reply before pre-created OAuth stream',
+ );
+ const branchTail = findMessage(messages, rootReply, false);
+
+ await mockPreCreatedOAuthStream({
+ page,
+ conversationId,
+ parentMessageId: branchTail.messageId,
+ prompt: followPrompt,
+ serverUserMessageId: `${label}-server-user`,
+ responseMessageId: `${label}-response`,
+ authUrl: `https://auth.example.test/${label}`,
+ postAuthText,
+ });
+
+ const response = await sendMessage(page, followPrompt);
+ expect(response.ok()).toBeTruthy();
+ await expectVisibleMessages(page, [rootPrompt, rootReply, followPrompt, postAuthText]);
+ });
+
test('long threads retain regenerated and save-and-submit branches after revisit', async ({
page,
}) => {