Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 3.8k
fix(explicit-user-abort): separate explicit user abort semantics#3776
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
143 changes: 100 additions & 43 deletions
143 apps/sim/app/workspace/[workspaceId]/home/hooks/use-chat.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -92,6 +92,9 @@ const DEPLOY_TOOL_NAMES = new Set(['deploy_api', 'deploy_chat', 'deploy_mcp', 'r | ||
| const RECONNECT_TAIL_ERROR = | ||
| 'Live reconnect failed before the stream finished. The latest response may be incomplete.' | ||
| const TERMINAL_STREAM_STATUSES = new Set(['complete', 'error', 'cancelled']) | ||
| const MAX_RECONNECT_ATTEMPTS = 10 | ||
| const RECONNECT_BASE_DELAY_MS = 1000 | ||
| const RECONNECT_MAX_DELAY_MS = 30_000 | ||
| interface StreamEventEnvelope { | ||
| eventId: number | ||
| @@ -1565,6 +1568,7 @@ export function useChat( | ||
| (options?: { error?: boolean }) => { | ||
| sendingRef.current = false | ||
| setIsSending(false) | ||
| setIsReconnecting(false) | ||
| abortControllerRef.current = null | ||
| invalidateChatQueries() | ||
| @@ -1609,6 +1613,47 @@ export function useChat( | ||
| ) | ||
| finalizeRef.current = finalize | ||
| const resumeOrFinalize = useCallback( | ||
| async (opts: { | ||
| streamId: string | ||
| assistantId: string | ||
| gen: number | ||
| fromEventId: number | ||
| snapshot?: StreamSnapshot | null | ||
| signal?: AbortSignal | ||
| }): Promise<void> => { | ||
| const { streamId, assistantId, gen, fromEventId, snapshot, signal } = opts | ||
| const batch = | ||
| snapshot ?? | ||
| (await (async () => { | ||
| const b = await fetchStreamBatch(streamId, fromEventId, signal) | ||
| if (streamGenRef.current !== gen) return null | ||
| return { events: b.events, status: b.status } as StreamSnapshot | ||
| })()) | ||
| if (!batch || streamGenRef.current !== gen) return | ||
| if (isTerminalStreamStatus(batch.status)) { | ||
| finalize(batch.status === 'error' ? { error: true } : undefined) | ||
| return | ||
| } | ||
| const reconnectResult = await attachToExistingStream({ | ||
| streamId, | ||
| assistantId, | ||
| expectedGen: gen, | ||
| snapshot: batch, | ||
| initialLastEventId: batch.events[batch.events.length - 1]?.eventId ?? fromEventId, | ||
| }) | ||
| if (streamGenRef.current === gen && !reconnectResult.aborted) { | ||
| finalize(reconnectResult.error ? { error: true } : undefined) | ||
| } | ||
| }, | ||
| [fetchStreamBatch, attachToExistingStream, finalize] | ||
| ) | ||
| const sendMessage = useCallback( | ||
| async (message: string, fileAttachments?: FileAttachmentForApi[], contexts?: ChatContext[]) => { | ||
| if (!message.trim() || !workspaceId) return | ||
| @@ -1745,44 +1790,13 @@ export function useChat( | ||
| return | ||
| } | ||
| const batch = await fetchStreamBatch( | ||
| userMessageId, | ||
| termination.lastEventId, | ||
| abortController.signal | ||
| ) | ||
| if (streamGenRef.current !== gen) { | ||
| return | ||
| } | ||
| if (isTerminalStreamStatus(batch.status)) { | ||
| finalize(batch.status === 'error' ? { error: true } : undefined) | ||
| return | ||
| } | ||
| logger.warn( | ||
| 'Primary stream ended without terminal event, attempting in-place reconnect', | ||
| { | ||
| streamId: userMessageId, | ||
| lastEventId: termination.lastEventId, | ||
| streamStatus: batch.status, | ||
| sawDoneEvent: termination.sawDoneEvent, | ||
| } | ||
| ) | ||
| const reconnectResult = await attachToExistingStream({ | ||
| await resumeOrFinalize({ | ||
| streamId: userMessageId, | ||
| assistantId, | ||
| expectedGen: gen, | ||
| snapshot: { | ||
| events: batch.events, | ||
| status: batch.status, | ||
| }, | ||
| initialLastEventId: | ||
| batch.events[batch.events.length - 1]?.eventId ?? termination.lastEventId, | ||
| gen, | ||
| fromEventId: termination.lastEventId, | ||
| signal: abortController.signal, | ||
| }) | ||
| if (streamGenRef.current === gen && !reconnectResult.aborted) { | ||
| finalize(reconnectResult.error ? { error: true } : undefined) | ||
| } | ||
| } | ||
| } catch (err) { | ||
| if (err instanceof Error && err.name === 'AbortError') return | ||
| @@ -1827,17 +1841,13 @@ export function useChat( | ||
| .find((m) => m.role === 'assistant') | ||
| const recoveryAssistantId = lastAssistantMsg?.id ?? assistantId | ||
| const reconnectResult = await attachToExistingStream({ | ||
| await resumeOrFinalize({ | ||
| streamId: pendingRecovery.streamId, | ||
| assistantId: recoveryAssistantId, | ||
| expectedGen: gen, | ||
| gen, | ||
| fromEventId: lastEventIdRef.current, | ||
| snapshot: pendingRecovery.snapshot, | ||
| initialLastEventId: lastEventIdRef.current, | ||
| }) | ||
| if (streamGenRef.current === gen && !reconnectResult.aborted) { | ||
| finalize(reconnectResult.error ? { error: true } : undefined) | ||
| } | ||
| return | ||
| } catch (recoveryError) { | ||
| logger.warn('Failed to recover active stream after conflict', { | ||
| @@ -1847,6 +1857,53 @@ export function useChat( | ||
| } | ||
| } | ||
| const activeStreamId = streamIdRef.current | ||
| if (activeStreamId && streamGenRef.current === gen) { | ||
| for (let attempt = 0; attempt < MAX_RECONNECT_ATTEMPTS; attempt++) { | ||
| if (streamGenRef.current !== gen) return | ||
| if (abortControllerRef.current?.signal.aborted) return | ||
| const delayMs = Math.min(RECONNECT_BASE_DELAY_MS * 2 ** attempt, RECONNECT_MAX_DELAY_MS) | ||
| logger.info('Reconnect attempt after network error', { | ||
| streamId: activeStreamId, | ||
| attempt: attempt + 1, | ||
| maxAttempts: MAX_RECONNECT_ATTEMPTS, | ||
| delayMs, | ||
| error: errorMessage, | ||
| }) | ||
| setIsReconnecting(true) | ||
| await new Promise((resolve) => setTimeout(resolve, delayMs)) | ||
| if (streamGenRef.current !== gen) return | ||
| if (abortControllerRef.current?.signal.aborted) return | ||
| try { | ||
| await resumeOrFinalize({ | ||
| streamId: activeStreamId, | ||
| assistantId, | ||
| gen, | ||
| fromEventId: lastEventIdRef.current, | ||
| signal: abortController.signal, | ||
| }) | ||
| return | ||
| } catch (reconnectErr) { | ||
| if (reconnectErr instanceof Error && reconnectErr.name === 'AbortError') return | ||
| logger.warn('Reconnect attempt failed', { | ||
| streamId: activeStreamId, | ||
| attempt: attempt + 1, | ||
| error: reconnectErr instanceof Error ? reconnectErr.message : String(reconnectErr), | ||
| }) | ||
| } | ||
| } | ||
| logger.error('All reconnect attempts exhausted', { | ||
| streamId: activeStreamId, | ||
| maxAttempts: MAX_RECONNECT_ATTEMPTS, | ||
| }) | ||
| setIsReconnecting(false) | ||
| } | ||
icecrasher321 marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| setError(errorMessage) | ||
| if (streamGenRef.current === gen) { | ||
| finalize({ error: true }) | ||
icecrasher321 marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| @@ -1859,7 +1916,7 @@ export function useChat( | ||
| queryClient, | ||
| processSSEStream, | ||
| finalize, | ||
| attachToExistingStream, | ||
| resumeOrFinalize, | ||
| preparePendingStreamRecovery, | ||
| ] | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 9 additions & 1 deletion
10 apps/sim/lib/copilot/orchestrator/sse/handlers/handlers.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 7 additions & 3 deletions
10 apps/sim/lib/copilot/orchestrator/sse/handlers/tool-execution.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.