Skip to content

Commit fefeb01

Browse files
committed
Add client retry logic
1 parent ee6c7f9 commit fefeb01

1 file changed

Lines changed: 26 additions & 6 deletions

File tree

  • apps/sim/app/workspace/[workspaceId]/home/hooks

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

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,9 @@ const DEPLOY_TOOL_NAMES: Set<string> = new Set([
107107
])
108108
const RECONNECT_TAIL_ERROR =
109109
'Live reconnect failed before the stream finished. The latest response may be incomplete.'
110-
const RECOVERY_RETRY_DELAYS_MS = [250, 500, 1000, 2000] as const
110+
const MAX_RECONNECT_ATTEMPTS = 10
111+
const RECONNECT_BASE_DELAY_MS = 1000
112+
const RECONNECT_MAX_DELAY_MS = 30_000
111113

112114
const logger = createLogger('useChat')
113115

@@ -1286,11 +1288,29 @@ export function useChat(
12861288
setIsReconnecting(true)
12871289

12881290
try {
1289-
for (let attempt = 0; attempt <= RECOVERY_RETRY_DELAYS_MS.length; attempt++) {
1291+
for (let attempt = 0; attempt <= MAX_RECONNECT_ATTEMPTS; attempt++) {
12901292
if (abortController.signal.aborted || isStale()) {
12911293
return { attached: false, hadStreamError: false, aborted: true }
12921294
}
12931295

1296+
if (attempt > 0) {
1297+
const delayMs = Math.min(
1298+
RECONNECT_BASE_DELAY_MS * 2 ** (attempt - 1),
1299+
RECONNECT_MAX_DELAY_MS
1300+
)
1301+
logger.warn('Reconnect attempt', {
1302+
streamId,
1303+
attempt,
1304+
maxAttempts: MAX_RECONNECT_ATTEMPTS,
1305+
delayMs,
1306+
})
1307+
setIsReconnecting(true)
1308+
await waitForRetry(delayMs)
1309+
if (abortController.signal.aborted || isStale()) {
1310+
return { attached: false, hadStreamError: false, aborted: true }
1311+
}
1312+
}
1313+
12941314
if (!streamId && chatId) {
12951315
streamId = (await getActiveStreamIdForChat(chatId)) ?? undefined
12961316
}
@@ -1348,12 +1368,12 @@ export function useChat(
13481368
}
13491369
}
13501370
}
1351-
1352-
if (attempt < RECOVERY_RETRY_DELAYS_MS.length) {
1353-
await waitForRetry(RECOVERY_RETRY_DELAYS_MS[attempt] ?? 1000)
1354-
}
13551371
}
13561372

1373+
logger.error('All reconnect attempts exhausted', {
1374+
streamId,
1375+
maxAttempts: MAX_RECONNECT_ATTEMPTS,
1376+
})
13571377
setError(lastError)
13581378
return { attached: false, hadStreamError: true, aborted: false }
13591379
} finally {

0 commit comments

Comments
 (0)