Repository navigation
Expand file tree
/
Copy pathchatService.ts
More file actions
692 lines (618 loc) · 21.1 KB
/
Copy pathchatService.ts
File metadata and controls
692 lines (618 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
import type { Dispatch } from 'react';
import type { AppAction } from '../types/appState';
import type { ConversationSummary, ConversationMessageInfo } from '../types/appState';
import type { IChatItem } from '../types/chat';
import type { AppError } from '../types/errors';
import { isAppError } from '../types/errors';
import { trackException } from './telemetry';
import {
createAppError,
getErrorCodeFromMessage,
parseErrorFromResponse,
getErrorCodeFromResponse,
isTokenExpiredError,
retryWithBackoff,
} from '../utils/errorHandler';
import {
convertFilesToDataUris,
createAttachmentMetadata,
} from '../utils/fileAttachments';
import { parseSseLine, splitSseBuffer } from '../utils/sseParser';
/**
* ChatService handles all chat-related API operations.
* Dispatches AppContext actions for state management.
*
* @example
* ```typescript
* const chatService = new ChatService(
* '/api',
* getAccessToken,
* dispatch
* );
*
* // Send a message with images
* await chatService.sendMessage(
* 'Analyze this image',
* currentThreadId,
* [imageFile]
* );
* ```
*/
export class ChatService {
private apiUrl: string;
private getAccessToken: () => Promise<string | null>;
private dispatch: Dispatch<AppAction>;
private currentStreamAbort?: AbortController;
// Flag indicating an intentional user cancellation of the active stream.
private streamCancelled = false;
constructor(
apiUrl: string,
getAccessToken: () => Promise<string | null>,
dispatch: Dispatch<AppAction>
) {
this.apiUrl = apiUrl;
this.getAccessToken = getAccessToken;
this.dispatch = dispatch;
}
/**
* Acquire authentication token using MSAL.
* Attempts silent acquisition first, falls back to popup if needed.
*
* @returns Access token string
* @throws {Error} If token acquisition fails
*/
private async ensureAuthToken(): Promise<string> {
const token = await this.getAccessToken();
if (!token) {
throw createAppError(new Error('Failed to acquire access token'), 'AUTH');
}
return token;
}
/**
* Prepare message payload with optional file attachments.
* Converts files to data URIs and separates images from documents.
*
* @param text - Message text content
* @param files - Optional array of files (images and documents)
* @returns Payload with content, image URIs, file attachments, and attachment metadata
*/
private async prepareMessagePayload(
text: string,
files?: File[]
): Promise<{
content: string;
imageDataUris: string[];
fileDataUris: Array<{ dataUri: string; fileName: string; mimeType: string }>;
attachments: IChatItem['attachments'];
}> {
let imageDataUris: string[] = [];
let fileDataUris: Array<{ dataUri: string; fileName: string; mimeType: string }> = [];
let attachments: IChatItem['attachments'] = undefined;
if (files && files.length > 0) {
try {
const results = await convertFilesToDataUris(files);
// Separate images from documents
const imageResults = results.filter((r) => r.mimeType.startsWith('image/'));
const fileResults = results.filter((r) => !r.mimeType.startsWith('image/'));
imageDataUris = imageResults.map((r) => r.dataUri);
fileDataUris = fileResults.map((r) => ({
dataUri: r.dataUri,
fileName: r.name,
mimeType: r.mimeType,
}));
// Create attachment metadata for UI display
attachments = createAttachmentMetadata(results);
} catch (error) {
const appError = createAppError(error);
this.dispatch({ type: 'CHAT_ERROR', error: appError });
throw appError;
}
}
return { content: text, imageDataUris, fileDataUris, attachments };
}
/**
* Construct request body for chat API.
*
* @param message - User message text
* @param conversationId - Current conversation ID (null for new conversations)
* @param imageDataUris - Array of base64 data URIs for images
* @param fileDataUris - Array of file attachments with metadata
* @returns Request body object
*/
private constructRequestBody(
message: string,
conversationId: string | null,
imageDataUris: string[],
fileDataUris: Array<{ dataUri: string; fileName: string; mimeType: string }>
): Record<string, unknown> {
return {
message,
conversationId,
imageDataUris: imageDataUris.length > 0 ? imageDataUris : undefined,
fileDataUris: fileDataUris.length > 0 ? fileDataUris : undefined,
};
}
/**
* Initiate streaming fetch request to chat API.
* Validates response and throws typed errors on failure.
*
* @param url - API endpoint URL
* @param token - Access token
* @param body - Request body
* @param signal - Abort signal for cancellation
* @returns Response object
* @throws {AppError} If request fails or response is not OK
*/
private async initiateStream(
url: string,
token: string,
body: Record<string, unknown>,
signal: AbortSignal
): Promise<Response> {
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(body),
signal,
});
if (!res.ok) {
const errorMessage = await parseErrorFromResponse(res);
const errorCode = getErrorCodeFromResponse(res);
throw createAppError(new Error(errorMessage), errorCode);
}
return res;
}
/**
* Send a message and stream the response from the Azure AI Agent.
* Orchestrates authentication, file conversion, optimistic UI updates, and streaming.
* Retries the full stream cycle up to 3 times on retryable errors, then recovers
* the message text back to the input if all retries fail.
*
* @param messageText - The user's message text
* @param currentConversationId - Current conversation ID (null for new conversations)
* @param files - Optional array of files to attach (images and documents)
* @throws {Error} If authentication fails (non-retryable)
*/
async sendMessage(
messageText: string,
currentConversationId: string | null,
files?: File[]
): Promise<void> {
if (this.currentStreamAbort) {
this.streamCancelled = true;
this.currentStreamAbort.abort();
this.dispatch({ type: 'CHAT_CANCEL_STREAM' });
}
let token: string;
try {
token = await this.ensureAuthToken();
} catch (error) {
if (isTokenExpiredError(error)) {
this.dispatch({ type: 'AUTH_TOKEN_EXPIRED' });
}
const appError: AppError = isAppError(error)
? error
: createAppError(error, 'AUTH');
this.dispatch({ type: 'CHAT_ERROR', error: appError });
throw error;
}
const { content, imageDataUris, fileDataUris, attachments } = await this.prepareMessagePayload(
messageText,
files
);
const userMessage: IChatItem = {
id: Date.now().toString(),
role: 'user',
content,
attachments,
more: {
time: new Date().toISOString(),
},
};
this.dispatch({ type: 'CHAT_SEND_MESSAGE', message: userMessage });
const assistantMessageId = (Date.now() + 1).toString();
this.dispatch({ type: 'CHAT_ADD_ASSISTANT_MESSAGE', messageId: assistantMessageId });
this.dispatch({
type: 'CHAT_START_STREAM',
conversationId: currentConversationId || undefined,
messageId: assistantMessageId,
});
const requestBody = this.constructRequestBody(
messageText,
currentConversationId,
imageDataUris,
fileDataUris
);
const maxRetries = 3;
let lastError: unknown;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
if (attempt > 1) {
this.dispatch({
type: 'CHAT_STREAM_RETRY',
messageId: assistantMessageId,
attempt,
maxRetries,
});
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, attempt - 1)));
}
this.currentStreamAbort = new AbortController();
this.streamCancelled = false;
const response = await this.initiateStream(
`${this.apiUrl}/chat/stream`,
token,
requestBody,
this.currentStreamAbort.signal
);
await this.processStream(response, assistantMessageId, currentConversationId);
this.currentStreamAbort = undefined;
this.streamCancelled = false;
return;
} catch (error) {
lastError = error;
this.currentStreamAbort = undefined;
this.streamCancelled = false;
// User cancelled
if (error instanceof DOMException && error.name === 'AbortError') {
return;
}
if (isTokenExpiredError(error)) {
this.dispatch({ type: 'AUTH_TOKEN_EXPIRED' });
throw error;
}
if (isAppError(error) && error.code === 'AUTH') {
this.dispatch({ type: 'CHAT_ERROR', error });
throw error;
}
if (attempt === maxRetries) {
break;
}
}
}
trackException(lastError instanceof Error ? lastError : new Error(String(lastError)), {
context: 'sendMessage',
retryCount: String(maxRetries),
});
const appError: AppError = isAppError(lastError)
? lastError
: createAppError(lastError, getErrorCodeFromMessage(lastError));
this.dispatch({
type: 'CHAT_RECOVER_MESSAGE',
messageText,
error: appError,
retryCount: maxRetries,
});
}
/**
* Process Server-Sent Events stream from the API.
* Implements duplicate chunk suppression to prevent UI flicker.
*
* @param response - Fetch Response object with SSE stream
* @param messageId - ID of the assistant message being streamed
* @param currentConversationId - Current conversation ID (null for new conversations)
* @throws {Error} If stream is not readable or parsing fails
*/
private async processStream(
response: Response,
messageId: string,
currentConversationId: string | null
): Promise<void> {
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) {
const error = createAppError(
new Error(`Response body is not readable for message ${messageId}`),
'STREAM'
);
this.dispatch({ type: 'CHAT_ERROR', error });
throw error;
}
let newConversationId = currentConversationId;
let lastChunkContent: string | undefined;
let buffer = '';
try {
while (true) {
if (this.streamCancelled) {
break;
}
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
const [lines, remaining] = splitSseBuffer(buffer);
buffer = remaining;
for (const line of lines) {
const event = parseSseLine(line);
if (!event) continue;
if (event.data?.error) {
console.error('[ChatService] SSE error event received:', event.data.error);
const error = createAppError(
new Error(event.data.error.message || event.data.error || 'Stream error occurred'),
'STREAM'
);
this.dispatch({ type: 'CHAT_ERROR', error });
throw error;
}
switch (event.type) {
case 'conversationId':
if (!newConversationId) {
newConversationId = event.data.conversationId;
this.dispatch({
type: 'CHAT_START_STREAM',
conversationId: event.data.conversationId,
messageId,
});
}
break;
case 'chunk':
if (event.data.content !== lastChunkContent) {
this.dispatch({
type: 'CHAT_STREAM_CHUNK',
messageId,
content: event.data.content,
});
lastChunkContent = event.data.content;
}
break;
case 'annotations':
if (event.data.annotations && event.data.annotations.length > 0) {
this.dispatch({
type: 'CHAT_STREAM_ANNOTATIONS',
messageId,
annotations: event.data.annotations,
});
}
break;
case 'toolUse':
if (event.data.toolName) {
this.dispatch({
type: 'CHAT_STREAM_TOOL_USE',
messageId,
toolName: event.data.toolName,
});
}
break;
case 'mcpApprovalRequest':
if (event.data.approvalRequest) {
this.dispatch({
type: 'CHAT_MCP_APPROVAL_REQUEST',
messageId,
approvalRequest: event.data.approvalRequest,
previousResponseId: event.data.approvalRequest.previousResponseId ?? '',
});
}
break;
case 'usage':
this.dispatch({
type: 'CHAT_STREAM_COMPLETE',
usage: {
promptTokens: event.data.promptTokens,
completionTokens: event.data.completionTokens,
totalTokens: event.data.totalTokens,
duration: event.data.duration,
},
});
break;
case 'done':
return;
case 'error': {
const error = createAppError(
new Error(`Stream error for message ${messageId}: ${event.data.message}`),
'STREAM'
);
this.dispatch({ type: 'CHAT_ERROR', error });
throw error;
}
}
}
}
} catch (error) {
if (error instanceof DOMException && error.name === 'AbortError' && this.streamCancelled) {
// User intentionally cancelled the stream - not an error condition
return;
}
const appError =
error instanceof Error && 'code' in error
? error
: createAppError(
new Error(
`Stream processing failed: ${error instanceof Error ? error.message : String(error)} (Conversation: ${currentConversationId}, Message: ${messageId})`
),
'STREAM'
);
this.dispatch({ type: 'CHAT_ERROR', error: appError as AppError });
throw error;
} finally {
try {
reader.releaseLock();
} catch {
// Reader may already be released
}
}
}
/**
* Send approval response for an MCP tool call.
*
* @param approvalRequestId - ID of the approval request
* @param approved - Whether the tool call was approved
* @param previousResponseId - Response ID to continue from
* @param conversationId - Current conversation ID
*/
async sendMcpApproval(
approvalRequestId: string,
approved: boolean,
previousResponseId: string,
conversationId: string
): Promise<void> {
try {
const token = await this.ensureAuthToken();
const assistantMessageId = Date.now().toString();
this.dispatch({ type: 'CHAT_ADD_ASSISTANT_MESSAGE', messageId: assistantMessageId });
this.dispatch({
type: 'CHAT_START_STREAM',
conversationId,
messageId: assistantMessageId,
});
this.currentStreamAbort = new AbortController();
this.streamCancelled = false;
const requestBody = {
message: approved ? 'Approved' : 'Rejected',
conversationId,
previousResponseId,
mcpApproval: {
approvalRequestId,
approved,
},
};
const response = await retryWithBackoff(
async () =>
this.initiateStream(
`${this.apiUrl}/chat/stream`,
token,
requestBody,
this.currentStreamAbort!.signal
),
3,
1000
);
await this.processStream(response, assistantMessageId, conversationId);
this.currentStreamAbort = undefined;
this.streamCancelled = false;
} catch (error) {
this.currentStreamAbort = undefined;
this.streamCancelled = false;
if (error instanceof DOMException && error.name === 'AbortError') {
return;
}
trackException(error instanceof Error ? error : new Error(String(error)), { context: 'sendMcpApproval' });
const appError: AppError = isAppError(error)
? error
: createAppError(error, getErrorCodeFromMessage(error));
this.dispatch({ type: 'CHAT_ERROR', error: appError });
throw error;
}
}
/**
* Clear chat history and reset to empty state.
* Dispatches CHAT_CLEAR action to remove all messages and conversation ID.
*/
clearChat(): void {
this.dispatch({ type: 'CHAT_CLEAR' });
}
/**
* Clear current error state without affecting chat history.
* Dispatches CHAT_CLEAR_ERROR action.
*/
clearError(): void {
this.dispatch({ type: 'CHAT_CLEAR_ERROR' });
}
/**
* Cancel the current streaming response if any is active.
* Abort controller is not cleared immediately to allow processStream
* to observe the cancellation flag and exit gracefully.
*/
cancelStream(): void {
if (this.currentStreamAbort) {
this.streamCancelled = true;
this.currentStreamAbort.abort();
this.dispatch({ type: 'CHAT_CANCEL_STREAM' });
}
}
async downloadFile(fileId: string, fileName?: string, containerId?: string): Promise<void> {
const token = await this.ensureAuthToken();
const params = containerId ? `?containerId=${encodeURIComponent(containerId)}` : '';
const response = await fetch(`${this.apiUrl}/files/${encodeURIComponent(fileId)}${params}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) throw new Error(`File download failed: ${response.status}`);
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName || fileId;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 100);
}
/**
* List all conversations from the server.
* @returns Array of conversation summaries
*/
async listConversations(limit: number = 20): Promise<{ conversations: ConversationSummary[]; hasMore: boolean }> {
const token = await this.ensureAuthToken();
const response = await fetch(`${this.apiUrl}/conversations?limit=${limit}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw createAppError(new Error(`Failed to list conversations: ${response.status}`), 'API');
}
return response.json();
}
/**
* Get messages for a specific conversation.
* @param conversationId - The conversation ID to fetch messages for
* @returns Array of conversation messages
*/
async getConversationMessages(conversationId: string): Promise<ConversationMessageInfo[]> {
const token = await this.ensureAuthToken();
const response = await fetch(`${this.apiUrl}/conversations/${conversationId}/messages`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw createAppError(new Error(`Failed to get conversation messages: ${response.status}`), 'API');
}
return response.json();
}
/**
* Delete a conversation.
* @param conversationId - The conversation ID to delete
*/
async deleteConversation(conversationId: string): Promise<void> {
const token = await this.ensureAuthToken();
const response = await fetch(`${this.apiUrl}/conversations/${conversationId}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw createAppError(new Error(`Failed to delete conversation: ${response.status}`), 'API');
}
}
/**
* Get a summary of files uploaded by this web app that are still stored in the Foundry project.
* Scoped to files whose names begin with the web-app upload prefix (see backend).
*/
async getUploadedFilesInfo(): Promise<{ count: number; totalBytes: number }> {
const token = await this.ensureAuthToken();
const response = await fetch(`${this.apiUrl}/files/uploaded`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) {
throw createAppError(new Error(`Failed to list uploaded files: ${response.status}`), 'API');
}
return response.json();
}
/**
* Delete every uploaded file that this web app previously uploaded for image attachments.
*/
async cleanupUploadedFiles(): Promise<{ deleted: number; failed: number }> {
const token = await this.ensureAuthToken();
const response = await fetch(`${this.apiUrl}/files/cleanup`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) {
throw createAppError(new Error(`Failed to clean up uploaded files: ${response.status}`), 'API');
}
return response.json();
}
}