Skip to content

Commit cec8c6a

Browse files
authored
Merge pull request #272 from cloudflare/fix/duplicate-agent-session-creation
Fix: prevent duplicate agent session creation and improve error handling in chat initialization
2 parents f656cf0 + 80bf691 commit cec8c6a

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,6 @@ debug-tools/*.json
5050
# Sentry Config File
5151
.env.sentry-build-plugin
5252
data-dump
53-
debug-tools/extracted
53+
debug-tools/extracted
54+
cli
55+
debug-tools

src/routes/chat/hooks/use-chat.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,9 @@ export function useChat({
421421
return;
422422
}
423423

424+
// Prevent duplicate session creation on rerenders while streaming
425+
connectionStatus.current = 'connecting';
426+
424427
// Start new code generation using API client
425428
const response = await apiClient.createAgentSession({
426429
query: userQuery,
@@ -487,6 +490,10 @@ export function useChat({
487490
setIsGeneratingBlueprint(false);
488491
sendMessage(createAIMessage('main', 'Blueprint generation complete. Now starting the code generation...', true));
489492

493+
if (!result.websocketUrl || !result.agentId) {
494+
throw new Error('Failed to initialize agent session');
495+
}
496+
490497
// Connect to WebSocket
491498
logger.debug('connecting to ws with created id');
492499
connectWithRetry(result.websocketUrl);
@@ -498,6 +505,9 @@ export function useChat({
498505
description: userQuery,
499506
});
500507
} else if (connectionStatus.current === 'idle') {
508+
// Prevent duplicate connect calls on rerenders
509+
connectionStatus.current = 'connecting';
510+
501511
setIsBootstrapping(false);
502512
// Show starting message with thinking indicator
503513
setMessages(() => [
@@ -516,12 +526,18 @@ export function useChat({
516526
setChatId(urlChatId);
517527

518528

529+
if (!response.data.websocketUrl) {
530+
throw new Error('Missing websocketUrl for existing agent');
531+
}
532+
519533
logger.debug('connecting from init for existing chatId');
520534
connectWithRetry(response.data.websocketUrl, {
521535
disableGenerate: true, // We'll handle generation resume in the WebSocket open handler
522536
});
523537
}
524538
} catch (error) {
539+
// Allow retry on failure
540+
connectionStatus.current = 'idle';
525541
logger.error('Error initializing code generation:', error);
526542
if (error instanceof RateLimitExceededError) {
527543
const rateLimitMessage = handleRateLimitError(error.details, onDebugMessage);

0 commit comments

Comments
 (0)