Skip to content

Commit 6470046

Browse files
committed
fix: prevent prompt enhancer from hanging on network errors
- Wrap fetch() in try/catch network failures now log error and reset enhancingPrompt state instead of leaving UI stuck forever - Handle null response.body early return with state cleanup instead of silently skipping the finally block - Previously, any fetch failure or empty body left the enhancing indicator permanently visible with no way to recover
1 parent 4eeb6d1 commit 6470046

1 file changed

Lines changed: 46 additions & 33 deletions

File tree

‎app/lib/hooks/usePromptEnhancer.ts‎

Lines changed: 46 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -33,52 +33,65 @@ export function usePromptEnhancer() {
3333
requestBody.apiKeys = apiKeys;
3434
}
3535

36-
const response = await fetch('/api/enhancer', {
37-
method: 'POST',
38-
body: JSON.stringify(requestBody),
39-
});
36+
let response: Response;
37+
38+
try {
39+
response = await fetch('/api/enhancer', {
40+
method: 'POST',
41+
body: JSON.stringify(requestBody),
42+
});
43+
} catch (error) {
44+
logger.error('Prompt enhancement request failed:', error);
45+
setEnhancingPrompt(false);
46+
47+
return;
48+
}
4049

4150
const reader = response.body?.getReader();
4251

43-
const originalInput = input;
44-
45-
if (reader) {
46-
const decoder = new TextDecoder();
52+
if (!reader) {
53+
logger.warn('Prompt enhancement response has no body');
54+
setEnhancingPrompt(false);
4755

48-
let _input = '';
49-
let _error;
50-
51-
try {
52-
setInput('');
56+
return;
57+
}
5358

54-
while (true) {
55-
const { value, done } = await reader.read();
59+
const originalInput = input;
60+
const decoder = new TextDecoder();
5661

57-
if (done) {
58-
break;
59-
}
62+
let _input = '';
63+
let _error;
6064

61-
_input += decoder.decode(value);
65+
try {
66+
setInput('');
6267

63-
logger.trace('Set input', _input);
68+
while (true) {
69+
const { value, done } = await reader.read();
6470

65-
setInput(_input);
66-
}
67-
} catch (error) {
68-
_error = error;
69-
setInput(originalInput);
70-
} finally {
71-
if (_error) {
72-
logger.error(_error);
71+
if (done) {
72+
break;
7373
}
7474

75-
setEnhancingPrompt(false);
76-
setPromptEnhanced(true);
75+
_input += decoder.decode(value);
76+
77+
logger.trace('Set input', _input);
7778

78-
setTimeout(() => {
79-
setInput(_input);
80-
});
79+
setInput(_input);
80+
}
81+
} catch (error) {
82+
_error = error;
83+
setInput(originalInput);
84+
} finally {
85+
if (_error) {
86+
logger.error(_error);
8187
}
88+
89+
setEnhancingPrompt(false);
90+
setPromptEnhanced(true);
91+
92+
setTimeout(() => {
93+
setInput(_input);
94+
});
8295
}
8396
};
8497

0 commit comments

Comments
 (0)