Skip to content

Commit ce6db00

Browse files
committed
Fix abort
1 parent d55d18a commit ce6db00

File tree

2 files changed

+110
-88
lines changed

2 files changed

+110
-88
lines changed

apps/sim/app/workspace/[workspaceId]/home/hooks/use-chat.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2189,6 +2189,13 @@ export function useChat(
21892189
let seedEvents = opts.initialBatch?.events ?? []
21902190
let streamStatus = opts.initialBatch?.status ?? 'unknown'
21912191

2192+
const isStaleReconnect = () =>
2193+
streamGenRef.current !== expectedGen || abortControllerRef.current?.signal.aborted === true
2194+
2195+
if (isStaleReconnect()) {
2196+
return { error: false, aborted: true }
2197+
}
2198+
21922199
setTransportReconnecting()
21932200
setError(null)
21942201

@@ -2232,6 +2239,10 @@ export function useChat(
22322239
throw new Error(RECONNECT_TAIL_ERROR)
22332240
}
22342241

2242+
if (isStaleReconnect()) {
2243+
return { error: false, aborted: true }
2244+
}
2245+
22352246
setTransportStreaming()
22362247

22372248
const liveResult = await processSSEStreamRef.current(
@@ -2249,6 +2260,10 @@ export function useChat(
22492260
return { error: false, aborted: false }
22502261
}
22512262

2263+
if (isStaleReconnect()) {
2264+
return { error: false, aborted: true }
2265+
}
2266+
22522267
setTransportReconnecting()
22532268

22542269
latestCursor = lastCursorRef.current || latestCursor
@@ -2344,9 +2359,11 @@ export function useChat(
23442359
async (opts: { streamId: string; assistantId: string; gen: number }): Promise<boolean> => {
23452360
const { streamId, assistantId, gen } = opts
23462361

2362+
const isStaleReconnect = () =>
2363+
streamGenRef.current !== gen || abortControllerRef.current?.signal.aborted === true
2364+
23472365
for (let attempt = 0; attempt <= MAX_RECONNECT_ATTEMPTS; attempt++) {
2348-
if (streamGenRef.current !== gen) return true
2349-
if (abortControllerRef.current?.signal.aborted) return true
2366+
if (isStaleReconnect()) return true
23502367

23512368
if (attempt > 0) {
23522369
const delayMs = Math.min(
@@ -2359,6 +2376,9 @@ export function useChat(
23592376
maxAttempts: MAX_RECONNECT_ATTEMPTS,
23602377
delayMs,
23612378
})
2379+
2380+
if (isStaleReconnect()) return true
2381+
23622382
setTransportReconnecting()
23632383
await new Promise((resolve) => setTimeout(resolve, delayMs))
23642384
if (streamGenRef.current !== gen) {
@@ -2428,7 +2448,9 @@ export function useChat(
24282448
streamId,
24292449
maxAttempts: MAX_RECONNECT_ATTEMPTS,
24302450
})
2431-
setIsReconnecting(false)
2451+
if (streamGenRef.current === gen) {
2452+
setIsReconnecting(false)
2453+
}
24322454
return false
24332455
},
24342456
[resumeOrFinalize, setTransportIdle, setTransportReconnecting]

0 commit comments

Comments
 (0)