rio-assist-widget 0.1.32 → 0.1.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,90 +1,90 @@
1
- import { LitElement, type PropertyValues } from 'lit';
2
- import { widgetStyles } from './rio-assist.styles';
3
- import { renderRioAssist } from './rio-assist.template';
4
- import {
5
- RioWebsocketClient,
6
- type RioIncomingMessage,
7
- } from '../../services/rioWebsocket';
8
- import MarkdownIt from 'markdown-it';
9
- import markdownItTaskLists from 'markdown-it-task-lists';
10
- import DOMPurify from 'dompurify';
11
-
12
- type ChatRole = 'user' | 'assistant';
13
-
14
- export type ChatMessage = {
15
- id: string;
16
- role: ChatRole;
17
- text: string;
18
- html?: string;
19
- timestamp: number;
20
- };
21
-
22
- type ConversationItem = {
23
- id: string;
24
- title: string;
25
- updatedAt: string;
26
- };
27
-
28
- type ConversationDeleteTarget = {
29
- id: string;
30
- title: string;
31
- index: number;
32
- };
33
-
34
- type ConversationRenameTarget = {
35
- id: string;
36
- title: string;
37
- index: number;
38
- draft: string;
39
- };
40
-
41
- type ConversationActionKind = 'rename' | 'delete';
42
-
43
- type ConversationActionAttempt = {
44
- action: ConversationActionKind;
45
- conversationId: string;
46
- originalTitle: string;
47
- index: number;
48
- newTitle?: string;
49
- snapshot?: ConversationItem;
50
- messagesSnapshot?: ChatMessage[];
51
- wasActive?: boolean;
52
- };
53
-
54
- type ConversationActionErrorState = ConversationActionAttempt & {
55
- message: string;
56
- };
57
-
58
- export type HeaderActionConfig = {
59
- id?: string;
60
- iconUrl: string;
61
- ariaLabel?: string;
62
- onClick?: () => void;
63
- };
64
-
65
- export class RioAssistWidget extends LitElement {
66
- static styles = widgetStyles;
67
-
68
- static properties = {
69
- open: { type: Boolean, state: true },
70
- message: { type: String, state: true },
71
- titleText: { type: String, attribute: 'data-title' },
72
- buttonLabel: { type: String, attribute: 'data-button-label' },
73
- placeholder: { type: String, attribute: 'data-placeholder' },
74
- accentColor: { type: String, attribute: 'data-accent-color' },
75
- apiBaseUrl: { type: String, attribute: 'data-api-base-url' },
76
- rioToken: { type: String, attribute: 'data-rio-token' },
77
- suggestionsSource: { type: String, attribute: 'data-suggestions' },
78
- messages: { state: true },
79
- isLoading: { type: Boolean, state: true },
80
- errorMessage: { type: String, state: true },
81
- showConversations: { type: Boolean, state: true },
82
- conversationSearch: { type: String, state: true },
83
- conversationMenuId: { state: true },
84
- conversationMenuPlacement: { state: true },
85
- isFullscreen: { type: Boolean, state: true },
86
- conversationScrollbar: { state: true },
87
- showNewConversationShortcut: { type: Boolean, state: true },
1
+ import { LitElement, type PropertyValues } from 'lit';
2
+ import { widgetStyles } from './rio-assist.styles';
3
+ import { renderRioAssist } from './rio-assist.template';
4
+ import {
5
+ RioWebsocketClient,
6
+ type RioIncomingMessage,
7
+ } from '../../services/rioWebsocket';
8
+ import MarkdownIt from 'markdown-it';
9
+ import markdownItTaskLists from 'markdown-it-task-lists';
10
+ import DOMPurify from 'dompurify';
11
+
12
+ type ChatRole = 'user' | 'assistant';
13
+
14
+ export type ChatMessage = {
15
+ id: string;
16
+ role: ChatRole;
17
+ text: string;
18
+ html?: string;
19
+ timestamp: number;
20
+ };
21
+
22
+ type ConversationItem = {
23
+ id: string;
24
+ title: string;
25
+ updatedAt: string;
26
+ };
27
+
28
+ type ConversationDeleteTarget = {
29
+ id: string;
30
+ title: string;
31
+ index: number;
32
+ };
33
+
34
+ type ConversationRenameTarget = {
35
+ id: string;
36
+ title: string;
37
+ index: number;
38
+ draft: string;
39
+ };
40
+
41
+ type ConversationActionKind = 'rename' | 'delete';
42
+
43
+ type ConversationActionAttempt = {
44
+ action: ConversationActionKind;
45
+ conversationId: string;
46
+ originalTitle: string;
47
+ index: number;
48
+ newTitle?: string;
49
+ snapshot?: ConversationItem;
50
+ messagesSnapshot?: ChatMessage[];
51
+ wasActive?: boolean;
52
+ };
53
+
54
+ type ConversationActionErrorState = ConversationActionAttempt & {
55
+ message: string;
56
+ };
57
+
58
+ export type HeaderActionConfig = {
59
+ id?: string;
60
+ iconUrl: string;
61
+ ariaLabel?: string;
62
+ onClick?: () => void;
63
+ };
64
+
65
+ export class RioAssistWidget extends LitElement {
66
+ static styles = widgetStyles;
67
+
68
+ static properties = {
69
+ open: { type: Boolean, state: true },
70
+ message: { type: String, state: true },
71
+ titleText: { type: String, attribute: 'data-title' },
72
+ buttonLabel: { type: String, attribute: 'data-button-label' },
73
+ placeholder: { type: String, attribute: 'data-placeholder' },
74
+ accentColor: { type: String, attribute: 'data-accent-color' },
75
+ apiBaseUrl: { type: String, attribute: 'data-api-base-url' },
76
+ rioToken: { type: String, attribute: 'data-rio-token' },
77
+ suggestionsSource: { type: String, attribute: 'data-suggestions' },
78
+ messages: { state: true },
79
+ isLoading: { type: Boolean, state: true },
80
+ errorMessage: { type: String, state: true },
81
+ showConversations: { type: Boolean, state: true },
82
+ conversationSearch: { type: String, state: true },
83
+ conversationMenuId: { state: true },
84
+ conversationMenuPlacement: { state: true },
85
+ isFullscreen: { type: Boolean, state: true },
86
+ conversationScrollbar: { state: true },
87
+ showNewConversationShortcut: { type: Boolean, state: true },
88
88
  conversations: { state: true },
89
89
  conversationHistoryLoading: { type: Boolean, state: true },
90
90
  activeConversationTitle: { state: true },
@@ -96,1790 +96,1920 @@ export class RioAssistWidget extends LitElement {
96
96
  conversationActionError: { attribute: false },
97
97
  headerActions: { attribute: false },
98
98
  homeUrl: { type: String, attribute: 'data-home-url' },
99
+ floatingButtonOffset: { type: Number, state: true },
100
+ };
101
+
102
+ open = false;
103
+
104
+ message = '';
105
+
106
+ titleText = 'Rio Insight';
107
+
108
+ buttonLabel = 'Rio Insight';
109
+
110
+ placeholder = 'Pergunte alguma coisa';
111
+
112
+ accentColor = '#008B9A';
113
+
114
+ floatingButtonOffset = 32;
115
+
116
+ apiBaseUrl = '';
117
+
118
+ rioToken = '';
119
+
120
+ suggestionsSource = '';
121
+
122
+ private randomizedSuggestions: string[] = [];
123
+
124
+ messages: ChatMessage[] = [];
125
+
126
+ isLoading = false;
127
+
128
+ errorMessage = '';
129
+
130
+ get loadingLabel() {
131
+ return this.loadingLabelInternal;
132
+ }
133
+
134
+ showConversations = false;
135
+
136
+ conversationSearch = '';
137
+
138
+ conversationMenuId: string | null = null;
139
+
140
+ conversationMenuPlacement: 'above' | 'below' = 'below';
141
+
142
+ isFullscreen = false;
143
+
144
+ showNewConversationShortcut = false;
145
+
146
+ conversationScrollbar = {
147
+ height: 0,
148
+ top: 0,
149
+ visible: false,
99
150
  };
100
-
101
- open = false;
102
-
103
- message = '';
104
-
105
- titleText = 'Rio Insight';
106
-
107
- buttonLabel = 'Rio Insight';
108
-
109
- placeholder = 'Pergunte alguma coisa';
110
-
111
- accentColor = '#008B9A';
112
-
113
- apiBaseUrl = '';
114
-
115
- rioToken = '';
116
-
117
- suggestionsSource = '';
118
-
119
- private randomizedSuggestions: string[] = [];
120
-
121
- messages: ChatMessage[] = [];
122
-
123
- isLoading = false;
124
-
125
- errorMessage = '';
126
-
127
- get loadingLabel() {
128
- return this.loadingLabelInternal;
129
- }
130
-
131
- showConversations = false;
132
-
133
- conversationSearch = '';
134
-
135
- conversationMenuId: string | null = null;
136
-
137
- conversationMenuPlacement: 'above' | 'below' = 'below';
138
-
139
- isFullscreen = false;
140
-
141
- showNewConversationShortcut = false;
142
-
143
- conversationScrollbar = {
144
- height: 0,
145
- top: 0,
146
- visible: false,
147
- };
148
-
149
- conversationHistoryLoading = false;
150
-
151
- conversationHistoryError = '';
152
-
153
- deleteConversationTarget: ConversationDeleteTarget | null = null;
154
-
155
- renameConversationTarget: ConversationRenameTarget | null = null;
151
+
152
+ conversationHistoryLoading = false;
153
+
154
+ conversationHistoryError = '';
155
+
156
+ deleteConversationTarget: ConversationDeleteTarget | null = null;
157
+
158
+ renameConversationTarget: ConversationRenameTarget | null = null;
156
159
 
157
160
  shortAnswerEnabled = true;
158
161
 
159
162
  newConversationConfirmOpen = false;
160
163
 
161
164
  conversationActionError: ConversationActionErrorState | null = null;
162
-
163
- private loadingLabelInternal = 'Rio Insight está respondendo...';
164
- private loadingTimerSlow: number | null = null;
165
- private loadingTimerTimeout: number | null = null;
166
-
167
- private refreshConversationsAfterResponse = false;
168
-
169
- activeConversationTitle: string | null = null;
170
-
171
- headerActions: HeaderActionConfig[] = [];
172
-
173
- homeUrl = '';
174
-
175
- private pendingConversationAction: ConversationActionAttempt | null = null;
176
-
177
- private generateConversationId() {
178
- if (!this.conversationUserId) {
179
- this.conversationUserId = this.inferUserIdFromToken();
180
- }
181
-
182
- const userSegment = this.conversationUserId ?? 'user';
183
- const id = `default-${userSegment}-${this.randomId(8)}`;
184
- console.info('[RioAssist][conversation] gerando conversationId', id);
185
- return id;
186
- }
187
-
188
- private inferUserIdFromToken(): string | null {
189
- const token = this.rioToken.trim();
190
- if (!token || !token.includes('.')) {
191
- return null;
192
- }
193
-
194
- const [, payload] = token.split('.');
195
- try {
196
- const decoded = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
197
- const candidate =
198
- decoded?.userId ??
199
- decoded?.user_id ??
200
- decoded?.sub ??
201
- decoded?.id ??
202
- decoded?.email ??
203
- decoded?.username;
204
-
205
- if (candidate && typeof candidate === 'string') {
206
- return candidate.replace(/[^a-zA-Z0-9_-]/g, '');
207
- }
208
- } catch {
209
- return null;
210
- }
211
-
212
- return null;
213
- }
214
-
215
- private randomId(length: number) {
216
- const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
217
- let result = '';
218
- for (let i = 0; i < length; i += 1) {
219
- result += chars.charAt(Math.floor(Math.random() * chars.length));
220
- }
221
- return result;
222
- }
223
-
224
- private conversationScrollbarRaf: number | null = null;
225
-
226
- private rioClient: RioWebsocketClient | null = null;
227
-
228
- private rioUnsubscribe: (() => void) | null = null;
229
-
230
- private loadingTimer: number | null = null;
231
-
232
- private currentConversationId: string | null = null;
233
-
234
- private conversationCounter = 0;
235
-
236
- private conversationUserId: string | null = null;
237
-
238
- private conversationScrollbarDraggingId: number | null = null;
239
-
240
- private conversationScrollbarDragState: {
241
- startY: number;
242
- startThumbTop: number;
243
- trackHeight: number;
244
- thumbHeight: number;
245
- list: HTMLElement;
246
- } | null = null;
247
-
248
- private markdownRenderer = new MarkdownIt({
249
- html: false,
250
- linkify: true,
251
- breaks: true,
252
- }).use(markdownItTaskLists);
253
-
254
- conversations: ConversationItem[] = [];
255
-
256
- get suggestions(): string[] {
257
- return this.randomizedSuggestions;
258
- }
259
-
260
- private parseSuggestions(source: string): string[] {
261
- if (!source) {
262
- return [];
263
- }
264
-
265
- return source
266
- .split('|')
267
- .map((item) => item.trim())
268
- .filter(Boolean);
269
- }
270
-
271
- private pickRandomSuggestions(options: string[], count: number): string[] {
272
- if (options.length <= count) {
273
- return [...options];
274
- }
275
-
276
- const pool = [...options];
277
- for (let index = pool.length - 1; index > 0; index -= 1) {
278
- const swapIndex = Math.floor(Math.random() * (index + 1));
279
- [pool[index], pool[swapIndex]] = [pool[swapIndex], pool[index]];
280
- }
281
-
282
- return pool.slice(0, count);
283
- }
284
-
285
- protected willUpdate(changedProperties: PropertyValues): void {
286
- super.willUpdate(changedProperties);
287
-
288
- if (changedProperties.has('suggestionsSource')) {
289
- this.randomizedSuggestions = this.pickRandomSuggestions(
290
- this.parseSuggestions(this.suggestionsSource),
291
- 3,
292
- );
293
- }
294
- }
295
-
296
- protected updated(changedProperties: PropertyValues): void {
297
- super.updated(changedProperties);
298
- this.style.setProperty('--accent-color', this.accentColor);
299
-
300
- if (
301
- changedProperties.has('isFullscreen') ||
302
- changedProperties.has('showConversations') ||
303
- changedProperties.has('conversations')
304
- ) {
305
- this.enqueueConversationScrollbarMeasure();
306
- }
307
-
308
- if (
309
- changedProperties.has('messages') ||
310
- (changedProperties.has('isLoading') && this.isLoading) ||
311
- (changedProperties.has('open') && this.open) ||
312
- (changedProperties.has('isFullscreen') && this.isFullscreen)
313
- ) {
314
- this.scrollConversationToBottom();
315
- }
316
- }
317
-
318
- protected firstUpdated(): void {
319
- this.enqueueConversationScrollbarMeasure();
320
- }
321
-
322
- disconnectedCallback(): void {
323
- super.disconnectedCallback();
324
- if (this.conversationScrollbarRaf !== null) {
325
- cancelAnimationFrame(this.conversationScrollbarRaf);
326
- this.conversationScrollbarRaf = null;
327
- }
328
-
329
- this.teardownRioClient();
330
- this.clearLoadingGuard();
331
- }
332
-
333
- get filteredConversations() {
334
- const query = this.conversationSearch.trim().toLowerCase();
335
- if (!query) {
336
- return this.conversations;
337
- }
338
-
339
- return this.conversations.filter((conversation) =>
340
- conversation.title.toLowerCase().includes(query),
341
- );
342
- }
343
-
344
- get hasActiveConversation() {
345
- return this.messages.length > 0;
346
- }
347
-
348
- togglePanel() {
349
- if (this.isFullscreen) {
350
- this.exitFullscreen(false);
351
- return;
352
- }
353
-
354
- this.open = !this.open;
355
- this.dispatchEvent(
356
- new CustomEvent(this.open ? 'rioassist:open' : 'rioassist:close', {
357
- bubbles: true,
358
- composed: true,
359
- }),
360
- );
361
- }
362
-
363
- closePanel() {
364
- this.isFullscreen = false;
365
- if (this.open) {
366
- this.togglePanel();
367
- }
368
- }
369
-
370
- openConversationsPanel() {
371
- this.showConversations = true;
372
- this.requestConversationHistory();
373
- }
374
-
375
- closeConversationsPanel() {
376
- this.showConversations = false;
377
- this.conversationMenuId = null;
378
- }
379
-
380
- toggleConversationsPanel() {
381
- this.showConversations = !this.showConversations;
382
- if (!this.showConversations) {
383
- this.conversationMenuId = null;
384
- return;
385
- }
386
-
387
- this.requestConversationHistory();
388
- }
389
-
390
- toggleNewConversationShortcut() {
391
- this.showNewConversationShortcut = !this.showNewConversationShortcut;
392
- }
393
-
394
- toggleShortAnswers() {
395
- this.shortAnswerEnabled = !this.shortAnswerEnabled;
396
- }
397
-
398
- handleConversationSelect(conversationId: string) {
399
- if (!conversationId) {
400
- return;
401
- }
402
-
403
- this.showConversations = false;
404
- this.conversationMenuId = null;
405
- this.errorMessage = '';
406
- this.currentConversationId = conversationId;
407
- this.activeConversationTitle = this.lookupConversationTitle(conversationId);
408
-
409
- console.info('[RioAssist][history] carregando conversa', conversationId);
410
- this.requestConversationHistory(conversationId);
411
- }
412
-
413
- handleConversationSearch(event: InputEvent) {
414
- this.conversationSearch = (event.target as HTMLInputElement).value;
415
- }
416
-
417
- handleConversationMenuToggle(event: Event, id: string) {
418
- event.stopPropagation();
419
-
420
- if (this.conversationMenuId === id) {
421
- this.conversationMenuId = null;
422
- return;
423
- }
424
-
425
- const button = event.currentTarget as HTMLElement;
426
- const container = this.renderRoot.querySelector(
427
- '.conversations-panel__surface',
428
- ) as HTMLElement | null;
429
-
430
- if (button && container) {
431
- const buttonRect = button.getBoundingClientRect();
432
- const containerRect = container.getBoundingClientRect();
433
- const spaceBelow = containerRect.bottom - buttonRect.bottom;
434
- this.conversationMenuPlacement = spaceBelow < 140 ? 'above' : 'below';
435
- } else {
436
- this.conversationMenuPlacement = 'below';
437
- }
438
-
439
- this.conversationMenuId = id;
440
- }
441
-
442
- handleConversationsPanelPointer(event: PointerEvent) {
443
- const target = event.target as HTMLElement;
444
- if (
445
- !target.closest('.conversation-menu') &&
446
- !target.closest('.conversation-menu-button')
447
- ) {
448
- this.conversationMenuId = null;
449
- }
450
- }
451
-
452
- handleConversationAction(action: 'rename' | 'delete', id: string) {
453
- this.conversationMenuId = null;
454
- const conversationIndex = this.conversations.findIndex((item) => item.id === id);
455
- if (conversationIndex === -1) {
456
- return;
457
- }
458
-
459
- const conversation = this.conversations[conversationIndex];
460
- if (action === 'delete') {
461
- this.deleteConversationTarget = {
462
- id: conversation.id,
463
- title: conversation.title,
464
- index: conversationIndex,
465
- };
466
- return;
467
- }
468
-
469
- this.renameConversationTarget = {
470
- id: conversation.id,
471
- title: conversation.title,
472
- index: conversationIndex,
473
- draft: conversation.title,
474
- };
475
- }
476
-
477
- handleHomeNavigation() {
478
- const detail = { url: this.homeUrl || null };
479
- const allowed = this.dispatchEvent(
480
- new CustomEvent('rioassist:home', {
481
- detail,
482
- bubbles: true,
483
- composed: true,
484
- cancelable: true,
485
- }),
486
- );
487
-
488
- if (!allowed) {
489
- return;
490
- }
491
-
492
- if (this.homeUrl) {
493
- window.location.assign(this.homeUrl);
494
- }
495
- }
496
-
497
- applyConversationRename(id: string, newTitle: string) {
498
- if (!id || !newTitle) {
499
- return;
500
- }
501
-
502
- let changed = false;
503
- this.conversations = this.conversations.map((conversation) => {
504
- if (conversation.id === id) {
505
- changed = true;
506
- return { ...conversation, title: newTitle };
507
- }
508
- return conversation;
509
- });
510
-
511
- if (!changed) {
512
- return;
513
- }
514
-
515
- if (this.currentConversationId === id) {
516
- this.activeConversationTitle = newTitle;
517
- }
518
- }
519
-
520
- applyConversationDeletion(id: string) {
521
- if (!id) {
522
- return;
523
- }
524
-
525
- const wasActive = this.currentConversationId === id;
526
- const next = this.conversations.filter((conversation) => conversation.id !== id);
527
-
528
- if (next.length === this.conversations.length) {
529
- return;
530
- }
531
-
532
- this.conversations = next;
533
-
534
- if (wasActive) {
535
- this.currentConversationId = null;
536
- this.activeConversationTitle = null;
537
- this.messages = [];
538
- }
539
- }
540
-
541
- private restoreConversationSnapshot(snapshot: ConversationItem | undefined, index: number) {
542
- if (!snapshot) {
543
- return;
544
- }
545
-
546
- const exists = this.conversations.some((conversation) => conversation.id === snapshot.id);
547
- if (exists) {
548
- return;
549
- }
550
-
551
- const next = [...this.conversations];
552
- const position = index >= 0 && index <= next.length ? index : next.length;
553
- next.splice(position, 0, snapshot);
554
- this.conversations = next;
555
- }
556
-
557
- async confirmDeleteConversation() {
558
- const target = this.deleteConversationTarget;
559
- if (!target) {
560
- return;
561
- }
562
-
563
- const snapshot =
564
- this.conversations[target.index] ??
565
- this.conversations.find((item) => item.id === target.id) ?? {
566
- id: target.id,
567
- title: target.title,
568
- updatedAt: new Date().toISOString(),
569
- };
570
- const isActive = this.currentConversationId === target.id;
571
- this.pendingConversationAction = {
572
- action: 'delete',
573
- conversationId: target.id,
574
- originalTitle: target.title,
575
- index: target.index,
576
- snapshot,
577
- messagesSnapshot: isActive ? [...this.messages] : undefined,
578
- wasActive: isActive,
579
- };
580
-
581
- const success = await this.dispatchConversationAction(
582
- 'delete',
583
- { id: target.id, title: target.title },
584
- target.index,
585
- );
586
- if (success) {
587
- this.deleteConversationTarget = null;
588
- return;
589
- }
590
-
591
- this.pendingConversationAction = null;
592
- }
593
-
594
- cancelDeleteConversation() {
595
- this.deleteConversationTarget = null;
596
- }
597
-
598
- handleRenameDraft(event: InputEvent) {
599
- if (!this.renameConversationTarget) {
600
- return;
601
- }
602
-
603
- this.renameConversationTarget = {
604
- ...this.renameConversationTarget,
605
- draft: (event.target as HTMLInputElement).value,
606
- };
607
- }
608
-
609
- async confirmRenameConversation() {
610
- const target = this.renameConversationTarget;
611
- if (!target) {
612
- return;
613
- }
614
-
615
- const newTitle = target.draft.trim();
616
- if (!newTitle) {
617
- return;
618
- }
619
-
620
- this.pendingConversationAction = {
621
- action: 'rename',
622
- conversationId: target.id,
623
- originalTitle: target.title,
624
- index: target.index,
625
- newTitle,
626
- };
627
-
628
- const success = await this.dispatchConversationAction(
629
- 'rename',
630
- { id: target.id, title: newTitle },
631
- target.index,
632
- newTitle,
633
- );
634
- if (success) {
635
- this.renameConversationTarget = null;
636
- return;
637
- }
638
-
639
- this.pendingConversationAction = null;
640
- }
641
-
642
- cancelRenameConversation() {
643
- this.renameConversationTarget = null;
644
- }
645
-
646
- cancelConversationActionError() {
647
- this.conversationActionError = null;
648
- this.pendingConversationAction = null;
649
- }
650
-
651
- async retryConversationAction() {
652
- const errorState = this.conversationActionError;
653
- if (!errorState) {
654
- return;
655
- }
656
-
657
- const indexFromState =
658
- typeof errorState.index === 'number' ? errorState.index : this.conversations.findIndex(
659
- (item) => item.id === errorState.conversationId,
660
- );
661
- const safeIndex =
662
- indexFromState >= 0
663
- ? indexFromState
664
- : this.conversations.length > 0
665
- ? this.conversations.length - 1
666
- : 0;
667
-
668
- const snapshot =
669
- errorState.snapshot ??
670
- this.conversations.find((item) => item.id === errorState.conversationId) ?? {
671
- id: errorState.conversationId,
672
- title: errorState.originalTitle,
673
- updatedAt: new Date().toISOString(),
674
- };
675
-
676
- this.pendingConversationAction = {
677
- action: errorState.action,
678
- conversationId: errorState.conversationId,
679
- originalTitle: errorState.originalTitle,
680
- index: safeIndex,
681
- newTitle: errorState.newTitle,
682
- snapshot,
683
- messagesSnapshot: errorState.messagesSnapshot,
684
- wasActive: errorState.wasActive,
685
- };
686
-
687
- this.conversationActionError = null;
688
-
689
- await this.dispatchConversationAction(
690
- errorState.action,
691
- { id: errorState.conversationId, title: errorState.newTitle ?? errorState.originalTitle },
692
- safeIndex,
693
- errorState.newTitle,
694
- );
695
- }
696
-
697
- private async dispatchConversationAction(
698
- action: 'rename' | 'delete',
699
- conversation: Pick<ConversationItem, 'id' | 'title'>,
700
- index: number,
701
- newTitle?: string,
702
- ) {
703
- const eventName =
704
- action === 'rename' ? 'rioassist:conversation-rename' : 'rioassist:conversation-delete';
705
- const detail = {
706
- id: conversation.id,
707
- title: conversation.title,
708
- index,
709
- action,
710
- };
711
-
712
- const allowed = this.dispatchEvent(
713
- new CustomEvent(eventName, {
714
- detail,
715
- bubbles: true,
716
- composed: true,
717
- cancelable: true,
718
- }),
719
- );
720
-
721
- if (!allowed) {
722
- return false;
723
- }
724
-
725
- if (action === 'delete') {
726
- const ok = await this.syncConversationDeleteBackend(conversation.id);
727
- return ok;
728
- }
729
-
730
- if (action === 'rename' && newTitle) {
731
- const ok = await this.syncConversationRenameBackend(conversation.id, newTitle);
732
- return ok;
733
- }
734
-
735
- return false;
736
- }
737
-
738
- private async syncConversationRenameBackend(conversationId: string, newTitle: string) {
739
- try {
740
- const client = this.ensureRioClient();
741
- await client.renameConversation(conversationId, newTitle);
742
- this.applyConversationRename(conversationId, newTitle);
743
- this.conversationHistoryError = '';
744
- return true;
745
- } catch (error) {
746
- console.error('[RioAssist][history] erro ao renomear conversa', error);
747
- this.conversationHistoryError =
748
- error instanceof Error && error.message
749
- ? error.message
750
- : 'Nao foi possivel renomear a conversa.';
751
- return false;
752
- }
753
- }
754
-
755
- private async syncConversationDeleteBackend(conversationId: string) {
756
- try {
757
- const client = this.ensureRioClient();
758
- await client.deleteConversation(conversationId);
759
- this.applyConversationDeletion(conversationId);
760
- this.conversationHistoryError = '';
761
- return true;
762
- } catch (error) {
763
- console.error('[RioAssist][history] erro ao excluir conversa', error);
764
- this.conversationHistoryError =
765
- error instanceof Error && error.message
766
- ? error.message
767
- : 'Nao foi possivel excluir a conversa.';
768
- return false;
769
- }
770
- }
771
-
772
- private handleConversationSystemAction(message: RioIncomingMessage) {
773
- const action = (message.action ?? '').toLowerCase();
774
- if (action === 'conversationrenamed') {
775
- const data = message.data as Record<string, unknown>;
776
- const id = this.extractString(data, ['conversationId', 'id']);
777
- const newTitle = this.extractString(data, ['newTitle', 'title']);
778
- if (id && newTitle) {
779
- this.applyConversationRename(id, newTitle);
780
- this.conversationHistoryError = '';
781
- if (
782
- this.pendingConversationAction &&
783
- this.pendingConversationAction.conversationId === id &&
784
- this.pendingConversationAction.action === 'rename'
785
- ) {
786
- this.pendingConversationAction = null;
787
- this.conversationActionError = null;
788
- }
789
- }
790
- return true;
791
- }
792
-
793
- if (action === 'conversationdeleted') {
794
- const data = message.data as Record<string, unknown>;
795
- const id = this.extractString(data, ['conversationId', 'id']);
796
- if (id) {
797
- this.applyConversationDeletion(id);
798
- this.conversationHistoryError = '';
799
- if (
800
- this.pendingConversationAction &&
801
- this.pendingConversationAction.conversationId === id &&
802
- this.pendingConversationAction.action === 'delete'
803
- ) {
804
- this.pendingConversationAction = null;
805
- this.conversationActionError = null;
806
- }
807
- }
808
- return true;
809
- }
810
-
811
- if (action === 'processing') {
812
- return true;
813
- }
814
-
815
- return false;
816
- }
817
-
818
- private handleConversationActionError(message: RioIncomingMessage) {
819
- const action = (message.action ?? '').toLowerCase();
820
- if (action !== 'error') {
821
- return false;
822
- }
823
-
824
- const data = message.data as Record<string, unknown>;
825
- const errorText =
826
- this.extractString(data, ['error', 'message', 'detail', 'description']) ||
827
- (typeof message.text === 'string' && message.text.trim()
828
- ? message.text
829
- : 'O agente retornou um erro ao processar a conversa.');
830
-
831
- const pending = this.pendingConversationAction;
832
- if (pending) {
833
- if (pending.action === 'rename') {
834
- this.applyConversationRename(pending.conversationId, pending.originalTitle);
835
- }
836
-
837
- if (pending.action === 'delete') {
838
- this.restoreConversationSnapshot(pending.snapshot, pending.index);
839
- if (pending.wasActive) {
840
- this.currentConversationId = pending.conversationId;
841
- this.activeConversationTitle = pending.originalTitle;
842
- this.messages = pending.messagesSnapshot ?? this.messages;
843
- }
844
- }
845
-
846
- this.conversationActionError = {
847
- ...pending,
848
- message: errorText,
849
- };
850
- this.pendingConversationAction = null;
851
- this.clearLoadingGuard();
852
- this.isLoading = false;
853
- return true;
854
- }
855
-
856
- this.errorMessage = errorText;
857
- this.clearLoadingGuard();
858
- this.isLoading = false;
859
- return true;
860
- }
861
-
862
- private shouldIgnoreAssistantPayload(action?: string) {
863
- if (!action) {
864
- return false;
865
- }
866
- const normalized = action.toLowerCase();
867
- return (
868
- normalized === 'processing' ||
869
- normalized === 'conversationrenamed' ||
870
- normalized === 'conversationdeleted'
871
- );
872
- }
873
-
874
- private extractString(
875
- data: Record<string, unknown> | undefined,
876
- keys: string[],
877
- ): string | null {
878
- if (!data || typeof data !== 'object') {
879
- return null;
880
- }
881
- for (const key of keys) {
882
- const value = data[key];
883
- if (typeof value === 'string' && value.trim()) {
884
- return value;
885
- }
886
- }
887
- return null;
888
- }
889
-
890
- handleHeaderActionClick(action: HeaderActionConfig, index: number) {
891
- const detail = {
892
- index,
893
- id: action.id ?? null,
894
- ariaLabel: action.ariaLabel ?? null,
895
- iconUrl: action.iconUrl,
896
- };
897
-
898
- const allowed = this.dispatchEvent(
899
- new CustomEvent('rioassist:header-action', {
900
- detail,
901
- bubbles: true,
902
- composed: true,
903
- cancelable: true,
904
- }),
905
- );
906
-
907
- if (!allowed) {
908
- return;
909
- }
910
-
911
- if (typeof action.onClick === 'function') {
912
- action.onClick();
913
- }
914
- }
915
-
916
- handleCloseAction() {
917
- if (this.isFullscreen) {
918
- this.exitFullscreen(true);
919
- return;
920
- }
921
-
922
- if (this.showConversations) {
923
- this.closeConversationsPanel();
924
- } else {
925
- this.closePanel();
926
- }
927
- }
928
-
929
- enterFullscreen() {
930
- if (this.isFullscreen) {
931
- return;
932
- }
933
-
934
- this.isFullscreen = true;
935
- this.open = false;
936
- this.showConversations = false;
937
- this.requestConversationHistory();
938
- }
939
-
940
- exitFullscreen(restorePanel: boolean) {
941
- if (!this.isFullscreen) {
942
- return;
943
- }
944
-
945
- this.isFullscreen = false;
946
- this.conversationMenuId = null;
947
- this.showNewConversationShortcut = false;
948
- if (restorePanel) {
949
- this.open = true;
950
- }
951
- }
952
-
953
- handleCreateConversation() {
954
- if (!this.hasActiveConversation) {
165
+
166
+ private loadingLabelInternal = 'Rio Insight está respondendo...';
167
+ private loadingTimerSlow: number | null = null;
168
+ private loadingTimerTimeout: number | null = null;
169
+
170
+ private refreshConversationsAfterResponse = false;
171
+
172
+ activeConversationTitle: string | null = null;
173
+
174
+ headerActions: HeaderActionConfig[] = [];
175
+
176
+ homeUrl = '';
177
+
178
+ private pendingConversationAction: ConversationActionAttempt | null = null;
179
+
180
+ private inferUserIdFromToken(): string | null {
181
+ const token = this.rioToken.trim();
182
+ if (!token || !token.includes('.')) {
183
+ return null;
184
+ }
185
+
186
+ const [, payload] = token.split('.');
187
+ try {
188
+ const decoded = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
189
+ const candidate =
190
+ decoded?.userId ??
191
+ decoded?.user_id ??
192
+ decoded?.sub ??
193
+ decoded?.id ??
194
+ decoded?.email ??
195
+ decoded?.username;
196
+
197
+ if (candidate && typeof candidate === 'string') {
198
+ return candidate.replace(/[^a-zA-Z0-9_:-]/g, '');
199
+ }
200
+ } catch {
201
+ return null;
202
+ }
203
+
204
+ return null;
205
+ }
206
+
207
+ private repairConversationId(rawId: string): string {
208
+ if (!rawId || rawId.includes(':')) {
209
+ return rawId;
210
+ }
211
+
212
+ const uuidMatch = rawId.match(
213
+ /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/,
214
+ );
215
+
216
+ if (!uuidMatch || uuidMatch.index === undefined) {
217
+ return rawId;
218
+ }
219
+
220
+ const uuid = uuidMatch[0];
221
+ const prefix = rawId.slice(0, uuidMatch.index).replace(/[-:]?$/, '');
222
+ const suffix = rawId.slice(uuidMatch.index + uuid.length);
223
+
224
+ const prefixPart = prefix ? `${prefix}:` : '';
225
+ return `${prefixPart}${uuid}${suffix}`;
226
+ }
227
+
228
+ private randomId(length: number) {
229
+ const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
230
+ let result = '';
231
+ for (let i = 0; i < length; i += 1) {
232
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
233
+ }
234
+ return result;
235
+ }
236
+
237
+ private clamp(value: number, min: number, max: number) {
238
+ return Math.min(Math.max(value, min), max);
239
+ }
240
+
241
+ private conversationScrollbarRaf: number | null = null;
242
+
243
+ private rioClient: RioWebsocketClient | null = null;
244
+
245
+ private rioUnsubscribe: (() => void) | null = null;
246
+
247
+ private loadingTimer: number | null = null;
248
+
249
+ private currentConversationId: string | null = null;
250
+
251
+ private conversationCounter = 0;
252
+
253
+ private conversationUserId: string | null = null;
254
+
255
+ private conversationScrollbarDraggingId: number | null = null;
256
+
257
+ private conversationScrollbarDragState: {
258
+ startY: number;
259
+ startThumbTop: number;
260
+ trackHeight: number;
261
+ thumbHeight: number;
262
+ list: HTMLElement;
263
+ } | null = null;
264
+
265
+ private floatingButtonDragState: {
266
+ pointerId: number;
267
+ startY: number;
268
+ startOffset: number;
269
+ buttonHeight: number;
270
+ } | null = null;
271
+
272
+ private floatingButtonDragged = false;
273
+
274
+ private suppressFloatingButtonClick = false;
275
+
276
+ private markdownRenderer = new MarkdownIt({
277
+ html: false,
278
+ linkify: true,
279
+ breaks: true,
280
+ }).use(markdownItTaskLists);
281
+
282
+ conversations: ConversationItem[] = [];
283
+
284
+ get suggestions(): string[] {
285
+ return this.randomizedSuggestions;
286
+ }
287
+
288
+ private parseSuggestions(source: string): string[] {
289
+ if (!source) {
290
+ return [];
291
+ }
292
+
293
+ return source
294
+ .split('|')
295
+ .map((item) => item.trim())
296
+ .filter(Boolean);
297
+ }
298
+
299
+ private pickRandomSuggestions(options: string[], count: number): string[] {
300
+ if (options.length <= count) {
301
+ return [...options];
302
+ }
303
+
304
+ const pool = [...options];
305
+ for (let index = pool.length - 1; index > 0; index -= 1) {
306
+ const swapIndex = Math.floor(Math.random() * (index + 1));
307
+ [pool[index], pool[swapIndex]] = [pool[swapIndex], pool[index]];
308
+ }
309
+
310
+ return pool.slice(0, count);
311
+ }
312
+
313
+ protected willUpdate(changedProperties: PropertyValues): void {
314
+ super.willUpdate(changedProperties);
315
+
316
+ if (changedProperties.has('suggestionsSource')) {
317
+ this.randomizedSuggestions = this.pickRandomSuggestions(
318
+ this.parseSuggestions(this.suggestionsSource),
319
+ 3,
320
+ );
321
+ }
322
+ }
323
+
324
+ protected updated(changedProperties: PropertyValues): void {
325
+ super.updated(changedProperties);
326
+ this.style.setProperty('--accent-color', this.accentColor);
327
+
328
+ if (
329
+ changedProperties.has('isFullscreen') ||
330
+ changedProperties.has('showConversations') ||
331
+ changedProperties.has('conversations')
332
+ ) {
333
+ this.enqueueConversationScrollbarMeasure();
334
+ }
335
+
336
+ if (
337
+ changedProperties.has('messages') ||
338
+ (changedProperties.has('isLoading') && this.isLoading) ||
339
+ (changedProperties.has('open') && this.open) ||
340
+ (changedProperties.has('isFullscreen') && this.isFullscreen)
341
+ ) {
342
+ this.scrollConversationToBottom();
343
+ }
344
+ }
345
+
346
+ protected firstUpdated(): void {
347
+ this.enqueueConversationScrollbarMeasure();
348
+ }
349
+
350
+ disconnectedCallback(): void {
351
+ super.disconnectedCallback();
352
+ if (this.conversationScrollbarRaf !== null) {
353
+ cancelAnimationFrame(this.conversationScrollbarRaf);
354
+ this.conversationScrollbarRaf = null;
355
+ }
356
+
357
+ this.teardownRioClient();
358
+ this.clearLoadingGuard();
359
+ }
360
+
361
+ get filteredConversations() {
362
+ const query = this.conversationSearch.trim().toLowerCase();
363
+ if (!query) {
364
+ return this.conversations;
365
+ }
366
+
367
+ return this.conversations.filter((conversation) =>
368
+ conversation.title.toLowerCase().includes(query),
369
+ );
370
+ }
371
+
372
+ get hasActiveConversation() {
373
+ return this.messages.length > 0;
374
+ }
375
+
376
+ handleFloatingButtonClick(event: Event) {
377
+ if (this.suppressFloatingButtonClick) {
378
+ event.preventDefault();
955
379
  return;
956
380
  }
957
381
 
958
- this.newConversationConfirmOpen = true;
382
+ this.togglePanel();
959
383
  }
960
384
 
961
- confirmCreateConversation() {
962
- if (!this.hasActiveConversation) {
963
- this.newConversationConfirmOpen = false;
385
+ handleFloatingButtonPointerDown(event: PointerEvent) {
386
+ const target = event.currentTarget as HTMLElement;
387
+ target.setPointerCapture(event.pointerId);
388
+
389
+ this.floatingButtonDragState = {
390
+ pointerId: event.pointerId,
391
+ startY: event.clientY,
392
+ startOffset: this.floatingButtonOffset,
393
+ buttonHeight: target.getBoundingClientRect().height,
394
+ };
395
+
396
+ this.floatingButtonDragged = false;
397
+ }
398
+
399
+ handleFloatingButtonPointerMove(event: PointerEvent) {
400
+ if (!this.floatingButtonDragState || this.floatingButtonDragState.pointerId !== event.pointerId) {
964
401
  return;
965
402
  }
966
403
 
967
- this.newConversationConfirmOpen = false;
404
+ const { startY, startOffset, buttonHeight } = this.floatingButtonDragState;
405
+ const deltaY = event.clientY - startY;
406
+ const viewportHeight = window.innerHeight || this.getBoundingClientRect().height || 0;
407
+ const margin = 12;
408
+ const maxBottom = Math.max(margin, viewportHeight - buttonHeight - margin);
968
409
 
969
- this.startNewConversation();
410
+ this.floatingButtonOffset = this.clamp(startOffset - deltaY, margin, maxBottom);
411
+ this.floatingButtonDragged = this.floatingButtonDragged || Math.abs(deltaY) > 3;
412
+ event.preventDefault();
970
413
  }
971
414
 
972
- cancelCreateConversation() {
973
- this.newConversationConfirmOpen = false;
415
+ handleFloatingButtonPointerUp(event: PointerEvent) {
416
+ this.finishFloatingButtonDrag(event);
974
417
  }
975
418
 
976
- private startNewConversation() {
977
- if (!this.hasActiveConversation) {
419
+ handleFloatingButtonPointerCancel(event: PointerEvent) {
420
+ this.finishFloatingButtonDrag(event);
421
+ }
422
+
423
+ private finishFloatingButtonDrag(event: PointerEvent) {
424
+ if (!this.floatingButtonDragState || this.floatingButtonDragState.pointerId !== event.pointerId) {
978
425
  return;
979
426
  }
980
427
 
981
- this.clearLoadingGuard();
982
- this.isLoading = false;
983
- this.messages = [];
984
- this.message = '';
985
- this.errorMessage = '';
986
- this.showConversations = false;
987
- this.teardownRioClient();
988
- this.currentConversationId = this.generateConversationId();
989
- this.activeConversationTitle = null;
990
- this.showNewConversationShortcut = false;
991
- this.dispatchEvent(
992
- new CustomEvent('rioassist:new-conversation', {
993
- bubbles: true,
994
- composed: true,
995
- }),
996
- );
997
- }
998
-
999
- handleConversationListScroll(event: Event) {
1000
- const target = event.currentTarget as HTMLElement | null;
1001
- if (!target) {
1002
- return;
1003
- }
1004
- this.updateConversationScrollbar(target);
1005
- }
1006
-
1007
- handleConversationScrollbarPointerDown(event: PointerEvent) {
1008
- const track = event.currentTarget as HTMLElement | null;
1009
- const list = this.renderRoot.querySelector(
1010
- '.conversation-list--sidebar',
1011
- ) as HTMLElement | null;
1012
-
1013
- if (!track || !list) {
1014
- return;
1015
- }
1016
-
1017
- const trackRect = track.getBoundingClientRect();
1018
- const thumbHeight = trackRect.height * (this.conversationScrollbar.height / 100);
1019
- const maxThumbTop = Math.max(trackRect.height - thumbHeight, 0);
1020
- const scrollRange = Math.max(list.scrollHeight - list.clientHeight, 1);
1021
- const currentThumbTop = (list.scrollTop / scrollRange) * maxThumbTop;
1022
- const offsetY = event.clientY - trackRect.top;
1023
- const isOnThumb = offsetY >= currentThumbTop && offsetY <= currentThumbTop + thumbHeight;
1024
-
1025
- const nextThumbTop = isOnThumb
1026
- ? currentThumbTop
1027
- : Math.min(Math.max(offsetY - thumbHeight / 2, 0), maxThumbTop);
1028
-
1029
- if (!isOnThumb) {
1030
- list.scrollTop = (nextThumbTop / Math.max(maxThumbTop, 1)) * (list.scrollHeight - list.clientHeight);
1031
- this.updateConversationScrollbar(list);
1032
- }
1033
-
1034
- track.setPointerCapture(event.pointerId);
1035
- this.conversationScrollbarDraggingId = event.pointerId;
1036
- this.conversationScrollbarDragState = {
1037
- startY: event.clientY,
1038
- startThumbTop: nextThumbTop,
1039
- trackHeight: trackRect.height,
1040
- thumbHeight,
1041
- list,
1042
- };
1043
- event.preventDefault();
1044
- }
1045
-
1046
- handleConversationScrollbarPointerMove(event: PointerEvent) {
1047
- if (
1048
- this.conversationScrollbarDraggingId === null ||
1049
- this.conversationScrollbarDraggingId !== event.pointerId ||
1050
- !this.conversationScrollbarDragState
1051
- ) {
1052
- return;
1053
- }
1054
-
1055
- const {
1056
- startY,
1057
- startThumbTop,
1058
- trackHeight,
1059
- thumbHeight,
1060
- list,
1061
- } = this.conversationScrollbarDragState;
1062
-
1063
- const maxThumbTop = Math.max(trackHeight - thumbHeight, 0);
1064
- const deltaY = event.clientY - startY;
1065
- const thumbTop = Math.min(Math.max(startThumbTop + deltaY, 0), maxThumbTop);
1066
- const scrollRange = list.scrollHeight - list.clientHeight;
1067
-
1068
- if (scrollRange > 0) {
1069
- list.scrollTop = (thumbTop / Math.max(maxThumbTop, 1)) * scrollRange;
1070
- this.updateConversationScrollbar(list);
1071
- }
1072
-
1073
- event.preventDefault();
1074
- }
1075
-
1076
- handleConversationScrollbarPointerUp(event: PointerEvent) {
1077
- if (this.conversationScrollbarDraggingId !== event.pointerId) {
1078
- return;
1079
- }
1080
-
1081
- const track = event.currentTarget as HTMLElement | null;
1082
- track?.releasePointerCapture(event.pointerId);
1083
-
1084
- this.conversationScrollbarDraggingId = null;
1085
- this.conversationScrollbarDragState = null;
1086
- }
1087
-
1088
- private enqueueConversationScrollbarMeasure() {
1089
- if (this.conversationScrollbarRaf !== null) {
1090
- return;
1091
- }
1092
-
1093
- this.conversationScrollbarRaf = requestAnimationFrame(() => {
1094
- this.conversationScrollbarRaf = null;
1095
- this.updateConversationScrollbar();
1096
- });
1097
- }
1098
-
1099
- private updateConversationScrollbar(target?: HTMLElement | null) {
1100
- const element =
1101
- target ??
1102
- (this.renderRoot.querySelector(
1103
- '.conversation-list--sidebar',
1104
- ) as HTMLElement | null);
1105
-
1106
- if (!element) {
1107
- if (this.conversationScrollbar.visible) {
1108
- this.conversationScrollbar = { height: 0, top: 0, visible: false };
1109
- }
1110
- return;
1111
- }
1112
-
1113
- const { scrollHeight, clientHeight, scrollTop } = element;
1114
- if (scrollHeight <= clientHeight + 1) {
1115
- if (this.conversationScrollbar.visible) {
1116
- this.conversationScrollbar = { height: 0, top: 0, visible: false };
1117
- }
1118
- return;
1119
- }
1120
-
1121
- const ratio = clientHeight / scrollHeight;
1122
- const height = Math.max(ratio * 100, 8);
1123
- const maxTop = 100 - height;
1124
- const top =
1125
- scrollTop / (scrollHeight - clientHeight) * (maxTop > 0 ? maxTop : 0);
1126
-
1127
- this.conversationScrollbar = {
1128
- height,
1129
- top,
1130
- visible: true,
1131
- };
1132
- }
1133
-
1134
- async onSuggestionClick(suggestion: string) {
1135
- await this.processMessage(suggestion);
1136
- }
1137
-
1138
- async handleSubmit(event: SubmitEvent) {
1139
- event.preventDefault();
1140
- await this.processMessage(this.message);
1141
- }
1142
-
1143
- private createMessage(role: ChatRole, text: string): ChatMessage {
1144
- const id = typeof crypto !== 'undefined' && 'randomUUID' in crypto
1145
- ? crypto.randomUUID()
1146
- : `${Date.now()}-${Math.random()}`;
1147
-
1148
- return {
1149
- id,
1150
- role,
1151
- text,
1152
- html: this.renderMarkdown(text),
1153
- timestamp: Date.now(),
1154
- };
1155
- }
1156
-
1157
- private async processMessage(rawValue: string) {
1158
- const content = rawValue.trim();
1159
- if (!content || this.isLoading) {
428
+ const target = event.currentTarget as HTMLElement | null;
429
+ if (target && target.hasPointerCapture(event.pointerId)) {
430
+ target.releasePointerCapture(event.pointerId);
431
+ }
432
+
433
+ if (this.floatingButtonDragged) {
434
+ this.suppressFloatingButtonClick = true;
435
+ window.setTimeout(() => {
436
+ this.suppressFloatingButtonClick = false;
437
+ }, 0);
438
+ }
439
+
440
+ this.floatingButtonDragState = null;
441
+ this.floatingButtonDragged = false;
442
+ }
443
+
444
+ togglePanel() {
445
+ if (this.isFullscreen) {
446
+ this.exitFullscreen(false);
1160
447
  return;
1161
448
  }
1162
449
 
1163
- const contentToSend = this.shortAnswerEnabled
1164
- ? `Quero uma resposta curta sobre: ${content}`
1165
- : content;
1166
- const contentToDisplay = content;
1167
-
1168
- if (!this.currentConversationId) {
1169
- this.currentConversationId = this.generateConversationId();
1170
- this.activeConversationTitle = null;
1171
- }
1172
-
1173
- const wasEmptyConversation = this.messages.length === 0;
1174
-
450
+ this.open = !this.open;
1175
451
  this.dispatchEvent(
1176
- new CustomEvent('rioassist:send', {
1177
- detail: {
1178
- message: content,
1179
- apiBaseUrl: this.apiBaseUrl,
1180
- token: this.rioToken,
1181
- },
1182
- bubbles: true,
1183
- composed: true,
1184
- }),
1185
- );
1186
-
1187
- const userMessage = this.createMessage('user', contentToDisplay);
1188
- this.messages = [...this.messages, userMessage];
1189
- if (wasEmptyConversation) {
1190
- this.showNewConversationShortcut = true;
1191
- this.refreshConversationsAfterResponse = true;
1192
- }
1193
- this.message = '';
1194
- this.errorMessage = '';
1195
- this.isLoading = true;
1196
- this.startLoadingGuard();
1197
-
1198
- try {
1199
- const client = this.ensureRioClient();
1200
- await client.sendMessage(contentToSend, this.currentConversationId);
1201
- } catch (error) {
1202
- this.clearLoadingGuard();
1203
- this.isLoading = false;
1204
- this.errorMessage = error instanceof Error
1205
- ? error.message
1206
- : 'Nao foi possivel enviar a mensagem para o agente.';
1207
- }
1208
- }
1209
-
1210
- private ensureRioClient() {
1211
- const token = this.rioToken.trim();
1212
- if (!token) {
1213
- throw new Error(
1214
- 'Informe o token RIO em data-rio-token para conectar no websocket do assistente.',
1215
- );
1216
- }
1217
-
1218
- if (!this.rioClient || !this.rioClient.matchesToken(token)) {
1219
- this.teardownRioClient();
1220
- this.rioClient = new RioWebsocketClient(token);
1221
- this.rioUnsubscribe = this.rioClient.onMessage((incoming) => {
1222
- this.handleIncomingMessage(incoming);
1223
- });
1224
- }
1225
-
1226
- return this.rioClient;
1227
- }
1228
-
1229
- private handleIncomingMessage(message: RioIncomingMessage) {
1230
- if (this.isHistoryPayload(message)) {
1231
- this.logHistoryPayload(message);
1232
- this.handleHistoryPayload(message.data);
1233
- return;
1234
- }
1235
-
1236
- if (this.handleConversationSystemAction(message)) {
1237
- return;
1238
- }
1239
-
1240
- if (this.handleConversationActionError(message)) {
1241
- return;
1242
- }
1243
-
1244
- if (this.shouldIgnoreAssistantPayload(message.action)) {
1245
- return;
1246
- }
1247
-
1248
- console.info('[RioAssist][ws] resposta de mensagem recebida', {
1249
- action: message.action ?? 'message',
1250
- text: message.text,
1251
- raw: message.raw,
1252
- data: message.data,
1253
- });
1254
-
1255
- // Handle "processing" type messages - just keep loading state, don't create message
1256
- if (message.action === 'processing') {
1257
- console.info('[RioAssist][ws] processando mensagem - aguardando resposta final');
1258
- // Keep isLoading = true, don't create a message balloon
1259
- return;
1260
- }
1261
-
1262
- const assistantMessage = this.createMessage('assistant', message.text);
1263
- this.messages = [...this.messages, assistantMessage];
1264
- this.clearLoadingGuard();
1265
- this.isLoading = false;
1266
-
1267
- if (this.refreshConversationsAfterResponse) {
1268
- this.refreshConversationsAfterResponse = false;
1269
- this.requestConversationHistory();
1270
- }
1271
- }
1272
-
1273
- private teardownRioClient() {
1274
- if (this.rioUnsubscribe) {
1275
- this.rioUnsubscribe();
1276
- this.rioUnsubscribe = null;
1277
- }
1278
-
1279
- if (this.rioClient) {
1280
- this.rioClient.close();
1281
- this.rioClient = null;
1282
- }
1283
- }
1284
-
1285
- async requestConversationHistory(conversationId?: string) {
1286
- try {
1287
- const client = this.ensureRioClient();
1288
- const limit = 50;
1289
-
1290
- console.info('[RioAssist][history] solicitando historico de conversas', {
1291
- conversationId: conversationId ?? null,
1292
- limit,
1293
- });
1294
-
1295
- this.conversationHistoryError = '';
1296
- this.conversationHistoryLoading = true;
1297
- await client.requestHistory({ conversationId, limit });
1298
- } catch (error) {
1299
- console.error('[RioAssist][history] erro ao solicitar historico', error);
1300
- this.conversationHistoryError =
1301
- error instanceof Error && error.message
1302
- ? error.message
1303
- : 'Nao foi possivel carregar as conversas.';
1304
- this.conversationHistoryLoading = false;
1305
- }
1306
- }
1307
-
1308
- private handleHistoryPayload(payload: unknown) {
1309
- const entries = this.extractHistoryEntries(payload);
1310
- const conversationId = this.extractConversationId(payload);
1311
-
1312
- if (conversationId !== null && conversationId !== undefined) {
1313
- this.applyMessageHistory(entries, conversationId);
1314
- return;
1315
- }
1316
-
1317
- if (this.isMessageHistoryEntries(entries)) {
1318
- this.applyMessageHistory(entries);
1319
- return;
1320
- }
1321
-
1322
- this.applyConversationHistoryFromEntries(entries);
1323
-
1324
- if (this.refreshConversationsAfterResponse) {
1325
- this.refreshConversationsAfterResponse = false;
1326
- }
1327
- }
1328
-
1329
- private isHistoryPayload(message: RioIncomingMessage) {
1330
- if (
1331
- typeof message.action === 'string' &&
1332
- message.action.toLowerCase().includes('history')
1333
- ) {
1334
- return true;
1335
- }
1336
-
1337
- const data = message.data;
1338
- if (data && typeof data === 'object') {
1339
- const action = (data as any).action;
1340
- if (typeof action === 'string' && action.toLowerCase().includes('history')) {
1341
- return true;
1342
- }
1343
-
1344
- if (Array.isArray((data as any).history) || Array.isArray((data as any).conversations)) {
1345
- return true;
1346
- }
1347
- }
1348
-
1349
- return false;
1350
- }
1351
-
1352
- private logHistoryPayload(message: RioIncomingMessage) {
1353
- const label = '[RioAssist][history] payload recebido do websocket';
1354
- if (message.data !== null && message.data !== undefined) {
1355
- console.info(label, message.data);
1356
- return;
1357
- }
1358
-
1359
- console.info(label, message.raw);
1360
- }
1361
-
1362
- private applyConversationHistoryFromEntries(entries: unknown[]) {
1363
- if (entries.length === 0) {
1364
- console.info('[RioAssist][history] payload sem itens para montar lista de conversas');
1365
- this.conversations = [];
1366
- this.conversationHistoryLoading = false;
1367
- this.conversationHistoryError = '';
1368
- return;
1369
- }
1370
-
1371
- const map = new Map<string, ConversationItem>();
1372
-
1373
- entries.forEach((entry, index) => {
1374
- if (!entry || typeof entry !== 'object') {
1375
- return;
1376
- }
1377
-
1378
- const normalized = this.normalizeConversationItem(
1379
- entry as Record<string, unknown>,
1380
- index,
1381
- );
1382
-
1383
- if (!normalized) {
1384
- return;
1385
- }
1386
-
1387
- const current = map.get(normalized.id);
1388
- if (!current) {
1389
- map.set(normalized.id, normalized);
1390
- return;
1391
- }
1392
-
1393
- const currentTime = Date.parse(current.updatedAt);
1394
- const nextTime = Date.parse(normalized.updatedAt);
1395
-
1396
- if (Number.isFinite(nextTime) && nextTime > currentTime) {
1397
- map.set(normalized.id, normalized);
1398
- }
1399
- });
1400
-
1401
- const conversations = Array.from(map.values()).sort((a, b) => {
1402
- const order = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
1403
- return Number.isFinite(order) ? order : 0;
1404
- });
1405
-
1406
- this.conversations = conversations;
1407
- this.conversationHistoryLoading = false;
1408
- this.conversationHistoryError = '';
1409
- this.syncActiveConversationTitle();
1410
- console.info('[RioAssist][history] conversas normalizadas', conversations);
1411
- }
1412
-
1413
- private applyMessageHistory(entries: unknown[], conversationId?: string | null) {
1414
- if (entries.length === 0) {
1415
- console.info('[RioAssist][history] lista de mensagens vazia', { conversationId });
1416
- this.messages = [];
1417
- this.showConversations = false;
1418
- this.clearLoadingGuard();
1419
- this.isLoading = false;
1420
- this.conversationHistoryLoading = false;
1421
- return;
1422
- }
1423
-
1424
- const normalized = entries.flatMap((entry, index) =>
1425
- this.normalizeHistoryMessages(entry as Record<string, unknown>, index),
1426
- );
1427
-
1428
- if (conversationId) {
1429
- this.currentConversationId = conversationId;
1430
- }
1431
-
1432
- this.messages = normalized;
1433
- this.showConversations = false;
1434
- this.clearLoadingGuard();
1435
- this.isLoading = false;
1436
- this.showNewConversationShortcut = normalized.length > 0;
1437
- this.conversationHistoryLoading = false;
1438
- this.refreshConversationsAfterResponse = false;
1439
-
1440
- console.info('[RioAssist][history] mensagens carregadas', {
1441
- conversationId: conversationId ?? null,
1442
- total: normalized.length,
1443
- });
1444
- }
1445
-
1446
- private extractHistoryEntries(payload: unknown): unknown[] {
1447
- if (Array.isArray(payload)) {
1448
- return payload;
1449
- }
1450
-
1451
- if (payload && typeof payload === 'object') {
1452
- const record = payload as Record<string, unknown>;
1453
- const candidates = [
1454
- record.history,
1455
- record.conversations,
1456
- record.data,
1457
- record.items,
1458
- record.messages,
1459
- ];
1460
-
1461
- for (const candidate of candidates) {
1462
- if (Array.isArray(candidate)) {
1463
- return candidate;
1464
- }
1465
- }
1466
-
1467
- if (record.data && typeof record.data === 'object' && !Array.isArray(record.data)) {
1468
- const nested = this.extractHistoryEntries(record.data);
1469
- if (nested.length > 0) {
1470
- return nested;
1471
- }
1472
- }
1473
- }
1474
-
1475
- return [];
1476
- }
1477
-
1478
- private extractConversationId(payload: unknown): string | null | undefined {
1479
- if (payload && typeof payload === 'object') {
1480
- const record = payload as Record<string, unknown>;
1481
- const candidates = [
1482
- record.conversationId,
1483
- record.conversationUUID,
1484
- record.conversationUuid,
1485
- record.uuid,
1486
- record.id,
1487
- ];
1488
-
1489
- for (const candidate of candidates) {
1490
- if (candidate === null) {
1491
- return null;
1492
- }
1493
-
1494
- if (candidate !== undefined) {
1495
- return String(candidate);
1496
- }
1497
- }
1498
- }
1499
-
1500
- return undefined;
1501
- }
1502
-
1503
- private isMessageHistoryEntries(entries: unknown[]) {
1504
- return entries.some((entry) => this.looksLikeMessageHistoryEntry(entry));
1505
- }
1506
-
1507
- private looksLikeMessageHistoryEntry(entry: unknown) {
1508
- if (!entry || typeof entry !== 'object') {
1509
- return false;
1510
- }
1511
-
1512
- const item = entry as Record<string, unknown>;
1513
- const role = item.role ?? item.sender ?? item.from ?? item.author ?? item.type;
1514
- if (typeof role === 'string' && role.trim().length > 0) {
1515
- return true;
1516
- }
1517
-
1518
- if (
1519
- typeof item.content === 'string' ||
1520
- typeof item.message === 'string' ||
1521
- typeof item.text === 'string' ||
1522
- typeof item.response === 'string'
1523
- ) {
1524
- return true;
1525
- }
1526
-
1527
- if (Array.isArray(item.parts) && item.parts.length > 0) {
1528
- return true;
1529
- }
1530
-
1531
- return false;
1532
- }
1533
-
1534
- private normalizeConversationItem(
1535
- value: Record<string, unknown>,
1536
- index: number,
1537
- ): ConversationItem | null {
1538
- const rawId =
1539
- value.id ??
1540
- value.conversationId ??
1541
- value.conversationUUID ??
1542
- value.conversationUuid ??
1543
- value.uuid;
1544
-
1545
- const id = rawId !== undefined && rawId !== null ? String(rawId) : `history-${index + 1}`;
1546
-
1547
- const rawTitle =
1548
- value.title ??
1549
- value.name ??
1550
- value.topic ??
1551
- value.subject ??
1552
- value.question ??
1553
- value.query ??
1554
- value.message;
1555
-
1556
- const title =
1557
- typeof rawTitle === 'string' && rawTitle.trim().length > 0
1558
- ? rawTitle.trim()
1559
- : `Conversa ${index + 1}`;
1560
-
1561
- const rawUpdated =
1562
- value.updatedAt ??
1563
- value.updated_at ??
1564
- value.lastMessageAt ??
1565
- value.last_message_at ??
1566
- value.createdAt ??
1567
- value.created_at ??
1568
- value.timestamp ??
1569
- value.date;
1570
-
1571
- const updatedAt = this.toIsoString(rawUpdated);
1572
-
1573
- return { id, title, updatedAt };
1574
- }
1575
-
1576
- private normalizeHistoryMessages(
1577
- value: Record<string, unknown>,
1578
- index: number,
1579
- ): ChatMessage[] {
1580
- const messages: ChatMessage[] = [];
1581
-
1582
- const rawUserText = value.message ?? value.question ?? value.query ?? value.text ?? value.content;
1583
- const userText = typeof rawUserText === 'string' ? rawUserText.trim() : '';
1584
-
1585
- const rawResponseText =
1586
- value.response ?? value.answer ?? value.reply ?? value.completion ?? value.body ?? value.preview;
1587
- const responseText = typeof rawResponseText === 'string' ? rawResponseText.trim() : '';
1588
-
1589
- const rawId = value.id ?? value.messageId ?? value.uuid ?? value.conversationMessageId;
1590
- const baseId = rawId !== undefined && rawId !== null
1591
- ? String(rawId)
1592
- : `history-${index + 1}`;
1593
-
1594
- const userTimestampValue =
1595
- value.timestamp ??
1596
- value.createdAt ??
1597
- value.created_at ??
1598
- value.date ??
1599
- value.time;
1600
- const assistantTimestampValue =
1601
- value.responseTimestamp ??
1602
- value.responseTime ??
1603
- value.responseDate ??
1604
- value.response_at ??
1605
- value.updatedAt ??
1606
- value.updated_at;
1607
-
1608
- const userTimestamp = this.parseTimestamp(userTimestampValue);
1609
- const assistantTimestamp = this.parseTimestamp(
1610
- assistantTimestampValue,
1611
- userTimestamp + 1,
1612
- );
1613
-
1614
- if (responseText) {
1615
- if (userText) {
1616
- messages.push({
1617
- id: `${baseId}-user`,
1618
- role: 'user',
1619
- text: userText,
1620
- html: this.renderMarkdown(userText),
1621
- timestamp: userTimestamp,
1622
- });
1623
- }
1624
-
1625
- messages.push({
1626
- id: `${baseId}-assistant`,
1627
- role: 'assistant',
1628
- text: responseText,
1629
- html: this.renderMarkdown(responseText),
1630
- timestamp: assistantTimestamp,
1631
- });
1632
- } else if (userText) {
1633
- // Se n�o tiver resposta, n�o exibimos a mensagem do usuario isolada.
1634
- return [];
1635
- }
1636
-
1637
- if (messages.length > 0) {
1638
- return messages;
1639
- }
1640
-
1641
- const fallback = this.normalizeSingleHistoryMessage(value, index);
1642
- return fallback ? [fallback] : [];
1643
- }
1644
-
1645
- private normalizeSingleHistoryMessage(
1646
- value: Record<string, unknown>,
1647
- index: number,
1648
- ): ChatMessage | null {
1649
- const rawText =
1650
- value.text ??
1651
- value.message ??
1652
- value.content ??
1653
- value.response ??
1654
- value.body ??
1655
- value.preview;
1656
-
1657
- const text = typeof rawText === 'string' && rawText.trim().length > 0
1658
- ? rawText
1659
- : '';
1660
-
1661
- if (!text) {
1662
- return null;
1663
- }
1664
-
1665
- const role = this.normalizeRole(
1666
- value.role ??
1667
- value.sender ??
1668
- value.from ??
1669
- value.author ??
1670
- value.type ??
1671
- value.direction,
1672
- );
1673
-
1674
- const rawId = value.id ?? value.messageId ?? value.uuid ?? value.conversationMessageId;
1675
- const id = rawId !== undefined && rawId !== null
1676
- ? String(rawId)
1677
- : `history-message-${index + 1}`;
1678
-
1679
- const timestampValue =
1680
- value.timestamp ??
1681
- value.createdAt ??
1682
- value.created_at ??
1683
- value.updatedAt ??
1684
- value.updated_at ??
1685
- value.date ??
1686
- value.time;
1687
-
1688
- const timestamp = this.parseTimestamp(timestampValue);
1689
-
1690
- return {
1691
- id,
1692
- role,
1693
- text,
1694
- html: this.renderMarkdown(text),
1695
- timestamp,
1696
- };
1697
- }
1698
-
1699
- private normalizeRole(value: unknown): ChatRole {
1700
- if (typeof value === 'string') {
1701
- const normalized = value.toLowerCase();
1702
- if (normalized.includes('user') || normalized.includes('client')) {
1703
- return 'user';
1704
- }
1705
- if (normalized.includes('assistant') || normalized.includes('agent') || normalized.includes('bot')) {
1706
- return 'assistant';
1707
- }
1708
- }
1709
-
1710
- return 'assistant';
1711
- }
1712
-
1713
- private parseTimestamp(value: unknown, fallback?: number) {
1714
- const parsed = Date.parse(this.toIsoString(value));
1715
- if (Number.isFinite(parsed)) {
1716
- return parsed;
1717
- }
1718
-
1719
- if (Number.isFinite(fallback ?? NaN)) {
1720
- return fallback as number;
1721
- }
1722
-
1723
- return Date.now();
1724
- }
1725
-
1726
- private lookupConversationTitle(conversationId: string | null) {
1727
- if (!conversationId) {
1728
- return null;
1729
- }
1730
-
1731
- const found = this.conversations.find((item) => item.id === conversationId);
1732
- return found ? found.title : null;
1733
- }
1734
-
1735
- private syncActiveConversationTitle() {
1736
- if (!this.currentConversationId) {
1737
- return;
1738
- }
1739
-
1740
- const title = this.lookupConversationTitle(this.currentConversationId);
1741
- if (title) {
1742
- this.activeConversationTitle = title;
1743
- }
1744
- }
1745
-
1746
- private toIsoString(value: unknown) {
1747
- if (typeof value === 'string' || typeof value === 'number') {
1748
- const date = new Date(value);
1749
- if (!Number.isNaN(date.getTime())) {
1750
- return date.toISOString();
1751
- }
1752
- }
1753
-
1754
- return new Date().toISOString();
1755
- }
1756
-
1757
- private startLoadingGuard() {
1758
- this.clearLoadingGuard();
1759
- this.loadingLabelInternal = 'RIO Insight está respondendo';
1760
-
1761
- // Após 20s, mensagem de processamento prolongado.
1762
- this.loadingTimerSlow = window.setTimeout(() => {
1763
- this.loadingLabelInternal = 'RIO Insight continua respondendo';
1764
- this.requestUpdate();
1765
- }, 20000);
1766
-
1767
- // Após 60s, aviso de demora maior.
1768
- this.loadingTimerTimeout = window.setTimeout(() => {
1769
- this.loadingLabelInternal =
1770
- 'RIO Insight ainda está processando sua resposta. Peço que aguarde um pouco mais';
1771
- this.requestUpdate();
1772
- }, 60000);
1773
-
1774
- // Após 120s, novo aviso de demora maior.
1775
- this.loadingTimerTimeout = window.setTimeout(() => {
1776
- this.loadingLabelInternal =
1777
- 'Essa solicitação está demorando um pouco mais que o esperado. Pode favor, aguarde mais um pouco';
1778
- this.requestUpdate();
1779
- }, 120000);
1780
- }
1781
-
1782
- private clearLoadingGuard() {
1783
- if (this.loadingTimer !== null) {
1784
- window.clearTimeout(this.loadingTimer);
1785
- this.loadingTimer = null;
1786
- }
1787
-
1788
- if (this.loadingTimerSlow !== null) {
1789
- window.clearTimeout(this.loadingTimerSlow);
1790
- this.loadingTimerSlow = null;
1791
- }
1792
-
1793
- if (this.loadingTimerTimeout !== null) {
1794
- window.clearTimeout(this.loadingTimerTimeout);
1795
- this.loadingTimerTimeout = null;
1796
- }
1797
- }
1798
-
1799
- private scrollConversationToBottom() {
1800
- const containers = Array.from(
1801
- this.renderRoot.querySelectorAll('.panel-content'),
1802
- ) as HTMLElement[];
1803
-
1804
- containers.forEach((container) => {
1805
- requestAnimationFrame(() => {
1806
- container.scrollTop = container.scrollHeight;
1807
- });
1808
- });
1809
- }
1810
-
1811
- private renderMarkdown(content: string) {
1812
- const rendered = this.markdownRenderer.render(content);
1813
- const clean = DOMPurify.sanitize(rendered, {
1814
- ALLOWED_TAGS: [
1815
- 'a',
1816
- 'p',
1817
- 'ul',
1818
- 'ol',
1819
- 'li',
1820
- 'code',
1821
- 'pre',
1822
- 'strong',
1823
- 'em',
1824
- 'blockquote',
1825
- 'table',
1826
- 'thead',
1827
- 'tbody',
1828
- 'tr',
1829
- 'th',
1830
- 'td',
1831
- 'del',
1832
- 'hr',
1833
- 'br',
1834
- 'img',
1835
- 'span',
1836
- 'input',
1837
- ],
1838
- ALLOWED_ATTR: [
1839
- 'href',
1840
- 'title',
1841
- 'target',
1842
- 'rel',
1843
- 'src',
1844
- 'alt',
1845
- 'class',
1846
- 'type',
1847
- 'checked',
1848
- 'disabled',
1849
- 'aria-label',
1850
- ],
1851
- ALLOW_DATA_ATTR: false,
1852
- FORBID_TAGS: ['style', 'script'],
1853
- USE_PROFILES: { html: true },
1854
- });
1855
-
1856
- const container = document.createElement('div');
1857
- container.innerHTML = clean;
1858
-
1859
- container.querySelectorAll('a').forEach((anchor) => {
1860
- anchor.setAttribute('target', '_blank');
1861
- anchor.setAttribute('rel', 'noopener noreferrer');
1862
- });
1863
-
1864
- container.querySelectorAll('input[type="checkbox"]').forEach((checkbox) => {
1865
- checkbox.setAttribute('disabled', '');
1866
- checkbox.setAttribute('tabindex', '-1');
1867
- });
1868
-
1869
- return container.innerHTML;
1870
- }
1871
-
1872
- render() {
1873
- return renderRioAssist(this);
1874
- }
1875
-
1876
- }
1877
- declare global {
1878
- interface HTMLElementTagNameMap {
1879
- 'rio-assist-widget': RioAssistWidget;
1880
- }
1881
- }
1882
-
1883
- if (!customElements.get('rio-assist-widget')) {
1884
- customElements.define('rio-assist-widget', RioAssistWidget);
1885
- }
452
+ new CustomEvent(this.open ? 'rioassist:open' : 'rioassist:close', {
453
+ bubbles: true,
454
+ composed: true,
455
+ }),
456
+ );
457
+ }
458
+
459
+ closePanel() {
460
+ this.isFullscreen = false;
461
+ if (this.open) {
462
+ this.togglePanel();
463
+ }
464
+ }
465
+
466
+ openConversationsPanel() {
467
+ this.showConversations = true;
468
+ this.requestConversationHistory();
469
+ }
470
+
471
+ closeConversationsPanel() {
472
+ this.showConversations = false;
473
+ this.conversationMenuId = null;
474
+ }
475
+
476
+ toggleConversationsPanel() {
477
+ this.showConversations = !this.showConversations;
478
+ if (!this.showConversations) {
479
+ this.conversationMenuId = null;
480
+ return;
481
+ }
482
+
483
+ this.requestConversationHistory();
484
+ }
485
+
486
+ toggleNewConversationShortcut() {
487
+ this.showNewConversationShortcut = !this.showNewConversationShortcut;
488
+ }
489
+
490
+ toggleShortAnswers() {
491
+ this.shortAnswerEnabled = !this.shortAnswerEnabled;
492
+ }
493
+
494
+ handleConversationSelect(conversationId: string) {
495
+ if (!conversationId) {
496
+ return;
497
+ }
498
+
499
+ this.showConversations = false;
500
+ this.conversationMenuId = null;
501
+ this.errorMessage = '';
502
+ this.currentConversationId = conversationId;
503
+ this.activeConversationTitle = this.lookupConversationTitle(conversationId);
504
+
505
+ console.info('[RioAssist][history] carregando conversa', conversationId);
506
+ this.requestConversationHistory(conversationId);
507
+ }
508
+
509
+ handleConversationSearch(event: InputEvent) {
510
+ this.conversationSearch = (event.target as HTMLInputElement).value;
511
+ }
512
+
513
+ handleConversationMenuToggle(event: Event, id: string) {
514
+ event.stopPropagation();
515
+
516
+ if (this.conversationMenuId === id) {
517
+ this.conversationMenuId = null;
518
+ return;
519
+ }
520
+
521
+ const button = event.currentTarget as HTMLElement;
522
+ const container = this.renderRoot.querySelector(
523
+ '.conversations-panel__surface',
524
+ ) as HTMLElement | null;
525
+
526
+ if (button && container) {
527
+ const buttonRect = button.getBoundingClientRect();
528
+ const containerRect = container.getBoundingClientRect();
529
+ const spaceBelow = containerRect.bottom - buttonRect.bottom;
530
+ this.conversationMenuPlacement = spaceBelow < 140 ? 'above' : 'below';
531
+ } else {
532
+ this.conversationMenuPlacement = 'below';
533
+ }
534
+
535
+ this.conversationMenuId = id;
536
+ }
537
+
538
+ handleConversationsPanelPointer(event: PointerEvent) {
539
+ const target = event.target as HTMLElement;
540
+ if (
541
+ !target.closest('.conversation-menu') &&
542
+ !target.closest('.conversation-menu-button')
543
+ ) {
544
+ this.conversationMenuId = null;
545
+ }
546
+ }
547
+
548
+ handleConversationAction(action: 'rename' | 'delete', id: string) {
549
+ this.conversationMenuId = null;
550
+ const conversationIndex = this.conversations.findIndex((item) => item.id === id);
551
+ if (conversationIndex === -1) {
552
+ return;
553
+ }
554
+
555
+ const conversation = this.conversations[conversationIndex];
556
+ if (action === 'delete') {
557
+ this.deleteConversationTarget = {
558
+ id: conversation.id,
559
+ title: conversation.title,
560
+ index: conversationIndex,
561
+ };
562
+ return;
563
+ }
564
+
565
+ this.renameConversationTarget = {
566
+ id: conversation.id,
567
+ title: conversation.title,
568
+ index: conversationIndex,
569
+ draft: conversation.title,
570
+ };
571
+ }
572
+
573
+ handleHomeNavigation() {
574
+ const detail = { url: this.homeUrl || null };
575
+ const allowed = this.dispatchEvent(
576
+ new CustomEvent('rioassist:home', {
577
+ detail,
578
+ bubbles: true,
579
+ composed: true,
580
+ cancelable: true,
581
+ }),
582
+ );
583
+
584
+ if (!allowed) {
585
+ return;
586
+ }
587
+
588
+ if (this.homeUrl) {
589
+ window.location.assign(this.homeUrl);
590
+ }
591
+ }
592
+
593
+ applyConversationRename(id: string, newTitle: string) {
594
+ if (!id || !newTitle) {
595
+ return;
596
+ }
597
+
598
+ let changed = false;
599
+ this.conversations = this.conversations.map((conversation) => {
600
+ if (conversation.id === id) {
601
+ changed = true;
602
+ return { ...conversation, title: newTitle };
603
+ }
604
+ return conversation;
605
+ });
606
+
607
+ if (!changed) {
608
+ return;
609
+ }
610
+
611
+ if (this.currentConversationId === id) {
612
+ this.activeConversationTitle = newTitle;
613
+ }
614
+ }
615
+
616
+ applyConversationDeletion(id: string) {
617
+ if (!id) {
618
+ return;
619
+ }
620
+
621
+ const wasActive = this.currentConversationId === id;
622
+ const next = this.conversations.filter((conversation) => conversation.id !== id);
623
+
624
+ if (next.length === this.conversations.length) {
625
+ return;
626
+ }
627
+
628
+ this.conversations = next;
629
+
630
+ if (wasActive) {
631
+ this.currentConversationId = null;
632
+ this.activeConversationTitle = null;
633
+ this.messages = [];
634
+ }
635
+ }
636
+
637
+ private restoreConversationSnapshot(snapshot: ConversationItem | undefined, index: number) {
638
+ if (!snapshot) {
639
+ return;
640
+ }
641
+
642
+ const exists = this.conversations.some((conversation) => conversation.id === snapshot.id);
643
+ if (exists) {
644
+ return;
645
+ }
646
+
647
+ const next = [...this.conversations];
648
+ const position = index >= 0 && index <= next.length ? index : next.length;
649
+ next.splice(position, 0, snapshot);
650
+ this.conversations = next;
651
+ }
652
+
653
+ async confirmDeleteConversation() {
654
+ const target = this.deleteConversationTarget;
655
+ if (!target) {
656
+ return;
657
+ }
658
+
659
+ const snapshot =
660
+ this.conversations[target.index] ??
661
+ this.conversations.find((item) => item.id === target.id) ?? {
662
+ id: target.id,
663
+ title: target.title,
664
+ updatedAt: new Date().toISOString(),
665
+ };
666
+ const isActive = this.currentConversationId === target.id;
667
+ this.pendingConversationAction = {
668
+ action: 'delete',
669
+ conversationId: target.id,
670
+ originalTitle: target.title,
671
+ index: target.index,
672
+ snapshot,
673
+ messagesSnapshot: isActive ? [...this.messages] : undefined,
674
+ wasActive: isActive,
675
+ };
676
+
677
+ const success = await this.dispatchConversationAction(
678
+ 'delete',
679
+ { id: target.id, title: target.title },
680
+ target.index,
681
+ );
682
+ if (success) {
683
+ this.deleteConversationTarget = null;
684
+ return;
685
+ }
686
+
687
+ this.pendingConversationAction = null;
688
+ }
689
+
690
+ cancelDeleteConversation() {
691
+ this.deleteConversationTarget = null;
692
+ }
693
+
694
+ handleRenameDraft(event: InputEvent) {
695
+ if (!this.renameConversationTarget) {
696
+ return;
697
+ }
698
+
699
+ this.renameConversationTarget = {
700
+ ...this.renameConversationTarget,
701
+ draft: (event.target as HTMLInputElement).value,
702
+ };
703
+ }
704
+
705
+ async confirmRenameConversation() {
706
+ const target = this.renameConversationTarget;
707
+ if (!target) {
708
+ return;
709
+ }
710
+
711
+ const newTitle = target.draft.trim();
712
+ if (!newTitle) {
713
+ return;
714
+ }
715
+
716
+ this.pendingConversationAction = {
717
+ action: 'rename',
718
+ conversationId: target.id,
719
+ originalTitle: target.title,
720
+ index: target.index,
721
+ newTitle,
722
+ };
723
+
724
+ const success = await this.dispatchConversationAction(
725
+ 'rename',
726
+ { id: target.id, title: newTitle },
727
+ target.index,
728
+ newTitle,
729
+ );
730
+ if (success) {
731
+ this.renameConversationTarget = null;
732
+ return;
733
+ }
734
+
735
+ this.pendingConversationAction = null;
736
+ }
737
+
738
+ cancelRenameConversation() {
739
+ this.renameConversationTarget = null;
740
+ }
741
+
742
+ cancelConversationActionError() {
743
+ this.conversationActionError = null;
744
+ this.pendingConversationAction = null;
745
+ }
746
+
747
+ async retryConversationAction() {
748
+ const errorState = this.conversationActionError;
749
+ if (!errorState) {
750
+ return;
751
+ }
752
+
753
+ const indexFromState =
754
+ typeof errorState.index === 'number' ? errorState.index : this.conversations.findIndex(
755
+ (item) => item.id === errorState.conversationId,
756
+ );
757
+ const safeIndex =
758
+ indexFromState >= 0
759
+ ? indexFromState
760
+ : this.conversations.length > 0
761
+ ? this.conversations.length - 1
762
+ : 0;
763
+
764
+ const snapshot =
765
+ errorState.snapshot ??
766
+ this.conversations.find((item) => item.id === errorState.conversationId) ?? {
767
+ id: errorState.conversationId,
768
+ title: errorState.originalTitle,
769
+ updatedAt: new Date().toISOString(),
770
+ };
771
+
772
+ this.pendingConversationAction = {
773
+ action: errorState.action,
774
+ conversationId: errorState.conversationId,
775
+ originalTitle: errorState.originalTitle,
776
+ index: safeIndex,
777
+ newTitle: errorState.newTitle,
778
+ snapshot,
779
+ messagesSnapshot: errorState.messagesSnapshot,
780
+ wasActive: errorState.wasActive,
781
+ };
782
+
783
+ this.conversationActionError = null;
784
+
785
+ await this.dispatchConversationAction(
786
+ errorState.action,
787
+ { id: errorState.conversationId, title: errorState.newTitle ?? errorState.originalTitle },
788
+ safeIndex,
789
+ errorState.newTitle,
790
+ );
791
+ }
792
+
793
+ private async dispatchConversationAction(
794
+ action: 'rename' | 'delete',
795
+ conversation: Pick<ConversationItem, 'id' | 'title'>,
796
+ index: number,
797
+ newTitle?: string,
798
+ ) {
799
+ const eventName =
800
+ action === 'rename' ? 'rioassist:conversation-rename' : 'rioassist:conversation-delete';
801
+ const detail = {
802
+ id: conversation.id,
803
+ title: conversation.title,
804
+ index,
805
+ action,
806
+ };
807
+
808
+ const allowed = this.dispatchEvent(
809
+ new CustomEvent(eventName, {
810
+ detail,
811
+ bubbles: true,
812
+ composed: true,
813
+ cancelable: true,
814
+ }),
815
+ );
816
+
817
+ if (!allowed) {
818
+ return false;
819
+ }
820
+
821
+ if (action === 'delete') {
822
+ const ok = await this.syncConversationDeleteBackend(conversation.id);
823
+ return ok;
824
+ }
825
+
826
+ if (action === 'rename' && newTitle) {
827
+ const ok = await this.syncConversationRenameBackend(conversation.id, newTitle);
828
+ return ok;
829
+ }
830
+
831
+ return false;
832
+ }
833
+
834
+ private async syncConversationRenameBackend(conversationId: string, newTitle: string) {
835
+ try {
836
+ const client = this.ensureRioClient();
837
+ console.info('[RioAssist][ws] enviando renameConversation', {
838
+ conversationId,
839
+ newTitle,
840
+ });
841
+ await client.renameConversation(conversationId, newTitle);
842
+ this.applyConversationRename(conversationId, newTitle);
843
+ this.conversationHistoryError = '';
844
+ return true;
845
+ } catch (error) {
846
+ console.error('[RioAssist][history] erro ao renomear conversa', error);
847
+ this.conversationHistoryError =
848
+ error instanceof Error && error.message
849
+ ? error.message
850
+ : 'Nao foi possivel renomear a conversa.';
851
+ return false;
852
+ }
853
+ }
854
+
855
+ private async syncConversationDeleteBackend(conversationId: string) {
856
+ try {
857
+ const client = this.ensureRioClient();
858
+ await client.deleteConversation(conversationId);
859
+ this.applyConversationDeletion(conversationId);
860
+ this.conversationHistoryError = '';
861
+ return true;
862
+ } catch (error) {
863
+ console.error('[RioAssist][history] erro ao excluir conversa', error);
864
+ this.conversationHistoryError =
865
+ error instanceof Error && error.message
866
+ ? error.message
867
+ : 'Nao foi possivel excluir a conversa.';
868
+ return false;
869
+ }
870
+ }
871
+
872
+ private handleConversationSystemAction(message: RioIncomingMessage) {
873
+ const action = (message.action ?? '').toLowerCase();
874
+ if (action === 'conversationrenamed') {
875
+ const data = message.data as Record<string, unknown>;
876
+ const id = this.repairConversationId(
877
+ this.extractString(data, ['conversationId', 'id']) ?? '',
878
+ );
879
+ const newTitle = this.extractString(data, ['newTitle', 'title']);
880
+ if (id && newTitle) {
881
+ this.applyConversationRename(id, newTitle);
882
+ this.conversationHistoryError = '';
883
+ if (
884
+ this.pendingConversationAction &&
885
+ this.pendingConversationAction.conversationId === id &&
886
+ this.pendingConversationAction.action === 'rename'
887
+ ) {
888
+ this.pendingConversationAction = null;
889
+ this.conversationActionError = null;
890
+ }
891
+ }
892
+ return true;
893
+ }
894
+
895
+ if (action === 'conversationdeleted') {
896
+ const data = message.data as Record<string, unknown>;
897
+ const id = this.repairConversationId(
898
+ this.extractString(data, ['conversationId', 'id']) ?? '',
899
+ );
900
+ if (id) {
901
+ this.applyConversationDeletion(id);
902
+ this.conversationHistoryError = '';
903
+ if (
904
+ this.pendingConversationAction &&
905
+ this.pendingConversationAction.conversationId === id &&
906
+ this.pendingConversationAction.action === 'delete'
907
+ ) {
908
+ this.pendingConversationAction = null;
909
+ this.conversationActionError = null;
910
+ }
911
+ }
912
+ return true;
913
+ }
914
+
915
+ if (action === 'processing') {
916
+ return true;
917
+ }
918
+
919
+ return false;
920
+ }
921
+
922
+ private handleConversationActionError(message: RioIncomingMessage) {
923
+ const action = (message.action ?? '').toLowerCase();
924
+ if (action !== 'error') {
925
+ return false;
926
+ }
927
+
928
+ const data = message.data as Record<string, unknown>;
929
+ console.error('[RioAssist][ws] erro em acao de conversa recebido do backend', {
930
+ text: message.text,
931
+ data,
932
+ raw: message.raw,
933
+ });
934
+ const errorText =
935
+ this.extractString(data, ['error', 'message', 'detail', 'description']) ||
936
+ (typeof message.text === 'string' && message.text.trim()
937
+ ? message.text
938
+ : 'O agente retornou um erro ao processar a conversa.');
939
+
940
+ const pending = this.pendingConversationAction;
941
+ if (pending) {
942
+ if (pending.action === 'rename') {
943
+ this.applyConversationRename(pending.conversationId, pending.originalTitle);
944
+ }
945
+
946
+ if (pending.action === 'delete') {
947
+ this.restoreConversationSnapshot(pending.snapshot, pending.index);
948
+ if (pending.wasActive) {
949
+ this.currentConversationId = pending.conversationId;
950
+ this.activeConversationTitle = pending.originalTitle;
951
+ this.messages = pending.messagesSnapshot ?? this.messages;
952
+ }
953
+ }
954
+
955
+ this.conversationActionError = {
956
+ ...pending,
957
+ message: errorText,
958
+ };
959
+ this.pendingConversationAction = null;
960
+ this.clearLoadingGuard();
961
+ this.isLoading = false;
962
+ return true;
963
+ }
964
+
965
+ this.errorMessage = errorText;
966
+ this.clearLoadingGuard();
967
+ this.isLoading = false;
968
+ return true;
969
+ }
970
+
971
+ private shouldIgnoreAssistantPayload(action?: string) {
972
+ if (!action) {
973
+ return false;
974
+ }
975
+ const normalized = action.toLowerCase();
976
+ return (
977
+ normalized === 'processing' ||
978
+ normalized === 'conversationrenamed' ||
979
+ normalized === 'conversationdeleted'
980
+ );
981
+ }
982
+
983
+ private extractString(
984
+ data: Record<string, unknown> | undefined,
985
+ keys: string[],
986
+ ): string | null {
987
+ if (!data || typeof data !== 'object') {
988
+ return null;
989
+ }
990
+ for (const key of keys) {
991
+ const value = data[key];
992
+ if (typeof value === 'string' && value.trim()) {
993
+ return value;
994
+ }
995
+ }
996
+ return null;
997
+ }
998
+
999
+ handleHeaderActionClick(action: HeaderActionConfig, index: number) {
1000
+ const detail = {
1001
+ index,
1002
+ id: action.id ?? null,
1003
+ ariaLabel: action.ariaLabel ?? null,
1004
+ iconUrl: action.iconUrl,
1005
+ };
1006
+
1007
+ const allowed = this.dispatchEvent(
1008
+ new CustomEvent('rioassist:header-action', {
1009
+ detail,
1010
+ bubbles: true,
1011
+ composed: true,
1012
+ cancelable: true,
1013
+ }),
1014
+ );
1015
+
1016
+ if (!allowed) {
1017
+ return;
1018
+ }
1019
+
1020
+ if (typeof action.onClick === 'function') {
1021
+ action.onClick();
1022
+ }
1023
+ }
1024
+
1025
+ handleCloseAction() {
1026
+ if (this.isFullscreen) {
1027
+ this.exitFullscreen(true);
1028
+ return;
1029
+ }
1030
+
1031
+ if (this.showConversations) {
1032
+ this.closeConversationsPanel();
1033
+ } else {
1034
+ this.closePanel();
1035
+ }
1036
+ }
1037
+
1038
+ enterFullscreen() {
1039
+ if (this.isFullscreen) {
1040
+ return;
1041
+ }
1042
+
1043
+ this.isFullscreen = true;
1044
+ this.open = false;
1045
+ this.showConversations = false;
1046
+ this.requestConversationHistory();
1047
+ }
1048
+
1049
+ exitFullscreen(restorePanel: boolean) {
1050
+ if (!this.isFullscreen) {
1051
+ return;
1052
+ }
1053
+
1054
+ this.isFullscreen = false;
1055
+ this.conversationMenuId = null;
1056
+ this.showNewConversationShortcut = false;
1057
+ if (restorePanel) {
1058
+ this.open = true;
1059
+ }
1060
+ }
1061
+
1062
+ handleCreateConversation() {
1063
+ if (!this.hasActiveConversation) {
1064
+ return;
1065
+ }
1066
+
1067
+ this.newConversationConfirmOpen = true;
1068
+ }
1069
+
1070
+ confirmCreateConversation() {
1071
+ if (!this.hasActiveConversation) {
1072
+ this.newConversationConfirmOpen = false;
1073
+ return;
1074
+ }
1075
+
1076
+ this.newConversationConfirmOpen = false;
1077
+
1078
+ this.startNewConversation();
1079
+ }
1080
+
1081
+ cancelCreateConversation() {
1082
+ this.newConversationConfirmOpen = false;
1083
+ }
1084
+
1085
+ private startNewConversation() {
1086
+ if (!this.hasActiveConversation) {
1087
+ return;
1088
+ }
1089
+
1090
+ this.clearLoadingGuard();
1091
+ this.isLoading = false;
1092
+ this.messages = [];
1093
+ this.message = '';
1094
+ this.errorMessage = '';
1095
+ this.showConversations = false;
1096
+ this.teardownRioClient();
1097
+ this.currentConversationId = null;
1098
+ this.activeConversationTitle = null;
1099
+ this.showNewConversationShortcut = false;
1100
+ this.dispatchEvent(
1101
+ new CustomEvent('rioassist:new-conversation', {
1102
+ bubbles: true,
1103
+ composed: true,
1104
+ }),
1105
+ );
1106
+ }
1107
+
1108
+ handleConversationListScroll(event: Event) {
1109
+ const target = event.currentTarget as HTMLElement | null;
1110
+ if (!target) {
1111
+ return;
1112
+ }
1113
+ this.updateConversationScrollbar(target);
1114
+ }
1115
+
1116
+ handleConversationScrollbarPointerDown(event: PointerEvent) {
1117
+ const track = event.currentTarget as HTMLElement | null;
1118
+ const list = this.renderRoot.querySelector(
1119
+ '.conversation-list--sidebar',
1120
+ ) as HTMLElement | null;
1121
+
1122
+ if (!track || !list) {
1123
+ return;
1124
+ }
1125
+
1126
+ const trackRect = track.getBoundingClientRect();
1127
+ const thumbHeight = trackRect.height * (this.conversationScrollbar.height / 100);
1128
+ const maxThumbTop = Math.max(trackRect.height - thumbHeight, 0);
1129
+ const scrollRange = Math.max(list.scrollHeight - list.clientHeight, 1);
1130
+ const currentThumbTop = (list.scrollTop / scrollRange) * maxThumbTop;
1131
+ const offsetY = event.clientY - trackRect.top;
1132
+ const isOnThumb = offsetY >= currentThumbTop && offsetY <= currentThumbTop + thumbHeight;
1133
+
1134
+ const nextThumbTop = isOnThumb
1135
+ ? currentThumbTop
1136
+ : Math.min(Math.max(offsetY - thumbHeight / 2, 0), maxThumbTop);
1137
+
1138
+ if (!isOnThumb) {
1139
+ list.scrollTop = (nextThumbTop / Math.max(maxThumbTop, 1)) * (list.scrollHeight - list.clientHeight);
1140
+ this.updateConversationScrollbar(list);
1141
+ }
1142
+
1143
+ track.setPointerCapture(event.pointerId);
1144
+ this.conversationScrollbarDraggingId = event.pointerId;
1145
+ this.conversationScrollbarDragState = {
1146
+ startY: event.clientY,
1147
+ startThumbTop: nextThumbTop,
1148
+ trackHeight: trackRect.height,
1149
+ thumbHeight,
1150
+ list,
1151
+ };
1152
+ event.preventDefault();
1153
+ }
1154
+
1155
+ handleConversationScrollbarPointerMove(event: PointerEvent) {
1156
+ if (
1157
+ this.conversationScrollbarDraggingId === null ||
1158
+ this.conversationScrollbarDraggingId !== event.pointerId ||
1159
+ !this.conversationScrollbarDragState
1160
+ ) {
1161
+ return;
1162
+ }
1163
+
1164
+ const {
1165
+ startY,
1166
+ startThumbTop,
1167
+ trackHeight,
1168
+ thumbHeight,
1169
+ list,
1170
+ } = this.conversationScrollbarDragState;
1171
+
1172
+ const maxThumbTop = Math.max(trackHeight - thumbHeight, 0);
1173
+ const deltaY = event.clientY - startY;
1174
+ const thumbTop = Math.min(Math.max(startThumbTop + deltaY, 0), maxThumbTop);
1175
+ const scrollRange = list.scrollHeight - list.clientHeight;
1176
+
1177
+ if (scrollRange > 0) {
1178
+ list.scrollTop = (thumbTop / Math.max(maxThumbTop, 1)) * scrollRange;
1179
+ this.updateConversationScrollbar(list);
1180
+ }
1181
+
1182
+ event.preventDefault();
1183
+ }
1184
+
1185
+ handleConversationScrollbarPointerUp(event: PointerEvent) {
1186
+ if (this.conversationScrollbarDraggingId !== event.pointerId) {
1187
+ return;
1188
+ }
1189
+
1190
+ const track = event.currentTarget as HTMLElement | null;
1191
+ track?.releasePointerCapture(event.pointerId);
1192
+
1193
+ this.conversationScrollbarDraggingId = null;
1194
+ this.conversationScrollbarDragState = null;
1195
+ }
1196
+
1197
+ private enqueueConversationScrollbarMeasure() {
1198
+ if (this.conversationScrollbarRaf !== null) {
1199
+ return;
1200
+ }
1201
+
1202
+ this.conversationScrollbarRaf = requestAnimationFrame(() => {
1203
+ this.conversationScrollbarRaf = null;
1204
+ this.updateConversationScrollbar();
1205
+ });
1206
+ }
1207
+
1208
+ private updateConversationScrollbar(target?: HTMLElement | null) {
1209
+ const element =
1210
+ target ??
1211
+ (this.renderRoot.querySelector(
1212
+ '.conversation-list--sidebar',
1213
+ ) as HTMLElement | null);
1214
+
1215
+ if (!element) {
1216
+ if (this.conversationScrollbar.visible) {
1217
+ this.conversationScrollbar = { height: 0, top: 0, visible: false };
1218
+ }
1219
+ return;
1220
+ }
1221
+
1222
+ const { scrollHeight, clientHeight, scrollTop } = element;
1223
+ if (scrollHeight <= clientHeight + 1) {
1224
+ if (this.conversationScrollbar.visible) {
1225
+ this.conversationScrollbar = { height: 0, top: 0, visible: false };
1226
+ }
1227
+ return;
1228
+ }
1229
+
1230
+ const ratio = clientHeight / scrollHeight;
1231
+ const height = Math.max(ratio * 100, 8);
1232
+ const maxTop = 100 - height;
1233
+ const top =
1234
+ scrollTop / (scrollHeight - clientHeight) * (maxTop > 0 ? maxTop : 0);
1235
+
1236
+ this.conversationScrollbar = {
1237
+ height,
1238
+ top,
1239
+ visible: true,
1240
+ };
1241
+ }
1242
+
1243
+ async onSuggestionClick(suggestion: string) {
1244
+ await this.processMessage(suggestion);
1245
+ }
1246
+
1247
+ async handleSubmit(event: SubmitEvent) {
1248
+ event.preventDefault();
1249
+ await this.processMessage(this.message);
1250
+ }
1251
+
1252
+ private createMessage(role: ChatRole, text: string): ChatMessage {
1253
+ const id = typeof crypto !== 'undefined' && 'randomUUID' in crypto
1254
+ ? crypto.randomUUID()
1255
+ : `${Date.now()}-${Math.random()}`;
1256
+
1257
+ return {
1258
+ id,
1259
+ role,
1260
+ text,
1261
+ html: this.renderMarkdown(text),
1262
+ timestamp: Date.now(),
1263
+ };
1264
+ }
1265
+
1266
+ private async processMessage(rawValue: string) {
1267
+ const content = rawValue.trim();
1268
+ if (!content || this.isLoading) {
1269
+ return;
1270
+ }
1271
+
1272
+ const contentToSend = this.shortAnswerEnabled
1273
+ ? `Quero uma resposta curta sobre: ${content}`
1274
+ : content;
1275
+ const contentToDisplay = content;
1276
+
1277
+ if (!this.currentConversationId) {
1278
+ this.currentConversationId = null;
1279
+ this.activeConversationTitle = null;
1280
+ }
1281
+
1282
+ const wasEmptyConversation = this.messages.length === 0;
1283
+
1284
+ this.dispatchEvent(
1285
+ new CustomEvent('rioassist:send', {
1286
+ detail: {
1287
+ message: content,
1288
+ apiBaseUrl: this.apiBaseUrl,
1289
+ token: this.rioToken,
1290
+ },
1291
+ bubbles: true,
1292
+ composed: true,
1293
+ }),
1294
+ );
1295
+
1296
+ const userMessage = this.createMessage('user', contentToDisplay);
1297
+ this.messages = [...this.messages, userMessage];
1298
+ if (wasEmptyConversation) {
1299
+ this.showNewConversationShortcut = true;
1300
+ this.refreshConversationsAfterResponse = true;
1301
+ }
1302
+ this.message = '';
1303
+ this.errorMessage = '';
1304
+ this.isLoading = true;
1305
+ this.startLoadingGuard();
1306
+
1307
+ try {
1308
+ const client = this.ensureRioClient();
1309
+ await client.sendMessage(contentToSend, this.currentConversationId);
1310
+ } catch (error) {
1311
+ this.clearLoadingGuard();
1312
+ this.isLoading = false;
1313
+ this.errorMessage = error instanceof Error
1314
+ ? error.message
1315
+ : 'Nao foi possivel enviar a mensagem para o agente.';
1316
+ }
1317
+ }
1318
+
1319
+ private ensureRioClient() {
1320
+ const token = this.rioToken.trim();
1321
+ if (!token) {
1322
+ throw new Error(
1323
+ 'Informe o token RIO em data-rio-token para conectar no websocket do assistente.',
1324
+ );
1325
+ }
1326
+
1327
+ if (!this.rioClient || !this.rioClient.matchesToken(token)) {
1328
+ this.teardownRioClient();
1329
+ this.rioClient = new RioWebsocketClient(token);
1330
+ this.rioUnsubscribe = this.rioClient.onMessage((incoming) => {
1331
+ this.handleIncomingMessage(incoming);
1332
+ });
1333
+ }
1334
+
1335
+ return this.rioClient;
1336
+ }
1337
+
1338
+ private handleIncomingMessage(message: RioIncomingMessage) {
1339
+ if (this.isHistoryPayload(message)) {
1340
+ this.logHistoryPayload(message);
1341
+ this.handleHistoryPayload(message.data);
1342
+ return;
1343
+ }
1344
+
1345
+ if (this.handleConversationSystemAction(message)) {
1346
+ return;
1347
+ }
1348
+
1349
+ if (this.handleConversationActionError(message)) {
1350
+ return;
1351
+ }
1352
+
1353
+ if (this.shouldIgnoreAssistantPayload(message.action)) {
1354
+ return;
1355
+ }
1356
+
1357
+ const incomingConversationId = this.extractConversationId(message.data);
1358
+ if (incomingConversationId) {
1359
+ this.currentConversationId = incomingConversationId;
1360
+ this.syncActiveConversationTitle();
1361
+ }
1362
+
1363
+ console.info('[RioAssist][ws] resposta de mensagem recebida', {
1364
+ action: message.action ?? 'message',
1365
+ text: message.text,
1366
+ raw: message.raw,
1367
+ data: message.data,
1368
+ });
1369
+
1370
+ // Handle "processing" type messages - just keep loading state, don't create message
1371
+ if (message.action === 'processing') {
1372
+ console.info('[RioAssist][ws] processando mensagem - aguardando resposta final');
1373
+ // Keep isLoading = true, don't create a message balloon
1374
+ return;
1375
+ }
1376
+
1377
+ const assistantMessage = this.createMessage('assistant', message.text);
1378
+ this.messages = [...this.messages, assistantMessage];
1379
+ this.clearLoadingGuard();
1380
+ this.isLoading = false;
1381
+
1382
+ if (this.refreshConversationsAfterResponse) {
1383
+ this.refreshConversationsAfterResponse = false;
1384
+ this.requestConversationHistory();
1385
+ }
1386
+ }
1387
+
1388
+ private teardownRioClient() {
1389
+ if (this.rioUnsubscribe) {
1390
+ this.rioUnsubscribe();
1391
+ this.rioUnsubscribe = null;
1392
+ }
1393
+
1394
+ if (this.rioClient) {
1395
+ this.rioClient.close();
1396
+ this.rioClient = null;
1397
+ }
1398
+ }
1399
+
1400
+ async requestConversationHistory(conversationId?: string) {
1401
+ try {
1402
+ const client = this.ensureRioClient();
1403
+ const limit = 50;
1404
+
1405
+ console.info('[RioAssist][history] solicitando historico de conversas', {
1406
+ conversationId: conversationId ?? null,
1407
+ limit,
1408
+ });
1409
+
1410
+ this.conversationHistoryError = '';
1411
+ this.conversationHistoryLoading = true;
1412
+ await client.requestHistory({ conversationId, limit });
1413
+ } catch (error) {
1414
+ console.error('[RioAssist][history] erro ao solicitar historico', error);
1415
+ this.conversationHistoryError =
1416
+ error instanceof Error && error.message
1417
+ ? error.message
1418
+ : 'Nao foi possivel carregar as conversas.';
1419
+ this.conversationHistoryLoading = false;
1420
+ }
1421
+ }
1422
+
1423
+ private handleHistoryPayload(payload: unknown) {
1424
+ const entries = this.extractHistoryEntries(payload);
1425
+ const conversationId = this.extractConversationId(payload);
1426
+
1427
+ if (conversationId !== null && conversationId !== undefined) {
1428
+ this.applyMessageHistory(entries, conversationId);
1429
+ return;
1430
+ }
1431
+
1432
+ if (this.isMessageHistoryEntries(entries)) {
1433
+ this.applyMessageHistory(entries);
1434
+ return;
1435
+ }
1436
+
1437
+ this.applyConversationHistoryFromEntries(entries);
1438
+
1439
+ if (this.refreshConversationsAfterResponse) {
1440
+ this.refreshConversationsAfterResponse = false;
1441
+ }
1442
+ }
1443
+
1444
+ private isHistoryPayload(message: RioIncomingMessage) {
1445
+ if (
1446
+ typeof message.action === 'string' &&
1447
+ message.action.toLowerCase().includes('history')
1448
+ ) {
1449
+ return true;
1450
+ }
1451
+
1452
+ const data = message.data;
1453
+ if (data && typeof data === 'object') {
1454
+ const action = (data as any).action;
1455
+ if (typeof action === 'string' && action.toLowerCase().includes('history')) {
1456
+ return true;
1457
+ }
1458
+
1459
+ if (Array.isArray((data as any).history) || Array.isArray((data as any).conversations)) {
1460
+ return true;
1461
+ }
1462
+ }
1463
+
1464
+ return false;
1465
+ }
1466
+
1467
+ private logHistoryPayload(message: RioIncomingMessage) {
1468
+ const label = '[RioAssist][history] payload recebido do websocket';
1469
+ if (message.data !== null && message.data !== undefined) {
1470
+ console.info(label, message.data);
1471
+ return;
1472
+ }
1473
+
1474
+ console.info(label, message.raw);
1475
+ }
1476
+
1477
+ private applyConversationHistoryFromEntries(entries: unknown[]) {
1478
+ if (entries.length === 0) {
1479
+ console.info('[RioAssist][history] payload sem itens para montar lista de conversas');
1480
+ this.conversations = [];
1481
+ this.conversationHistoryLoading = false;
1482
+ this.conversationHistoryError = '';
1483
+ return;
1484
+ }
1485
+
1486
+ const map = new Map<string, ConversationItem>();
1487
+
1488
+ entries.forEach((entry, index) => {
1489
+ if (!entry || typeof entry !== 'object') {
1490
+ return;
1491
+ }
1492
+
1493
+ const normalized = this.normalizeConversationItem(
1494
+ entry as Record<string, unknown>,
1495
+ index,
1496
+ );
1497
+
1498
+ const rawId =
1499
+ (entry as Record<string, unknown>).conversationId ??
1500
+ (entry as Record<string, unknown>).conversationUUID ??
1501
+ (entry as Record<string, unknown>).conversationUuid ??
1502
+ (entry as Record<string, unknown>).uuid ??
1503
+ (entry as Record<string, unknown>).id;
1504
+ if (rawId) {
1505
+ console.info('[RioAssist][history] conversa recebida do backend', {
1506
+ rawId,
1507
+ normalizedId: normalized?.id ?? null,
1508
+ entry,
1509
+ });
1510
+ }
1511
+
1512
+ if (!normalized) {
1513
+ return;
1514
+ }
1515
+
1516
+ const current = map.get(normalized.id);
1517
+ if (!current) {
1518
+ map.set(normalized.id, normalized);
1519
+ return;
1520
+ }
1521
+
1522
+ const currentTime = Date.parse(current.updatedAt);
1523
+ const nextTime = Date.parse(normalized.updatedAt);
1524
+
1525
+ if (Number.isFinite(nextTime) && nextTime > currentTime) {
1526
+ map.set(normalized.id, normalized);
1527
+ }
1528
+ });
1529
+
1530
+ const conversations = Array.from(map.values()).sort((a, b) => {
1531
+ const order = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
1532
+ return Number.isFinite(order) ? order : 0;
1533
+ });
1534
+
1535
+ this.conversations = conversations;
1536
+ this.conversationHistoryLoading = false;
1537
+ this.conversationHistoryError = '';
1538
+ this.syncActiveConversationTitle();
1539
+ console.info('[RioAssist][history] conversas normalizadas', conversations);
1540
+ }
1541
+
1542
+ private applyMessageHistory(entries: unknown[], conversationId?: string | null) {
1543
+ if (entries.length === 0) {
1544
+ console.info('[RioAssist][history] lista de mensagens vazia', { conversationId });
1545
+ this.messages = [];
1546
+ this.showConversations = false;
1547
+ this.clearLoadingGuard();
1548
+ this.isLoading = false;
1549
+ this.conversationHistoryLoading = false;
1550
+ return;
1551
+ }
1552
+
1553
+ const normalized = entries.flatMap((entry, index) =>
1554
+ this.normalizeHistoryMessages(entry as Record<string, unknown>, index),
1555
+ );
1556
+
1557
+ if (conversationId) {
1558
+ this.currentConversationId = conversationId;
1559
+ }
1560
+
1561
+ this.messages = normalized;
1562
+ this.showConversations = false;
1563
+ this.clearLoadingGuard();
1564
+ this.isLoading = false;
1565
+ this.showNewConversationShortcut = normalized.length > 0;
1566
+ this.conversationHistoryLoading = false;
1567
+ this.refreshConversationsAfterResponse = false;
1568
+
1569
+ console.info('[RioAssist][history] mensagens carregadas', {
1570
+ conversationId: conversationId ?? null,
1571
+ total: normalized.length,
1572
+ });
1573
+ }
1574
+
1575
+ private extractHistoryEntries(payload: unknown): unknown[] {
1576
+ if (Array.isArray(payload)) {
1577
+ return payload;
1578
+ }
1579
+
1580
+ if (payload && typeof payload === 'object') {
1581
+ const record = payload as Record<string, unknown>;
1582
+ const candidates = [
1583
+ record.history,
1584
+ record.conversations,
1585
+ record.data,
1586
+ record.items,
1587
+ record.messages,
1588
+ ];
1589
+
1590
+ for (const candidate of candidates) {
1591
+ if (Array.isArray(candidate)) {
1592
+ return candidate;
1593
+ }
1594
+ }
1595
+
1596
+ if (record.data && typeof record.data === 'object' && !Array.isArray(record.data)) {
1597
+ const nested = this.extractHistoryEntries(record.data);
1598
+ if (nested.length > 0) {
1599
+ return nested;
1600
+ }
1601
+ }
1602
+ }
1603
+
1604
+ return [];
1605
+ }
1606
+
1607
+ private extractConversationId(payload: unknown): string | null | undefined {
1608
+ if (payload && typeof payload === 'object') {
1609
+ const record = payload as Record<string, unknown>;
1610
+ const candidates = [
1611
+ record.conversationId,
1612
+ record.conversationUUID,
1613
+ record.conversationUuid,
1614
+ record.uuid,
1615
+ record.id,
1616
+ ];
1617
+
1618
+ for (const candidate of candidates) {
1619
+ if (candidate === null) {
1620
+ return null;
1621
+ }
1622
+
1623
+ if (candidate !== undefined) {
1624
+ return this.repairConversationId(String(candidate));
1625
+ }
1626
+ }
1627
+ }
1628
+
1629
+ return undefined;
1630
+ }
1631
+
1632
+ private isMessageHistoryEntries(entries: unknown[]) {
1633
+ return entries.some((entry) => this.looksLikeMessageHistoryEntry(entry));
1634
+ }
1635
+
1636
+ private looksLikeMessageHistoryEntry(entry: unknown) {
1637
+ if (!entry || typeof entry !== 'object') {
1638
+ return false;
1639
+ }
1640
+
1641
+ const item = entry as Record<string, unknown>;
1642
+ const role = item.role ?? item.sender ?? item.from ?? item.author ?? item.type;
1643
+ if (typeof role === 'string' && role.trim().length > 0) {
1644
+ return true;
1645
+ }
1646
+
1647
+ if (
1648
+ typeof item.content === 'string' ||
1649
+ typeof item.message === 'string' ||
1650
+ typeof item.text === 'string' ||
1651
+ typeof item.response === 'string'
1652
+ ) {
1653
+ return true;
1654
+ }
1655
+
1656
+ if (Array.isArray(item.parts) && item.parts.length > 0) {
1657
+ return true;
1658
+ }
1659
+
1660
+ return false;
1661
+ }
1662
+
1663
+ private normalizeConversationItem(
1664
+ value: Record<string, unknown>,
1665
+ index: number,
1666
+ ): ConversationItem | null {
1667
+ const rawId =
1668
+ value.conversationId ??
1669
+ value.conversationUUID ??
1670
+ value.conversationUuid ??
1671
+ value.uuid ??
1672
+ value.id;
1673
+
1674
+ const idRaw = rawId !== undefined && rawId !== null ? String(rawId) : `history-${index + 1}`;
1675
+ const id = this.repairConversationId(idRaw);
1676
+
1677
+ const rawTitle =
1678
+ value.title ??
1679
+ value.name ??
1680
+ value.topic ??
1681
+ value.subject ??
1682
+ value.question ??
1683
+ value.query ??
1684
+ value.message;
1685
+
1686
+ const title =
1687
+ typeof rawTitle === 'string' && rawTitle.trim().length > 0
1688
+ ? rawTitle.trim()
1689
+ : `Conversa ${index + 1}`;
1690
+
1691
+ const rawUpdated =
1692
+ value.updatedAt ??
1693
+ value.updated_at ??
1694
+ value.lastMessageAt ??
1695
+ value.last_message_at ??
1696
+ value.createdAt ??
1697
+ value.created_at ??
1698
+ value.timestamp ??
1699
+ value.date;
1700
+
1701
+ const updatedAt = this.toIsoString(rawUpdated);
1702
+
1703
+ return { id, title, updatedAt };
1704
+ }
1705
+
1706
+ private normalizeHistoryMessages(
1707
+ value: Record<string, unknown>,
1708
+ index: number,
1709
+ ): ChatMessage[] {
1710
+ const messages: ChatMessage[] = [];
1711
+
1712
+ const rawUserText = value.message ?? value.question ?? value.query ?? value.text ?? value.content;
1713
+ const userText = typeof rawUserText === 'string' ? rawUserText.trim() : '';
1714
+
1715
+ const rawResponseText =
1716
+ value.response ?? value.answer ?? value.reply ?? value.completion ?? value.body ?? value.preview;
1717
+ const responseText = typeof rawResponseText === 'string' ? rawResponseText.trim() : '';
1718
+
1719
+ const rawId = value.id ?? value.messageId ?? value.uuid ?? value.conversationMessageId;
1720
+ const baseId = rawId !== undefined && rawId !== null
1721
+ ? String(rawId)
1722
+ : `history-${index + 1}`;
1723
+
1724
+ const userTimestampValue =
1725
+ value.timestamp ??
1726
+ value.createdAt ??
1727
+ value.created_at ??
1728
+ value.date ??
1729
+ value.time;
1730
+ const assistantTimestampValue =
1731
+ value.responseTimestamp ??
1732
+ value.responseTime ??
1733
+ value.responseDate ??
1734
+ value.response_at ??
1735
+ value.updatedAt ??
1736
+ value.updated_at;
1737
+
1738
+ const userTimestamp = this.parseTimestamp(userTimestampValue);
1739
+ const assistantTimestamp = this.parseTimestamp(
1740
+ assistantTimestampValue,
1741
+ userTimestamp + 1,
1742
+ );
1743
+
1744
+ if (responseText) {
1745
+ if (userText) {
1746
+ messages.push({
1747
+ id: `${baseId}-user`,
1748
+ role: 'user',
1749
+ text: userText,
1750
+ html: this.renderMarkdown(userText),
1751
+ timestamp: userTimestamp,
1752
+ });
1753
+ }
1754
+
1755
+ messages.push({
1756
+ id: `${baseId}-assistant`,
1757
+ role: 'assistant',
1758
+ text: responseText,
1759
+ html: this.renderMarkdown(responseText),
1760
+ timestamp: assistantTimestamp,
1761
+ });
1762
+ } else if (userText) {
1763
+ // Se n�o tiver resposta, n�o exibimos a mensagem do usuario isolada.
1764
+ return [];
1765
+ }
1766
+
1767
+ if (messages.length > 0) {
1768
+ return messages;
1769
+ }
1770
+
1771
+ const fallback = this.normalizeSingleHistoryMessage(value, index);
1772
+ return fallback ? [fallback] : [];
1773
+ }
1774
+
1775
+ private normalizeSingleHistoryMessage(
1776
+ value: Record<string, unknown>,
1777
+ index: number,
1778
+ ): ChatMessage | null {
1779
+ const rawText =
1780
+ value.text ??
1781
+ value.message ??
1782
+ value.content ??
1783
+ value.response ??
1784
+ value.body ??
1785
+ value.preview;
1786
+
1787
+ const text = typeof rawText === 'string' && rawText.trim().length > 0
1788
+ ? rawText
1789
+ : '';
1790
+
1791
+ if (!text) {
1792
+ return null;
1793
+ }
1794
+
1795
+ const role = this.normalizeRole(
1796
+ value.role ??
1797
+ value.sender ??
1798
+ value.from ??
1799
+ value.author ??
1800
+ value.type ??
1801
+ value.direction,
1802
+ );
1803
+
1804
+ const rawId = value.id ?? value.messageId ?? value.uuid ?? value.conversationMessageId;
1805
+ const id = rawId !== undefined && rawId !== null
1806
+ ? String(rawId)
1807
+ : `history-message-${index + 1}`;
1808
+
1809
+ const timestampValue =
1810
+ value.timestamp ??
1811
+ value.createdAt ??
1812
+ value.created_at ??
1813
+ value.updatedAt ??
1814
+ value.updated_at ??
1815
+ value.date ??
1816
+ value.time;
1817
+
1818
+ const timestamp = this.parseTimestamp(timestampValue);
1819
+
1820
+ return {
1821
+ id,
1822
+ role,
1823
+ text,
1824
+ html: this.renderMarkdown(text),
1825
+ timestamp,
1826
+ };
1827
+ }
1828
+
1829
+ private normalizeRole(value: unknown): ChatRole {
1830
+ if (typeof value === 'string') {
1831
+ const normalized = value.toLowerCase();
1832
+ if (normalized.includes('user') || normalized.includes('client')) {
1833
+ return 'user';
1834
+ }
1835
+ if (normalized.includes('assistant') || normalized.includes('agent') || normalized.includes('bot')) {
1836
+ return 'assistant';
1837
+ }
1838
+ }
1839
+
1840
+ return 'assistant';
1841
+ }
1842
+
1843
+ private parseTimestamp(value: unknown, fallback?: number) {
1844
+ const parsed = Date.parse(this.toIsoString(value));
1845
+ if (Number.isFinite(parsed)) {
1846
+ return parsed;
1847
+ }
1848
+
1849
+ if (Number.isFinite(fallback ?? NaN)) {
1850
+ return fallback as number;
1851
+ }
1852
+
1853
+ return Date.now();
1854
+ }
1855
+
1856
+ private lookupConversationTitle(conversationId: string | null) {
1857
+ if (!conversationId) {
1858
+ return null;
1859
+ }
1860
+
1861
+ const found = this.conversations.find((item) => item.id === conversationId);
1862
+ return found ? found.title : null;
1863
+ }
1864
+
1865
+ private syncActiveConversationTitle() {
1866
+ if (!this.currentConversationId) {
1867
+ return;
1868
+ }
1869
+
1870
+ const title = this.lookupConversationTitle(this.currentConversationId);
1871
+ if (title) {
1872
+ this.activeConversationTitle = title;
1873
+ }
1874
+ }
1875
+
1876
+ private toIsoString(value: unknown) {
1877
+ if (typeof value === 'string' || typeof value === 'number') {
1878
+ const date = new Date(value);
1879
+ if (!Number.isNaN(date.getTime())) {
1880
+ return date.toISOString();
1881
+ }
1882
+ }
1883
+
1884
+ return new Date().toISOString();
1885
+ }
1886
+
1887
+ private startLoadingGuard() {
1888
+ this.clearLoadingGuard();
1889
+ this.loadingLabelInternal = 'RIO Insight está respondendo';
1890
+
1891
+ // Após 20s, mensagem de processamento prolongado.
1892
+ this.loadingTimerSlow = window.setTimeout(() => {
1893
+ this.loadingLabelInternal = 'RIO Insight continua respondendo';
1894
+ this.requestUpdate();
1895
+ }, 20000);
1896
+
1897
+ // Após 60s, aviso de demora maior.
1898
+ this.loadingTimerTimeout = window.setTimeout(() => {
1899
+ this.loadingLabelInternal =
1900
+ 'RIO Insight ainda está processando sua resposta. Peço que aguarde um pouco mais';
1901
+ this.requestUpdate();
1902
+ }, 60000);
1903
+
1904
+ // Após 120s, novo aviso de demora maior.
1905
+ this.loadingTimerTimeout = window.setTimeout(() => {
1906
+ this.loadingLabelInternal =
1907
+ 'Essa solicitação está demorando um pouco mais que o esperado. Pode favor, aguarde mais um pouco';
1908
+ this.requestUpdate();
1909
+ }, 120000);
1910
+ }
1911
+
1912
+ private clearLoadingGuard() {
1913
+ if (this.loadingTimer !== null) {
1914
+ window.clearTimeout(this.loadingTimer);
1915
+ this.loadingTimer = null;
1916
+ }
1917
+
1918
+ if (this.loadingTimerSlow !== null) {
1919
+ window.clearTimeout(this.loadingTimerSlow);
1920
+ this.loadingTimerSlow = null;
1921
+ }
1922
+
1923
+ if (this.loadingTimerTimeout !== null) {
1924
+ window.clearTimeout(this.loadingTimerTimeout);
1925
+ this.loadingTimerTimeout = null;
1926
+ }
1927
+ }
1928
+
1929
+ private scrollConversationToBottom() {
1930
+ const containers = Array.from(
1931
+ this.renderRoot.querySelectorAll('.panel-content'),
1932
+ ) as HTMLElement[];
1933
+
1934
+ containers.forEach((container) => {
1935
+ requestAnimationFrame(() => {
1936
+ container.scrollTop = container.scrollHeight;
1937
+ });
1938
+ });
1939
+ }
1940
+
1941
+ private renderMarkdown(content: string) {
1942
+ const rendered = this.markdownRenderer.render(content);
1943
+ const clean = DOMPurify.sanitize(rendered, {
1944
+ ALLOWED_TAGS: [
1945
+ 'a',
1946
+ 'p',
1947
+ 'ul',
1948
+ 'ol',
1949
+ 'li',
1950
+ 'code',
1951
+ 'pre',
1952
+ 'strong',
1953
+ 'em',
1954
+ 'blockquote',
1955
+ 'table',
1956
+ 'thead',
1957
+ 'tbody',
1958
+ 'tr',
1959
+ 'th',
1960
+ 'td',
1961
+ 'del',
1962
+ 'hr',
1963
+ 'br',
1964
+ 'img',
1965
+ 'span',
1966
+ 'input',
1967
+ ],
1968
+ ALLOWED_ATTR: [
1969
+ 'href',
1970
+ 'title',
1971
+ 'target',
1972
+ 'rel',
1973
+ 'src',
1974
+ 'alt',
1975
+ 'class',
1976
+ 'type',
1977
+ 'checked',
1978
+ 'disabled',
1979
+ 'aria-label',
1980
+ ],
1981
+ ALLOW_DATA_ATTR: false,
1982
+ FORBID_TAGS: ['style', 'script'],
1983
+ USE_PROFILES: { html: true },
1984
+ });
1985
+
1986
+ const container = document.createElement('div');
1987
+ container.innerHTML = clean;
1988
+
1989
+ container.querySelectorAll('a').forEach((anchor) => {
1990
+ anchor.setAttribute('target', '_blank');
1991
+ anchor.setAttribute('rel', 'noopener noreferrer');
1992
+ });
1993
+
1994
+ container.querySelectorAll('input[type="checkbox"]').forEach((checkbox) => {
1995
+ checkbox.setAttribute('disabled', '');
1996
+ checkbox.setAttribute('tabindex', '-1');
1997
+ });
1998
+
1999
+ return container.innerHTML;
2000
+ }
2001
+
2002
+ render() {
2003
+ return renderRioAssist(this);
2004
+ }
2005
+
2006
+ }
2007
+ declare global {
2008
+ interface HTMLElementTagNameMap {
2009
+ 'rio-assist-widget': RioAssistWidget;
2010
+ }
2011
+ }
2012
+
2013
+ if (!customElements.get('rio-assist-widget')) {
2014
+ customElements.define('rio-assist-widget', RioAssistWidget);
2015
+ }