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: Reconcile Completed Runs Behind Apparently Open Streams on Foreground (#15342)

Danny Avila2acd219c1701
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index 74d2906358..d1ad527497 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -3951,7 +3951,73 @@ describe('useResumableSSE', () => {
unmount();
});
- it('leaves a still-open stream alone when the page returns to the foreground', async () => {
+ it('reconciles durable messages when an apparently open stream is terminal on foreground', async () => {
+ (request.post as jest.Mock).mockResolvedValue({
+ streamId: 'stream-epoch',
+ status: 'started',
+ generationCreatedAt: 1000,
+ generationProtocolVersion: 2,
+ });
+ mockFetchStreamStatus.mockResolvedValue({
+ active: false,
+ status: 'complete',
+ createdAt: 1000,
+ generationProtocolVersion: 2,
+ });
+ const persisted = [
+ {
+ messageId: 'resp-1',
+ parentMessageId: 'msg-1',
+ conversationId: CONV_ID,
+ text: 'Completed while backgrounded',
+ isCreatedByUser: false,
+ },
+ ] as TMessage[];
+ mockFetchQuery.mockResolvedValue(persisted);
+ const submission = buildSubmission();
+ const chatHelpers = buildChatHelpers();
+
+ const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
+ await flushMicrotasks();
+
+ const initialSSE = getLastSSE();
+ const sseCount = mockSSEInstances.length;
+ initialSSE.readyState = MOCK_SSE_OPEN;
+
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ await Promise.resolve();
+ });
+ await flushMicrotasks();
+
+ expect(mockFetchStreamStatus).toHaveBeenCalledWith(CONV_ID);
+ expect(mockSSEInstances).toHaveLength(sseCount + 1);
+ expect(getLastSSE()._url).toBe(
+ '/api/agents/chat/stream/stream-epoch?resume=true&generationCreatedAt=1000&generationProtocolVersion=2',
+ );
+ expect(initialSSE.close).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ getLastSSE()._emit('error', { responseCode: 404 });
+ await Promise.resolve();
+ });
+ await flushMicrotasks();
+
+ expect(mockFetchQuery).toHaveBeenCalledWith({
+ queryKey: [QueryKeys.messages, CONV_ID],
+ });
+ expect(mockSettleAppliedSteerParts).toHaveBeenCalledWith(CONV_ID, persisted);
+ unmount();
+ });
+
+ it('leaves a still-open active stream alone when the page returns to the foreground', async () => {
+ mockFetchStreamStatus.mockResolvedValue({
+ active: true,
+ streamId: 'stream-123',
+ status: 'running',
+ createdAt: 1000,
+ generationProtocolVersion: 2,
+ });
const submission = buildSubmission();
const chatHelpers = buildChatHelpers();
@@ -3964,9 +4030,40 @@ describe('useResumableSSE', () => {
await act(async () => {
document.dispatchEvent(new Event('visibilitychange'));
+ await Promise.resolve();
+ });
+ await flushMicrotasks();
+
+ expect(mockFetchStreamStatus).toHaveBeenCalledWith(CONV_ID);
+ expect(mockSSEInstances).toHaveLength(sseCount);
+ expect(initialSSE.close).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ it('keeps an apparently open stream when foreground status belongs to another epoch', async () => {
+ mockFetchStreamStatus.mockResolvedValue({
+ active: false,
+ status: 'complete',
+ createdAt: 2000,
+ generationProtocolVersion: 2,
+ });
+ const submission = buildSubmission();
+ const chatHelpers = buildChatHelpers();
+
+ const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
+ await flushMicrotasks();
+
+ const initialSSE = getLastSSE();
+ const sseCount = mockSSEInstances.length;
+
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ await Promise.resolve();
});
+ await flushMicrotasks();
expect(mockSSEInstances).toHaveLength(sseCount);
+ expect(initialSSE.close).not.toHaveBeenCalled();
unmount();
});
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index e1eb9df81d..e76ea3d684 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -1667,6 +1667,28 @@ export default function useResumableSSE(
sse.close();
};
+ let foregroundStatusCheckInFlight = false;
+ const reattachOnForeground = () => {
+ logger.log('ResumableSSE', 'Re-attaching stream on foreground');
+ /** Any backoff still pending targets this same attachment, so returning
+ * to the app supersedes it rather than waiting the delay out; its
+ * callback finds a superseded subscription and does nothing. */
+ if (reconnectTimeoutRef.current) {
+ clearTimeout(reconnectTimeoutRef.current);
+ reconnectTimeoutRef.current = null;
+ }
+ reconnectAttemptRef.current = Math.max(reconnectAttemptRef.current, 1);
+ closeStream();
+ subscribeToStream(
+ currentStreamId,
+ currentSubmission,
+ true,
+ generationCreatedAt,
+ generationProtocolVersion,
+ lifecycleSignal,
+ );
+ };
+
/**
* A suspended page can lose its stream without the transport ever
* reporting it. When a mobile browser freezes the tab, an intermediary
@@ -1676,15 +1698,16 @@ export default function useResumableSSE(
* else re-reads the conversation while the pane stays mounted, which is
* why the response the run finished writing only appears after a reload.
*
- * Re-attaching on the way back costs one request and only when this
- * subscription's transport is already gone with no terminal event and no
- * recovery of its own in flight. A live job replays what was missed; a
- * finished one 404s into the durable refetch.
+ * Some mobile WebViews leave the XHR marked OPEN even after the suspended
+ * request stopped delivering events. In that case the durable run status
+ * is the only authority that distinguishes a healthy live attachment from
+ * a terminal one holding stale partial content. A terminal status forces
+ * the same resume path as a closed transport; it returns the synthesized
+ * terminal frame or 404 that reconciles persisted messages.
*/
const handleForegroundReattach = () => {
if (
document.visibilityState !== 'visible' ||
- sse.readyState !== SSE.CLOSED ||
finalReceived ||
subscriptionRetired ||
replacementHandoffRef.current ||
@@ -1693,23 +1716,52 @@ export default function useResumableSSE(
) {
return;
}
- logger.log('ResumableSSE', 'Stream was closed while hidden - re-attaching on foreground');
- /** Any backoff still pending targets this same attachment, so returning
- * to the app supersedes it rather than waiting the delay out; its
- * callback finds a superseded subscription and does nothing. */
- if (reconnectTimeoutRef.current) {
- clearTimeout(reconnectTimeoutRef.current);
- reconnectTimeoutRef.current = null;
+
+ if (sse.readyState === SSE.CLOSED) {
+ reattachOnForeground();
+ return;
}
- reconnectAttemptRef.current = Math.max(reconnectAttemptRef.current, 1);
- subscribeToStream(
- currentStreamId,
- submissionRef.current,
- true,
- generationCreatedAt,
- generationProtocolVersion,
- lifecycleSignal,
- );
+
+ if (foregroundStatusCheckInFlight) {
+ return;
+ }
+ foregroundStatusCheckInFlight = true;
+ const foregroundConvoId = currentSubmission.conversation?.conversationId ?? currentStreamId;
+ void fetchStreamStatus(foregroundConvoId)
+ .then((status) => {
+ if (
+ status.active !== false ||
+ (status.createdAt != null &&
+ generationCreatedAt != null &&
+ status.createdAt !== generationCreatedAt) ||
+ !isCurrentSubscription() ||
+ finalReceived ||
+ subscriptionRetired ||
+ replacementHandoffRef.current ||
+ document.visibilityState !== 'visible'
+ ) {
+ return;
+ }
+ logger.log(
+ 'ResumableSSE',
+ 'Apparently open stream is terminal - reconciling on foreground',
+ { conversationId: foregroundConvoId, generationCreatedAt },
+ );
+ reattachOnForeground();
+ })
+ .catch((error) => {
+ if (!isCurrentSubscription()) {
+ return;
+ }
+ logger.warn('ResumableSSE', 'Could not verify stream on foreground', {
+ conversationId: foregroundConvoId,
+ generationCreatedAt,
+ error,
+ });
+ })
+ .finally(() => {
+ foregroundStatusCheckInFlight = false;
+ });
};
stopForegroundReattachRef.current?.();
document.addEventListener('visibilitychange', handleForegroundReattach);