@channelhub/widget 0.1.8 → 0.1.9

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,9 +1,9 @@
1
1
  import { Component, FormEvent, createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
2
2
  import type { ReactNode } from 'react';
3
3
  import { createPortal } from 'react-dom';
4
- import { AlertCircle, Check, CheckCheck, ChevronDown, ChevronRight, Image, Inbox, Info, Loader2, MoreHorizontal, Paperclip, Play, Search, Send, SlidersHorizontal, Smile, X, Zap } from 'lucide-react';
4
+ import { AlertCircle, Check, CheckCheck, ChevronDown, ChevronRight, Image, Inbox, Info, Loader2, MoreHorizontal, Paperclip, Play, Search, Send, SlidersHorizontal, Smile, UserCheck, UserPlus, X, Zap } from 'lucide-react';
5
5
  import { ChannelHubClient } from './api.js';
6
- import type { ChannelHubInboxHandle, Connection, Conversation, ContactInfoRow, Extension, ExtensionContact, ExtensionContext, Message, MessageAttachment, Page, Provider, WidgetProps } from './types.js';
6
+ import type { ChannelHubAgent, ChannelHubInboxHandle, Connection, Conversation, ContactInfoRow, Extension, ExtensionContact, ExtensionContext, Message, MessageAttachment, Page, Provider, WidgetProps } from './types.js';
7
7
 
8
8
  type WidgetTranslations = { today: string; loadOlder: string; loading: string; noMessages: string; searchPlaceholder: string; unreadOnly: string; sendPlaceholder: string; send: string; all: string };
9
9
  import { Avatar as UiAvatar, Button, Input, ScrollArea, Textarea } from './components/ui/index.js';
@@ -121,15 +121,24 @@ function StatusIcon({ status }: { status?: Message['status'] }) {
121
121
  }
122
122
 
123
123
  type ActiveFilters = { provider: Provider | 'all'; unreadOnly: boolean };
124
+ type AssignmentScope = 'all' | 'mine' | 'unassigned';
125
+
126
+ function shortAgentName(name: string): string {
127
+ const parts = name.trim().split(/\s+/).filter(Boolean);
128
+ if (parts.length <= 2) return name.trim();
129
+ return parts.slice(-2).join(' ');
130
+ }
124
131
 
125
132
  export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(function ChannelHubInbox(
126
- { apiUrl, token, theme, height, defaultConversationId, disableAttachments, disableNotificationSound, hideKeyboardHint, locale = 'vi', extensions, onNewMessage, onConversationSelect },
133
+ { apiUrl, token, theme, height, defaultConversationId, disableAttachments, disableNotificationSound, hideKeyboardHint, locale = 'vi', extensions, currentAgent, teamAgents, onNewMessage, onConversationSelect },
127
134
  ref
128
135
  ) {
129
136
  const client = useRef(new ChannelHubClient(apiUrl, token));
130
137
  const [items, setItems] = useState<Conversation[]>([]); const [connections, setConnections] = useState<Connection[]>([]); const [cursor, setCursor] = useState<string>();
131
138
  const [selected, setSelected] = useState<Conversation>(); const selectedId = useRef<string | undefined>(undefined);
132
139
  const [query, setQuery] = useState('');
140
+ const [assignmentScope, setAssignmentScope] = useState<AssignmentScope>('all');
141
+ const [sessionAgent, setSessionAgent] = useState<ChannelHubAgent | null>(null);
133
142
  const [activeFilters, setActiveFilters] = useState<ActiveFilters>({ provider: 'all', unreadOnly: false });
134
143
  const [filterOpen, setFilterOpen] = useState(false);
135
144
  const filterBtnRef = useRef<HTMLButtonElement>(null);
@@ -145,6 +154,45 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
145
154
  const appendMessageRef = useRef<((msg: Message) => void) | null>(null);
146
155
  const [msgRefreshKey, setMsgRefreshKey] = useState(0);
147
156
 
157
+ const effectiveCurrentAgent = currentAgent ?? sessionAgent ?? null;
158
+
159
+ useEffect(() => {
160
+ client.current = new ChannelHubClient(apiUrl, token);
161
+ if (!currentAgent) {
162
+ void client.current.getSessionMe().then(res => {
163
+ if (res?.agent) setSessionAgent(res.agent);
164
+ }).catch(() => undefined);
165
+ }
166
+ }, [apiUrl, token, currentAgent]);
167
+
168
+ const mergedTeamAgents = useMemo(() => {
169
+ const map = new Map<string, ChannelHubAgent>();
170
+ if (effectiveCurrentAgent?.id) map.set(effectiveCurrentAgent.id, effectiveCurrentAgent);
171
+ for (const a of teamAgents ?? []) {
172
+ if (a?.id && !map.has(a.id)) map.set(a.id, a);
173
+ }
174
+ for (const conv of items) {
175
+ if (conv.assignedAgent?.id && !map.has(conv.assignedAgent.id)) {
176
+ map.set(conv.assignedAgent.id, conv.assignedAgent);
177
+ }
178
+ }
179
+ return [...map.values()];
180
+ }, [effectiveCurrentAgent, teamAgents, items]);
181
+
182
+ const handleAssignConversation = useCallback(async (conv: Conversation, agent: ChannelHubAgent | null) => {
183
+ setItems(prev => prev.map(item => item.id === conv.id ? { ...item, assignedAgent: agent } : item));
184
+ setSelected(prev => prev && prev.id === conv.id ? { ...prev, assignedAgent: agent } : prev);
185
+ setExtRefreshKey(k => k + 1);
186
+ try {
187
+ const updated = await client.current.assignConversation(conv.id, agent);
188
+ setItems(prev => prev.map(item => item.id === conv.id ? { ...item, ...updated, assignedAgent: updated.assignedAgent ?? agent } : item));
189
+ setSelected(prev => prev && prev.id === conv.id ? { ...prev, ...updated, assignedAgent: updated.assignedAgent ?? agent } : prev);
190
+ setExtRefreshKey(k => k + 1);
191
+ } catch {
192
+ // Keep optimistic assignment if offline/demo
193
+ }
194
+ }, []);
195
+
148
196
  const handleLinkContact = useCallback(async (conv: Conversation, externalId: string | null) => {
149
197
  if (conv.contactId) {
150
198
  await client.current.patchContact(conv.contactId, externalId);
@@ -205,16 +253,29 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
205
253
  return () => document.removeEventListener('mousedown', handleOutside);
206
254
  }, [filterOpen]);
207
255
 
256
+ const scopeCounts = useMemo(() => {
257
+ const mine = effectiveCurrentAgent
258
+ ? items.filter(x => x.assignedAgent?.id === effectiveCurrentAgent.id).length
259
+ : 0;
260
+ const unassigned = items.filter(x => !x.assignedAgent).length;
261
+ return { all: items.length, mine, unassigned };
262
+ }, [items, effectiveCurrentAgent]);
263
+
208
264
  const visible = useMemo(() => {
209
265
  const needle = query.toLowerCase().trim();
210
266
  return items.filter(x => {
211
- const label = `${x.contactName ?? ''} ${x.subject ?? ''} ${x.providerConversationKey}`.toLowerCase();
267
+ if (assignmentScope === 'mine') {
268
+ if (!effectiveCurrentAgent || x.assignedAgent?.id !== effectiveCurrentAgent.id) return false;
269
+ } else if (assignmentScope === 'unassigned') {
270
+ if (x.assignedAgent) return false;
271
+ }
272
+ const label = `${x.contactName ?? ''} ${x.subject ?? ''} ${x.providerConversationKey} ${x.assignedAgent?.name ?? ''}`.toLowerCase();
212
273
  const provider = connectionById.get(x.connectionId)?.provider ?? 'unknown';
213
274
  const matchProvider = activeFilters.provider === 'all' || provider === activeFilters.provider;
214
275
  const matchUnread = !activeFilters.unreadOnly || (x.unreadCount ?? 0) > 0;
215
276
  return matchProvider && matchUnread && (!needle || label.includes(needle));
216
277
  });
217
- }, [items, connectionById, activeFilters, query]);
278
+ }, [items, connectionById, activeFilters, query, assignmentScope, effectiveCurrentAgent]);
218
279
 
219
280
  const hasActiveFilters = activeFilters.provider !== 'all' || activeFilters.unreadOnly;
220
281
 
@@ -263,6 +324,56 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
263
324
  </div>
264
325
  <div style={css.search}><Search size={16} strokeWidth={2} /><Input aria-label={t.searchPlaceholder} value={query} onChange={e => setQuery(e.target.value)} placeholder={t.searchPlaceholder} />{query && <button style={css.clear} onClick={() => setQuery('')} aria-label="Xóa tìm kiếm">×</button>}</div>
265
326
 
327
+ {/* 3-Tab Assignment Scope Bar (Tất cả | Của tôi | Chưa nhận) */}
328
+ <div
329
+ role="tablist"
330
+ aria-label="Lọc theo người phụ trách"
331
+ style={{
332
+ display: 'grid',
333
+ gridTemplateColumns: 'repeat(3, 1fr)',
334
+ gap: 2,
335
+ margin: '0 14px 10px',
336
+ padding: 3,
337
+ borderRadius: 9,
338
+ border: `1px solid ${c.line}`,
339
+ background: c.surface,
340
+ }}
341
+ >
342
+ {([
343
+ { key: 'all' as const, label: locale === 'en' ? 'All' : 'Tất cả', count: scopeCounts.all },
344
+ { key: 'mine' as const, label: locale === 'en' ? 'Mine' : 'Của tôi', count: scopeCounts.mine },
345
+ { key: 'unassigned' as const, label: locale === 'en' ? 'Unassigned' : 'Chưa nhận', count: scopeCounts.unassigned },
346
+ ]).map(tab => {
347
+ const active = assignmentScope === tab.key;
348
+ return (
349
+ <button
350
+ key={tab.key}
351
+ type="button"
352
+ role="tab"
353
+ aria-selected={active}
354
+ onClick={() => setAssignmentScope(tab.key)}
355
+ style={{
356
+ border: 0,
357
+ borderRadius: 6,
358
+ padding: '5px 4px',
359
+ fontSize: 11,
360
+ fontWeight: active ? 700 : 500,
361
+ background: active ? c.white : 'transparent',
362
+ color: active ? primary : c.muted,
363
+ boxShadow: active ? '0 1px 3px rgba(23,32,51,.08)' : 'none',
364
+ cursor: 'pointer',
365
+ whiteSpace: 'nowrap',
366
+ overflow: 'hidden',
367
+ textOverflow: 'ellipsis',
368
+ transition: 'all 120ms ease',
369
+ }}
370
+ >
371
+ {tab.label} <span style={{ opacity: 0.75 }}>({tab.count})</span>
372
+ </button>
373
+ );
374
+ })}
375
+ </div>
376
+
266
377
  {/* Active filter chips */}
267
378
  {hasActiveFilters && (
268
379
  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', padding: '0 14px 8px' }}>
@@ -326,7 +437,7 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
326
437
  )}
327
438
 
328
439
  <ScrollArea style={css.conversationList}>
329
- {visible.map(x => <ConversationRow key={x.id} conversation={x} provider={connectionById.get(x.connectionId)?.provider} selected={selected?.id === x.id} primary={primary} onSelect={() => { setSelected(x); onConversationSelect?.(x.id); void client.current.markRead(x.id).then(() => load()).catch(() => undefined); }} />)}
440
+ {visible.map(x => <ConversationRow key={x.id} conversation={x} provider={connectionById.get(x.connectionId)?.provider} selected={selected?.id === x.id} primary={primary} currentAgent={effectiveCurrentAgent} onSelect={() => { setSelected(x); onConversationSelect?.(x.id); void client.current.markRead(x.id).then(() => load()).catch(() => undefined); }} />)}
330
441
  {!visible.length && <div style={css.emptySmall}><div style={css.emptyIcon}><Search size={16} strokeWidth={2} /></div><strong>Không tìm thấy</strong><span>Thử từ khóa hoặc bộ lọc khác.</span></div>}
331
442
  {cursor && <button style={css.loadMore} onClick={() => void load(cursor)}>Xem thêm hội thoại</button>}
332
443
  </ScrollArea>
@@ -349,6 +460,9 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
349
460
  disableAttachments={disableAttachments}
350
461
  hideKeyboardHint={hideKeyboardHint}
351
462
  extensions={extensions}
463
+ currentAgent={effectiveCurrentAgent}
464
+ teamAgents={mergedTeamAgents}
465
+ onAssignAgent={(agent) => handleAssignConversation(selected, agent)}
352
466
  onLinkContact={(extId) => handleLinkContact(selected, extId)}
353
467
  onRefreshContactInfo={handleRefreshContactInfo}
354
468
  />
@@ -374,7 +488,7 @@ export const ChannelHubInbox = forwardRef<ChannelHubInboxHandle, WidgetProps>(fu
374
488
  );
375
489
  });
376
490
 
377
- function ConversationRow({ conversation, provider, selected, primary, onSelect }: { conversation: Conversation; provider?: Provider; selected: boolean; primary: string; onSelect: () => void }) {
491
+ function ConversationRow({ conversation, provider, selected, primary, currentAgent, onSelect }: { conversation: Conversation; provider?: Provider; selected: boolean; primary: string; currentAgent?: ChannelHubAgent | null; onSelect: () => void }) {
378
492
  const [hovered, setHovered] = useState(false);
379
493
  const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
380
494
  const unread = conversation.unreadCount ?? 0;
@@ -382,6 +496,8 @@ function ConversationRow({ conversation, provider, selected, primary, onSelect }
382
496
  const prefix = conversation.lastMessageDirection === 'outbound' ? 'Bạn: ' : '';
383
497
  const truncated = rawText.length > 60 ? rawText.slice(0, 60) + '…' : rawText;
384
498
  const preview = rawText ? prefix + truncated : '';
499
+ const assigned = conversation.assignedAgent ?? null;
500
+ const isMine = Boolean(assigned && currentAgent && assigned.id === currentAgent.id);
385
501
 
386
502
  let rowBg = 'transparent';
387
503
  if (selected) rowBg = '#eef2ff';
@@ -414,10 +530,67 @@ function ConversationRow({ conversation, provider, selected, primary, onSelect }
414
530
  )}
415
531
  </span>
416
532
  </span>
417
- <span style={{ ...css.rowBottom, color: unread > 0 && !selected ? '#4a5568' : c.muted }}>
418
- <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>
533
+ <span style={{ ...css.rowBottom, justifyContent: 'space-between', alignItems: 'center', gap: 6, color: unread > 0 && !selected ? '#4a5568' : c.muted }}>
534
+ <span style={{ flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
419
535
  {preview || <span style={{ opacity: 0.5 }}>Chưa có tin nhắn</span>}
420
536
  </span>
537
+ {assigned ? (
538
+ <span
539
+ title={`Phụ trách: ${assigned.name}${assigned.title ? ` (${assigned.title})` : ''}`}
540
+ style={{
541
+ display: 'inline-flex',
542
+ alignItems: 'center',
543
+ gap: 4,
544
+ padding: '1px 6px 1px 2px',
545
+ borderRadius: 999,
546
+ fontSize: 10,
547
+ fontWeight: 600,
548
+ flexShrink: 0,
549
+ background: isMine ? `${primary}18` : '#f1f5f9',
550
+ color: isMine ? primary : '#475569',
551
+ border: isMine ? `1px solid ${primary}33` : '1px solid #e2e8f0',
552
+ }}
553
+ >
554
+ <span
555
+ style={{
556
+ width: 14,
557
+ height: 14,
558
+ borderRadius: '50%',
559
+ background: isMine ? primary : '#64748b',
560
+ color: '#fff',
561
+ fontSize: 8,
562
+ fontWeight: 700,
563
+ display: 'inline-grid',
564
+ placeItems: 'center',
565
+ overflow: 'hidden',
566
+ flexShrink: 0,
567
+ }}
568
+ >
569
+ {assigned.avatarUrl
570
+ ? <img src={assigned.avatarUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
571
+ : initials(assigned.name)}
572
+ </span>
573
+ <span style={{ maxWidth: 68, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
574
+ {shortAgentName(assigned.name)}
575
+ </span>
576
+ </span>
577
+ ) : unread > 0 ? (
578
+ <span
579
+ style={{
580
+ display: 'inline-flex',
581
+ alignItems: 'center',
582
+ padding: '1px 6px',
583
+ borderRadius: 999,
584
+ fontSize: 9.5,
585
+ fontWeight: 600,
586
+ flexShrink: 0,
587
+ background: '#fef3c7',
588
+ color: '#b45309',
589
+ }}
590
+ >
591
+ Chưa nhận
592
+ </span>
593
+ ) : null}
421
594
  </span>
422
595
  </span>
423
596
  </button>
@@ -426,7 +599,7 @@ function ConversationRow({ conversation, provider, selected, primary, onSelect }
426
599
 
427
600
  type PendingAttachment = { file: File; uploading: boolean; url?: string; mimeType?: string; attachmentType?: string; objectUrl?: string };
428
601
 
429
- function MessagePanel({ conversation, provider, connection, client, primary, error, onRegisterAppend, refreshKey, infoOpen, onToggleInfo, t, disableAttachments, hideKeyboardHint, extensions, onLinkContact, onRefreshContactInfo }: { conversation: Conversation; provider?: Provider; connection?: Connection; client: ChannelHubClient; primary: string; error: string; onRegisterAppend?: (fn: ((msg: Message) => void) | null) => void; refreshKey?: number; infoOpen: boolean; onToggleInfo: () => void; t: WidgetTranslations; disableAttachments?: boolean; hideKeyboardHint?: boolean; extensions?: Extension[]; onLinkContact: (externalId: string | null) => Promise<void>; onRefreshContactInfo: () => void }) {
602
+ function MessagePanel({ conversation, provider, connection, client, primary, error, onRegisterAppend, refreshKey, infoOpen, onToggleInfo, t, disableAttachments, hideKeyboardHint, extensions, currentAgent, teamAgents, onAssignAgent, onLinkContact, onRefreshContactInfo }: { conversation: Conversation; provider?: Provider; connection?: Connection; client: ChannelHubClient; primary: string; error: string; onRegisterAppend?: (fn: ((msg: Message) => void) | null) => void; refreshKey?: number; infoOpen: boolean; onToggleInfo: () => void; t: WidgetTranslations; disableAttachments?: boolean; hideKeyboardHint?: boolean; extensions?: Extension[]; currentAgent?: ChannelHubAgent | null; teamAgents?: ChannelHubAgent[]; onAssignAgent: (agent: ChannelHubAgent | null) => Promise<void>; onLinkContact: (externalId: string | null) => Promise<void>; onRefreshContactInfo: () => void }) {
430
603
  const [messages, setMessages] = useState<Message[]>([]); const [cursor, setCursor] = useState<string>(); const [text, setText] = useState(''); const [loading, setLoading] = useState(true); const [sending, setSending] = useState(false); const [sendError, setSendError] = useState(''); const messageAreaRef = useRef<HTMLDivElement>(null); const name = conversation.contactName ?? conversation.subject ?? conversation.providerConversationKey;
431
604
  const fileImageRef = useRef<HTMLInputElement>(null);
432
605
  const fileDocRef = useRef<HTMLInputElement>(null);
@@ -443,6 +616,20 @@ function MessagePanel({ conversation, provider, connection, client, primary, err
443
616
  const [templates, setTemplates] = useState<{ id: string; title: string; content: string; shortcut: string | null }[]>([]);
444
617
  const templatePickerRef = useRef<HTMLDivElement>(null);
445
618
  const templateBtnRef = useRef<HTMLButtonElement>(null);
619
+ const [assigneeMenuOpen, setAssigneeMenuOpen] = useState(false);
620
+ const assigneeBtnRef = useRef<HTMLDivElement>(null);
621
+ const assigneeMenuRef = useRef<HTMLDivElement>(null);
622
+
623
+ useEffect(() => {
624
+ if (!assigneeMenuOpen) return;
625
+ function handleOutside(e: MouseEvent) {
626
+ if (assigneeBtnRef.current?.contains(e.target as Node)) return;
627
+ if (assigneeMenuRef.current?.contains(e.target as Node)) return;
628
+ setAssigneeMenuOpen(false);
629
+ }
630
+ document.addEventListener('mousedown', handleOutside);
631
+ return () => document.removeEventListener('mousedown', handleOutside);
632
+ }, [assigneeMenuOpen]);
446
633
 
447
634
  useEffect(() => {
448
635
  return () => { if (pendingAttachment?.objectUrl) URL.revokeObjectURL(pendingAttachment.objectUrl); };
@@ -531,11 +718,43 @@ function MessagePanel({ conversation, provider, connection, client, primary, err
531
718
  : [];
532
719
  if (!value && !attachments.length || sending) return;
533
720
  setSending(true); setSendError('');
721
+ if (!conversation.assignedAgent && currentAgent) {
722
+ void onAssignAgent(currentAgent);
723
+ }
724
+ const optimisticId = `optimistic-${Date.now()}`;
725
+ if (currentAgent) {
726
+ shouldScrollToBottom.current = true;
727
+ setMessages(prev => [
728
+ ...prev,
729
+ {
730
+ id: optimisticId,
731
+ direction: 'outbound',
732
+ status: 'sending',
733
+ text: value || undefined,
734
+ attachments: attachments.length ? attachments : undefined,
735
+ occurredAt: new Date().toISOString(),
736
+ senderAgent: currentAgent,
737
+ },
738
+ ]);
739
+ }
534
740
  try {
535
741
  await client.sendMessage(conversation.id, value || undefined, attachments.length ? attachments : undefined);
536
742
  if (pendingAttachment?.objectUrl) URL.revokeObjectURL(pendingAttachment.objectUrl);
537
743
  setText(''); setPendingAttachment(null); await load();
538
- } catch (e) { setSendError(e instanceof Error ? e.message : 'Không gửi được tin nhắn'); } finally { setSending(false); }
744
+ if (currentAgent) {
745
+ setMessages(prev => {
746
+ const withoutOptimistic = prev.filter(m => m.id !== optimisticId);
747
+ const lastIdx = withoutOptimistic.length - 1;
748
+ if (lastIdx >= 0 && withoutOptimistic[lastIdx]?.direction === 'outbound' && !withoutOptimistic[lastIdx]?.senderAgent) {
749
+ return withoutOptimistic.map((m, i) => i === lastIdx ? { ...m, senderAgent: currentAgent } : m);
750
+ }
751
+ return withoutOptimistic;
752
+ });
753
+ }
754
+ } catch (e) {
755
+ setMessages(prev => prev.filter(m => m.id !== optimisticId));
756
+ setSendError(e instanceof Error ? e.message : 'Không gửi được tin nhắn');
757
+ } finally { setSending(false); }
539
758
  }
540
759
 
541
760
  function insertEmoji(emoji: string) {
@@ -574,7 +793,253 @@ function MessagePanel({ conversation, provider, connection, client, primary, err
574
793
  <strong style={css.contactName}>{name}</strong>
575
794
  <span style={css.contactMeta}>{connectionDisplayName(connection) ?? providerLabel(provider)}</span>
576
795
  </div>
577
- <div style={css.headerActions}>
796
+ <div style={{ ...css.headerActions, alignItems: 'center', gap: 6 }}>
797
+ {/* Assignee Switcher & Quick Claim */}
798
+ <div ref={assigneeBtnRef} style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
799
+ {!conversation.assignedAgent && currentAgent ? (
800
+ <div style={{ display: 'inline-flex', alignItems: 'center', borderRadius: 999, border: `1px solid ${primary}40`, background: `${primary}0d`, overflow: 'hidden' }}>
801
+ <button
802
+ type="button"
803
+ onClick={() => void onAssignAgent(currentAgent)}
804
+ style={{
805
+ border: 0,
806
+ background: 'transparent',
807
+ color: primary,
808
+ padding: '4px 9px',
809
+ fontSize: 11.5,
810
+ fontWeight: 600,
811
+ cursor: 'pointer',
812
+ display: 'inline-flex',
813
+ alignItems: 'center',
814
+ gap: 4,
815
+ whiteSpace: 'nowrap',
816
+ }}
817
+ >
818
+ <UserPlus size={12} strokeWidth={2.2} />
819
+ <span>+ Nhận phụ trách</span>
820
+ </button>
821
+ {(teamAgents?.length ?? 0) > 1 && (
822
+ <button
823
+ type="button"
824
+ aria-label="Chọn nhân viên phụ trách"
825
+ onClick={() => setAssigneeMenuOpen(o => !o)}
826
+ style={{
827
+ border: 0,
828
+ borderLeft: `1px solid ${primary}30`,
829
+ background: 'transparent',
830
+ color: primary,
831
+ padding: '4px 6px',
832
+ cursor: 'pointer',
833
+ display: 'inline-flex',
834
+ alignItems: 'center',
835
+ }}
836
+ >
837
+ <ChevronDown size={12} strokeWidth={2.2} />
838
+ </button>
839
+ )}
840
+ </div>
841
+ ) : (
842
+ <button
843
+ type="button"
844
+ onClick={() => setAssigneeMenuOpen(o => !o)}
845
+ style={{
846
+ display: 'inline-flex',
847
+ alignItems: 'center',
848
+ gap: 6,
849
+ padding: '3px 9px 3px 4px',
850
+ borderRadius: 999,
851
+ border: `1px solid ${c.line}`,
852
+ background: c.surface,
853
+ color: c.ink,
854
+ fontSize: 11.5,
855
+ fontWeight: 600,
856
+ cursor: 'pointer',
857
+ whiteSpace: 'nowrap',
858
+ }}
859
+ >
860
+ {conversation.assignedAgent ? (
861
+ <>
862
+ <span
863
+ style={{
864
+ width: 18,
865
+ height: 18,
866
+ borderRadius: '50%',
867
+ background: primary,
868
+ color: '#fff',
869
+ fontSize: 9,
870
+ fontWeight: 700,
871
+ display: 'inline-grid',
872
+ placeItems: 'center',
873
+ overflow: 'hidden',
874
+ flexShrink: 0,
875
+ }}
876
+ >
877
+ {conversation.assignedAgent.avatarUrl
878
+ ? <img src={conversation.assignedAgent.avatarUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
879
+ : initials(conversation.assignedAgent.name)}
880
+ </span>
881
+ <span style={{ color: c.muted, fontWeight: 500 }}>Phụ trách:</span>
882
+ <span style={{ maxWidth: 110, overflow: 'hidden', textOverflow: 'ellipsis' }}>
883
+ {shortAgentName(conversation.assignedAgent.name)}
884
+ </span>
885
+ </>
886
+ ) : (
887
+ <>
888
+ <UserCheck size={13} color={c.muted} />
889
+ <span style={{ color: c.muted }}>Chưa phân công</span>
890
+ </>
891
+ )}
892
+ <ChevronDown size={12} color={c.muted} />
893
+ </button>
894
+ )}
895
+
896
+ {assigneeMenuOpen && (
897
+ <div
898
+ ref={assigneeMenuRef}
899
+ style={{
900
+ position: 'absolute',
901
+ top: 'calc(100% + 6px)',
902
+ right: 0,
903
+ zIndex: 200,
904
+ minWidth: 230,
905
+ background: c.white,
906
+ border: `1px solid ${c.line}`,
907
+ borderRadius: 11,
908
+ boxShadow: '0 10px 28px rgba(23,32,51,.15)',
909
+ padding: 6,
910
+ fontSize: 12,
911
+ }}
912
+ >
913
+ <div style={{ padding: '4px 8px 6px', fontSize: 10, fontWeight: 700, color: c.muted, letterSpacing: 0.8, textTransform: 'uppercase' }}>
914
+ Người phụ trách hội thoại
915
+ </div>
916
+
917
+ {currentAgent && conversation.assignedAgent?.id !== currentAgent.id && (
918
+ <button
919
+ type="button"
920
+ onClick={() => {
921
+ setAssigneeMenuOpen(false);
922
+ void onAssignAgent(currentAgent);
923
+ }}
924
+ style={{
925
+ display: 'flex',
926
+ alignItems: 'center',
927
+ gap: 8,
928
+ width: '100%',
929
+ border: 0,
930
+ borderRadius: 7,
931
+ background: `${primary}10`,
932
+ color: primary,
933
+ padding: '6px 8px',
934
+ marginBottom: 4,
935
+ fontWeight: 600,
936
+ fontSize: 12,
937
+ cursor: 'pointer',
938
+ textAlign: 'left',
939
+ }}
940
+ >
941
+ <UserPlus size={13} />
942
+ <span>Nhận phụ trách cho tôi ({shortAgentName(currentAgent.name)})</span>
943
+ </button>
944
+ )}
945
+
946
+ <div style={{ maxHeight: 200, overflowY: 'auto' }}>
947
+ {(teamAgents ?? []).map(agent => {
948
+ const isAssigned = conversation.assignedAgent?.id === agent.id;
949
+ return (
950
+ <button
951
+ key={agent.id}
952
+ type="button"
953
+ onClick={() => {
954
+ setAssigneeMenuOpen(false);
955
+ void onAssignAgent(agent);
956
+ }}
957
+ style={{
958
+ display: 'flex',
959
+ alignItems: 'center',
960
+ justifyContent: 'space-between',
961
+ gap: 8,
962
+ width: '100%',
963
+ border: 0,
964
+ borderRadius: 7,
965
+ background: isAssigned ? '#f1f5f9' : 'transparent',
966
+ color: c.ink,
967
+ padding: '6px 8px',
968
+ cursor: 'pointer',
969
+ textAlign: 'left',
970
+ }}
971
+ >
972
+ <span style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
973
+ <span
974
+ style={{
975
+ width: 22,
976
+ height: 22,
977
+ borderRadius: '50%',
978
+ background: `${primary}18`,
979
+ color: primary,
980
+ fontSize: 10,
981
+ fontWeight: 700,
982
+ display: 'inline-grid',
983
+ placeItems: 'center',
984
+ overflow: 'hidden',
985
+ flexShrink: 0,
986
+ }}
987
+ >
988
+ {agent.avatarUrl
989
+ ? <img src={agent.avatarUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
990
+ : initials(agent.name)}
991
+ </span>
992
+ <span style={{ minWidth: 0 }}>
993
+ <span style={{ display: 'block', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
994
+ {agent.name}
995
+ </span>
996
+ {agent.title && (
997
+ <span style={{ display: 'block', fontSize: 10.5, color: c.muted }}>
998
+ {agent.title}
999
+ </span>
1000
+ )}
1001
+ </span>
1002
+ </span>
1003
+ {isAssigned && <Check size={13} color={primary} strokeWidth={2.5} />}
1004
+ </button>
1005
+ );
1006
+ })}
1007
+ </div>
1008
+
1009
+ {conversation.assignedAgent && (
1010
+ <>
1011
+ <div style={{ borderTop: `1px solid ${c.line}`, margin: '5px 0' }} />
1012
+ <button
1013
+ type="button"
1014
+ onClick={() => {
1015
+ setAssigneeMenuOpen(false);
1016
+ void onAssignAgent(null);
1017
+ }}
1018
+ style={{
1019
+ display: 'flex',
1020
+ alignItems: 'center',
1021
+ gap: 6,
1022
+ width: '100%',
1023
+ border: 0,
1024
+ borderRadius: 7,
1025
+ background: 'transparent',
1026
+ color: '#b42318',
1027
+ padding: '6px 8px',
1028
+ fontSize: 11.5,
1029
+ fontWeight: 500,
1030
+ cursor: 'pointer',
1031
+ textAlign: 'left',
1032
+ }}
1033
+ >
1034
+ <X size={13} />
1035
+ <span>Bỏ phân công (Chưa có người nhận)</span>
1036
+ </button>
1037
+ </>
1038
+ )}
1039
+ </div>
1040
+ )}
1041
+ </div>
1042
+
578
1043
  <button style={css.iconButton} aria-label="Thêm tùy chọn">
579
1044
  <MoreHorizontal size={16} strokeWidth={2} />
580
1045
  </button>
@@ -958,10 +1423,42 @@ function MessageBubble({ message, primary }: { message: Message; primary: string
958
1423
  const [lightbox, setLightbox] = useState<{ url: string; kind: 'image' | 'video' } | null>(null);
959
1424
  const align = outbound ? 'flex-end' : 'flex-start';
960
1425
 
1426
+ const senderAgent = outbound ? (message.senderAgent ?? null) : null;
1427
+
961
1428
  const timeEl = (
962
- <time style={{ display: 'block', marginTop: 4, fontSize: 10, opacity: 0.65, textAlign: 'right', letterSpacing: 0.2, userSelect: 'none' as const }}>
963
- {formatTime(message.occurredAt, true)}{outbound && <> <StatusIcon status={message.status} /></>}
964
- </time>
1429
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: outbound ? 'flex-end' : 'flex-start', gap: 5, marginTop: 4, fontSize: 10, opacity: 0.78, letterSpacing: 0.2, userSelect: 'none' as const }}>
1430
+ {senderAgent && (
1431
+ <span
1432
+ title={senderAgent.title ? `${senderAgent.name} (${senderAgent.title})` : senderAgent.name}
1433
+ style={{ display: 'inline-flex', alignItems: 'center', gap: 3.5, fontWeight: 600 }}
1434
+ >
1435
+ <span
1436
+ style={{
1437
+ width: 14,
1438
+ height: 14,
1439
+ borderRadius: '50%',
1440
+ background: 'rgba(255,255,255,0.22)',
1441
+ color: '#fff',
1442
+ fontSize: 8,
1443
+ fontWeight: 700,
1444
+ display: 'inline-grid',
1445
+ placeItems: 'center',
1446
+ overflow: 'hidden',
1447
+ flexShrink: 0,
1448
+ }}
1449
+ >
1450
+ {senderAgent.avatarUrl
1451
+ ? <img src={senderAgent.avatarUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
1452
+ : initials(senderAgent.name)}
1453
+ </span>
1454
+ <span>{senderAgent.name}</span>
1455
+ <span style={{ opacity: 0.6 }}>•</span>
1456
+ </span>
1457
+ )}
1458
+ <time>
1459
+ {formatTime(message.occurredAt, true)}{outbound && <> <StatusIcon status={message.status} /></>}
1460
+ </time>
1461
+ </div>
965
1462
  );
966
1463
 
967
1464
  const overlayTime = (