@@ -18,6 +18,27 @@ function normalizeUserId(userId?: string): string {
1818 return userId || 'anonymous' ;
1919}
2020
21+ /**
22+ * Validate an SSE response, extract its body reader, and yield parsed events.
23+ * Consolidates the duplicated response → reader → parseSSEStream pipeline
24+ * used by streamChat and streamRegenerateImage.
25+ */
26+ async function * readSSEResponse (
27+ response : Response ,
28+ context : string ,
29+ ) : AsyncGenerator < AgentResponse > {
30+ if ( ! response . ok ) {
31+ throw new Error ( `${ context } : ${ response . statusText } ` ) ;
32+ }
33+
34+ const reader = response . body ?. getReader ( ) ;
35+ if ( ! reader ) {
36+ throw new Error ( 'No response body' ) ;
37+ }
38+
39+ yield * parseSSEStream ( reader ) ;
40+ }
41+
2142/**
2243 * Get application configuration including feature flags
2344 */
@@ -94,16 +115,7 @@ export async function* streamChat(
94115 } ) ,
95116 } ) ;
96117
97- if ( ! response . ok ) {
98- throw new Error ( `Chat request failed: ${ response . statusText } ` ) ;
99- }
100-
101- const reader = response . body ?. getReader ( ) ;
102- if ( ! reader ) {
103- throw new Error ( 'No response body' ) ;
104- }
105-
106- yield * parseSSEStream ( reader ) ;
118+ yield * readSSEResponse ( response , 'Chat request failed' ) ;
107119}
108120
109121/**
@@ -219,14 +231,5 @@ export async function* streamRegenerateImage(
219231 } ) ,
220232 } ) ;
221233
222- if ( ! response . ok ) {
223- throw new Error ( `Regeneration request failed: ${ response . statusText } ` ) ;
224- }
225-
226- const reader = response . body ?. getReader ( ) ;
227- if ( ! reader ) {
228- throw new Error ( 'No response body' ) ;
229- }
230-
231- yield * parseSSEStream ( reader ) ;
234+ yield * readSSEResponse ( response , 'Regeneration request failed' ) ;
232235}
0 commit comments