@adatechnology/conversations-ui 0.1.0-rc.2 → 0.1.0-rc.21
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.
- package/dist/{chunk-ZDURDZTM.js → chunk-2AYDBWNE.js} +14 -0
- package/dist/chunk-TV4OQRGH.js +2187 -0
- package/dist/flows/index.d.ts +14 -2
- package/dist/flows/index.js +117 -39
- package/dist/index.d.ts +862 -136
- package/dist/index.js +1746 -1124
- package/dist/preview/index.d.ts +470 -0
- package/dist/preview/index.js +1329 -0
- package/dist/styles.css +228 -0
- package/dist/types-C6A_9edv.d.ts +456 -0
- package/package.json +10 -3
- package/src/AudioRecorderButton.test.tsx +30 -0
- package/src/AudioRecorderButton.tsx +248 -0
- package/src/AudioTranscription.test.tsx +115 -0
- package/src/AudioTranscription.tsx +249 -0
- package/src/Avatar.tsx +30 -4
- package/src/ChannelIcon.tsx +87 -0
- package/src/ConversationContextPanel.tsx +280 -0
- package/src/ConversationDocumentsPanel.tsx +425 -0
- package/src/ConversationHeader.tsx +257 -0
- package/src/ConversationListItem.tsx +54 -7
- package/src/ConversationLocalesProvider.tsx +44 -0
- package/src/ConversationRow.tsx +137 -0
- package/src/DateDivider.tsx +16 -3
- package/src/DocumentsLibrary.tsx +322 -0
- package/src/EmojiPicker.tsx +69 -55
- package/src/FileIcon.test.ts +83 -0
- package/src/FileIcon.tsx +88 -11
- package/src/InteractiveMessage.test.tsx +41 -0
- package/src/InteractiveMessage.tsx +143 -0
- package/src/Lightbox.tsx +18 -3
- package/src/MediaRenderer.tsx +96 -22
- package/src/MessageBubble.tsx +77 -5
- package/src/MessageComposer.test.tsx +35 -0
- package/src/MessageComposer.tsx +165 -19
- package/src/RichMessageComposer.test.tsx +83 -0
- package/src/RichMessageComposer.tsx +380 -0
- package/src/Wallpaper.test.tsx +21 -0
- package/src/Wallpaper.tsx +69 -7
- package/src/WhatsAppMessageEditor.tsx +28 -4
- package/src/WindowExpiredNotice.tsx +57 -0
- package/src/audioRecorderFormat.test.ts +67 -0
- package/src/conversationChannel.test.ts +53 -0
- package/src/conversationChannel.ts +146 -0
- package/src/conversationTranscript.test.ts +122 -0
- package/src/conversationTranscript.ts +89 -0
- package/src/conversationWindow.test.ts +90 -0
- package/src/conversationWindow.ts +78 -0
- package/src/documentTypeLabel.test.ts +57 -0
- package/src/emojiCatalog.test.ts +35 -0
- package/src/emojiCatalog.ts +189 -0
- package/src/flows/FlowGroupHeader.tsx +12 -2
- package/src/flows/FlowMapCanvas.tsx +17 -14
- package/src/flows/FlowMapNode.tsx +3 -1
- package/src/flows/FlowNodeCard.tsx +22 -4
- package/src/flows/FlowNodePanel.tsx +132 -35
- package/src/flows/FlowPalette.tsx +6 -2
- package/src/flows/FlowWhatsAppPreview.tsx +14 -3
- package/src/flows/flowGraph.ts +5 -5
- package/src/flows/labels.ts +5 -0
- package/src/hooks/useConversationActions.ts +56 -0
- package/src/hooks/useConversationDocuments.ts +15 -9
- package/src/hooks/useConversationList.ts +15 -9
- package/src/hooks/useConversationMessages.ts +2 -2
- package/src/hooks/useScrollToLatestMessage.ts +127 -0
- package/src/index.ts +140 -16
- package/src/lib/cn.test.ts +29 -0
- package/src/lib/cn.ts +15 -0
- package/src/lib/createMediaUrlResolver.ts +33 -0
- package/src/lib/paginated.test.ts +33 -0
- package/src/lib/paginated.ts +26 -0
- package/src/lib/phone.ts +34 -0
- package/src/preview/ConversationPreview.tsx +334 -0
- package/src/preview/MediaTypesPreview.tsx +87 -0
- package/src/preview/conversationPreviewFailures.test.ts +64 -0
- package/src/preview/createMockConversationsApi.ts +271 -0
- package/src/preview/createMockSSEProvider.ts +40 -0
- package/src/preview/createPreviewBridgeClient.test.ts +92 -0
- package/src/preview/createPreviewBridgeClient.ts +124 -0
- package/src/preview/createPreviewMediaUploader.ts +82 -0
- package/src/preview/createPreviewWebhookClient.test.ts +194 -0
- package/src/preview/createPreviewWebhookClient.ts +222 -0
- package/src/preview/index.ts +67 -0
- package/src/preview/mediaTypeOf.test.ts +15 -0
- package/src/preview/mockDocumentsSearch.test.ts +57 -0
- package/src/preview/mockEventSource.ts +53 -0
- package/src/preview/preview.test.ts +177 -0
- package/src/preview/previewFileSamples.test.ts +151 -0
- package/src/preview/previewFileSamples.ts +74 -0
- package/src/preview/previewFixtures.ts +440 -0
- package/src/preview/previewMediaSource.test.ts +62 -0
- package/src/preview/previewMediaSource.ts +91 -0
- package/src/preview/previewMediaUploader.test.ts +61 -0
- package/src/preview/previewStore.ts +193 -0
- package/src/preview/startPreviewScript.ts +60 -0
- package/src/providers/types.ts +175 -12
- package/src/quickReply.test.ts +58 -0
- package/src/settings/TranscriptionSettingsForm.test.tsx +81 -0
- package/src/settings/TranscriptionSettingsForm.tsx +189 -0
- package/src/settings/WhatsAppCreateTemplateForm.tsx +3 -1
- package/src/settings/WhatsAppTemplatesSettings.tsx +106 -0
- package/src/styles.css +173 -0
- package/src/types.ts +72 -1
- package/src/useDarkMode.ts +26 -0
- package/src/useIsNarrow.ts +29 -0
- package/src/useWaitingNotifications.ts +74 -29
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Visão lado-cliente: você digita como se fosse o cliente no WhatsApp e vê o bot responder. A
|
|
3
|
+
* mensagem sai assinada para o webhook real, então o que roda aqui é o mesmo caminho de staging e
|
|
4
|
+
* produção — webhook, parser, motor de conversa.
|
|
5
|
+
*
|
|
6
|
+
* É o layout de conversa de verdade (wallpaper, divisor de data, agrupamento de bolhas), não uma
|
|
7
|
+
* casca de teste: o preview serve para julgar copy e fluxo, e isso só funciona se o que se vê
|
|
8
|
+
* aqui for o que o cliente vê no aparelho dele.
|
|
9
|
+
*
|
|
10
|
+
* O SSE só avisa que algo mudou (`{ direction, sender }`, sem conteúdo), então a chegada de um
|
|
11
|
+
* evento dispara refetch. É assim que o servidor funciona; renderizar direto do evento
|
|
12
|
+
* funcionaria no mock e quebraria em produção.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
16
|
+
import type { InteractiveSelection, MessagePayload } from '../types'
|
|
17
|
+
import type { SSEProvider } from '../providers/types'
|
|
18
|
+
import { MessageBubble } from '../MessageBubble'
|
|
19
|
+
import { MessageComposer } from '../MessageComposer'
|
|
20
|
+
import { DateDivider } from '../DateDivider'
|
|
21
|
+
import { ConversationWallpaper } from '../Wallpaper'
|
|
22
|
+
import type { PreviewWebhookClient, SendPreviewMediaParams } from './createPreviewWebhookClient'
|
|
23
|
+
import { AudioRecorderButton } from '../AudioRecorderButton'
|
|
24
|
+
|
|
25
|
+
export type ConversationPreviewProps = {
|
|
26
|
+
client: PreviewWebhookClient
|
|
27
|
+
sse: SSEProvider
|
|
28
|
+
conversationId: string
|
|
29
|
+
loadMessages: (conversationId: string) => Promise<MessagePayload[]>
|
|
30
|
+
placeholder?: string
|
|
31
|
+
/**
|
|
32
|
+
* Recarrega o transcript a cada N ms. Serve a host SEM stream: a resposta do bot é assíncrona, e
|
|
33
|
+
* sem SSE nem polling ela só apareceria no próximo envio — o sintoma é "às vezes ele não
|
|
34
|
+
* responde". Ausente, não faz polling (host com SSE não precisa).
|
|
35
|
+
*/
|
|
36
|
+
pollIntervalMs?: number
|
|
37
|
+
/**
|
|
38
|
+
* Como transformar um arquivo do disco (ou o áudio gravado) na referência que o webhook carrega.
|
|
39
|
+
* O caminho da Meta entrega mídia por `id`, e quem sabe hospedar o arquivo é o host — a SDK não
|
|
40
|
+
* inventa um endpoint de upload. Ausente, o compositor não oferece anexo nem gravação: melhor um
|
|
41
|
+
* botão que não existe do que um que falha ao ser tocado.
|
|
42
|
+
*/
|
|
43
|
+
/** Destino alternativo do áudio gravado. Sem isto, usa o do próprio `client`. */
|
|
44
|
+
uploadMedia?: (file: File) => Promise<PreviewUploadedMedia>
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type PreviewUploadedMedia = {
|
|
48
|
+
readonly mediaId: string
|
|
49
|
+
readonly mimeType?: string
|
|
50
|
+
readonly filename?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Deriva o tipo de mídia do WhatsApp a partir do MIME do arquivo escolhido. */
|
|
54
|
+
export function mediaTypeOf(mimeType: string): SendPreviewMediaParams['mediaType'] {
|
|
55
|
+
if (mimeType.startsWith('image/')) return 'image'
|
|
56
|
+
if (mimeType.startsWith('video/')) return 'video'
|
|
57
|
+
if (mimeType.startsWith('audio/')) return 'audio'
|
|
58
|
+
return 'document'
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Mesma janela usada pelo WhatsApp para colar bolhas do mesmo autor: acima disso, a mensagem
|
|
62
|
+
// recomeça um grupo (com rabicho e espaçamento maior).
|
|
63
|
+
const GROUPING_WINDOW_MS = 5 * 60 * 1000
|
|
64
|
+
|
|
65
|
+
// Escalonado, não um atraso fixo: a maioria das respostas chega em ~300ms, mas fluxo que consulta
|
|
66
|
+
// catálogo ou IA demora mais — e recarregar três vezes é mais barato que a conversa parecer morta.
|
|
67
|
+
const FOLLOW_UP_REFRESH_MS = [400, 1200, 3000]
|
|
68
|
+
|
|
69
|
+
type RenderedMessage = {
|
|
70
|
+
readonly message: MessagePayload
|
|
71
|
+
readonly isFirstInGroup: boolean
|
|
72
|
+
readonly showDateDivider: boolean
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function decorate(messages: readonly MessagePayload[]): RenderedMessage[] {
|
|
76
|
+
return messages.map((message, index) => {
|
|
77
|
+
const previous = index > 0 ? messages[index - 1] : undefined
|
|
78
|
+
const currentTime = new Date(message.timestamp).getTime()
|
|
79
|
+
const previousTime = previous ? new Date(previous.timestamp).getTime() : 0
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
message,
|
|
83
|
+
isFirstInGroup:
|
|
84
|
+
!previous || previous.sender !== message.sender || currentTime - previousTime > GROUPING_WINDOW_MS,
|
|
85
|
+
showDateDivider:
|
|
86
|
+
!previous || new Date(message.timestamp).toDateString() !== new Date(previous.timestamp).toDateString(),
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Status HTTP do erro, quando o host o preserva.
|
|
93
|
+
*
|
|
94
|
+
* O contrato não exige um tipo de erro — cada host tem o seu —, então a leitura é estrutural: basta
|
|
95
|
+
* carregar `status` (ou `statusCode`) para ser classificável. Host que joga `new Error(texto)` cai no
|
|
96
|
+
* caminho genérico, que ainda é melhor que silêncio.
|
|
97
|
+
*/
|
|
98
|
+
function statusOf(error: unknown): number | undefined {
|
|
99
|
+
if (typeof error !== 'object' || error === null) return undefined
|
|
100
|
+
const candidate = error as { status?: unknown; statusCode?: unknown }
|
|
101
|
+
const value = candidate.status ?? candidate.statusCode
|
|
102
|
+
return typeof value === 'number' ? value : undefined
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function isNotFound(error: unknown): boolean {
|
|
106
|
+
return statusOf(error) === 404
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function describeLoadFailure(error: unknown): string {
|
|
110
|
+
const status = statusOf(error)
|
|
111
|
+
// 401/403 no simulador quase sempre é a aba sem sessão: `sessionStorage` é por aba, e link com
|
|
112
|
+
// `rel="noreferrer"` abre contexto novo que não herda o token do painel.
|
|
113
|
+
if (status === 401 || status === 403) {
|
|
114
|
+
return 'Sem sessão de administrador nesta aba: a mensagem é entregue no webhook, mas o transcript não pode ser lido. Entre no painel nesta mesma aba e reabra o simulador.'
|
|
115
|
+
}
|
|
116
|
+
if (error instanceof Error && error.message) return `Não foi possível ler o transcript: ${error.message}`
|
|
117
|
+
return 'Não foi possível ler o transcript da conversa.'
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function ConversationPreview({
|
|
121
|
+
client,
|
|
122
|
+
sse,
|
|
123
|
+
conversationId,
|
|
124
|
+
loadMessages,
|
|
125
|
+
placeholder,
|
|
126
|
+
pollIntervalMs,
|
|
127
|
+
uploadMedia,
|
|
128
|
+
}: ConversationPreviewProps) {
|
|
129
|
+
const [messages, setMessages] = useState<MessagePayload[]>([])
|
|
130
|
+
const [failure, setFailure] = useState<string | undefined>(undefined)
|
|
131
|
+
const [loadFailure, setLoadFailure] = useState<string | undefined>(undefined)
|
|
132
|
+
const [isRecording, setIsRecording] = useState(false)
|
|
133
|
+
// Mensagens que o servidor ainda não devolveu. Sem isto, quem não consegue LER a conversa (sessão
|
|
134
|
+
// ausente, API fora) digita, envia com sucesso e não vê absolutamente nada mudar — o preview fica
|
|
135
|
+
// indistinguível de quebrado. São descartadas assim que uma leitura dá certo: aí quem manda na
|
|
136
|
+
// tela é o servidor, que já tem a mensagem gravada.
|
|
137
|
+
const [pendingLocal, setPendingLocal] = useState<MessagePayload[]>([])
|
|
138
|
+
const loadMessagesRef = useRef(loadMessages)
|
|
139
|
+
const bottomRef = useRef<HTMLDivElement>(null)
|
|
140
|
+
loadMessagesRef.current = loadMessages
|
|
141
|
+
|
|
142
|
+
const refresh = useCallback(async (): Promise<void> => {
|
|
143
|
+
try {
|
|
144
|
+
const loaded = await loadMessagesRef.current(conversationId)
|
|
145
|
+
setMessages(loaded)
|
|
146
|
+
setLoadFailure(undefined)
|
|
147
|
+
// Só descarta o eco quando o servidor de fato devolveu conversa: lista vazia é "não consegui
|
|
148
|
+
// ver nada" (sessão ausente, primeiro contato), e limpar aí apagava da tela a mensagem que o
|
|
149
|
+
// usuário acabou de mandar — o sintoma que este eco existe para evitar.
|
|
150
|
+
if (loaded.length > 0) setPendingLocal([])
|
|
151
|
+
} catch (error) {
|
|
152
|
+
// Conversa que ainda não existe é o estado normal do primeiro contato — transcript vazio, sem
|
|
153
|
+
// alarme. QUALQUER outra falha precisa aparecer: engolir todas era o que transformava sessão
|
|
154
|
+
// expirada (401) em silêncio absoluto, com a thread limpa e o operador concluindo que o envio
|
|
155
|
+
// não funcionou — quando a mensagem tinha sido entregue no webhook.
|
|
156
|
+
if (isNotFound(error)) {
|
|
157
|
+
setMessages([])
|
|
158
|
+
setLoadFailure(undefined)
|
|
159
|
+
return
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Não limpa o que já está na tela: perder o histórico por causa de um refresh que falhou é
|
|
163
|
+
// dano maior que o próprio erro.
|
|
164
|
+
setLoadFailure(describeLoadFailure(error))
|
|
165
|
+
}
|
|
166
|
+
}, [conversationId])
|
|
167
|
+
|
|
168
|
+
useEffect(() => {
|
|
169
|
+
void refresh()
|
|
170
|
+
}, [refresh])
|
|
171
|
+
|
|
172
|
+
useEffect(() => {
|
|
173
|
+
const source = sse.connectConversationStream(conversationId)
|
|
174
|
+
const handler = (): void => {
|
|
175
|
+
void refresh()
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
source.addEventListener('message', handler)
|
|
179
|
+
return () => {
|
|
180
|
+
source.removeEventListener('message', handler)
|
|
181
|
+
source.close()
|
|
182
|
+
}
|
|
183
|
+
}, [sse, conversationId, refresh])
|
|
184
|
+
|
|
185
|
+
useEffect(() => {
|
|
186
|
+
if (!pollIntervalMs) return
|
|
187
|
+
const timer = setInterval(() => void refresh(), pollIntervalMs)
|
|
188
|
+
return () => clearInterval(timer)
|
|
189
|
+
}, [pollIntervalMs, refresh])
|
|
190
|
+
|
|
191
|
+
useEffect(() => {
|
|
192
|
+
// `block: 'nearest'` e não o padrão ('start'): o padrão alinha o elemento ao topo da área
|
|
193
|
+
// visível MAIS PRÓXIMA que role — e quando o container do preview não tem altura limitada, essa
|
|
194
|
+
// área é a PÁGINA. O efeito era a tela inteira saltar para baixo ao abrir/usar o simulador.
|
|
195
|
+
bottomRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
|
|
196
|
+
}, [messages])
|
|
197
|
+
|
|
198
|
+
const rendered = useMemo(() => decorate([...messages, ...pendingLocal]), [messages, pendingLocal])
|
|
199
|
+
|
|
200
|
+
async function refreshWithFollowUps(): Promise<void> {
|
|
201
|
+
await refresh()
|
|
202
|
+
for (const atraso of FOLLOW_UP_REFRESH_MS) {
|
|
203
|
+
setTimeout(() => void refresh(), atraso)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function handleSend(text: string): Promise<void> {
|
|
208
|
+
setFailure(undefined)
|
|
209
|
+
try {
|
|
210
|
+
await client.sendText(text)
|
|
211
|
+
setPendingLocal((current) => [
|
|
212
|
+
...current,
|
|
213
|
+
{
|
|
214
|
+
id: `local-${current.length}-${text.length}`,
|
|
215
|
+
type: 'text',
|
|
216
|
+
content: text,
|
|
217
|
+
// Do ponto de vista do servidor, mensagem do cliente é inbound — é assim que ela aparece
|
|
218
|
+
// como "minha" nesta visão.
|
|
219
|
+
direction: 'inbound',
|
|
220
|
+
sender: 'customer',
|
|
221
|
+
timestamp: new Date().toISOString(),
|
|
222
|
+
status: 'sent',
|
|
223
|
+
},
|
|
224
|
+
])
|
|
225
|
+
// O bot responde de forma assíncrona: gravar a resposta leva algumas centenas de ms depois do
|
|
226
|
+
// 200 do webhook. Um refresh único aqui frequentemente chegava ANTES dela, e a conversa ficava
|
|
227
|
+
// com a pergunta sem resposta até o envio seguinte.
|
|
228
|
+
await refreshWithFollowUps()
|
|
229
|
+
} catch (error) {
|
|
230
|
+
// A recusa mais provável é assinatura inválida (segredo divergente do que a API valida), e
|
|
231
|
+
// ela precisa aparecer na tela: silenciada, o sintoma vira "mandei e não aconteceu nada".
|
|
232
|
+
setFailure(error instanceof Error ? error.message : 'Falha ao entregar a mensagem no webhook.')
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function handleInteractiveSelect(selection: InteractiveSelection): Promise<void> {
|
|
237
|
+
setFailure(undefined)
|
|
238
|
+
const reply = { id: selection.option.id, title: selection.option.title }
|
|
239
|
+
try {
|
|
240
|
+
// Botão e lista são payloads diferentes para a Meta (`button_reply` × `list_reply`), e o
|
|
241
|
+
// roteador do fluxo lê campos distintos: tratar os dois como um só faria o menu responder no
|
|
242
|
+
// simulador e falhar no aparelho do cliente.
|
|
243
|
+
await (selection.kind === 'button' ? client.sendButtonReply(reply) : client.sendListReply(reply))
|
|
244
|
+
await refreshWithFollowUps()
|
|
245
|
+
} catch (error) {
|
|
246
|
+
setFailure(error instanceof Error ? error.message : 'Falha ao entregar a resposta no webhook.')
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* O cliente do preview sabe subir mídia sozinho; a prop é só para quem quer outro destino.
|
|
252
|
+
*
|
|
253
|
+
* Antes isto era `uploadMedia` puro, e o microfone só aparecia no produto que lembrasse de montar
|
|
254
|
+
* o upload — de onde veio a divergência entre dois simuladores da mesma casa.
|
|
255
|
+
*/
|
|
256
|
+
const uploadFile = uploadMedia ?? client.uploadMedia
|
|
257
|
+
|
|
258
|
+
async function handleAttach(file: File): Promise<void> {
|
|
259
|
+
if (!uploadFile) return
|
|
260
|
+
setFailure(undefined)
|
|
261
|
+
try {
|
|
262
|
+
const uploaded = await uploadFile(file)
|
|
263
|
+
await client.sendMedia({
|
|
264
|
+
mediaType: mediaTypeOf(uploaded.mimeType ?? file.type),
|
|
265
|
+
mediaId: uploaded.mediaId,
|
|
266
|
+
mimeType: uploaded.mimeType ?? file.type,
|
|
267
|
+
filename: uploaded.filename ?? file.name,
|
|
268
|
+
})
|
|
269
|
+
await refreshWithFollowUps()
|
|
270
|
+
} catch (error) {
|
|
271
|
+
setFailure(error instanceof Error ? error.message : 'Falha ao enviar o arquivo.')
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return (
|
|
276
|
+
<div className="flex h-full min-h-0 flex-col">
|
|
277
|
+
<ConversationWallpaper className="flex-1 min-h-0 overflow-y-auto px-4 py-3">
|
|
278
|
+
{rendered.map(({ message, isFirstInGroup, showDateDivider }) => (
|
|
279
|
+
<div key={message.id}>
|
|
280
|
+
{showDateDivider ? <DateDivider iso={message.timestamp} /> : null}
|
|
281
|
+
<MessageBubble
|
|
282
|
+
message={message}
|
|
283
|
+
// Na visão do cliente, "minha" mensagem é a que ele enviou — inbound do ponto de
|
|
284
|
+
// vista do servidor.
|
|
285
|
+
isMine={message.direction === 'inbound'}
|
|
286
|
+
isFirstInGroup={isFirstInGroup}
|
|
287
|
+
// Só o que o bot ofereceu é tocável: reoferecer as opções da própria mensagem do
|
|
288
|
+
// cliente deixaria o menu clicável para sempre, o que o WhatsApp não faz.
|
|
289
|
+
onInteractiveSelect={
|
|
290
|
+
message.direction === 'outbound' ? (selection) => void handleInteractiveSelect(selection) : undefined
|
|
291
|
+
}
|
|
292
|
+
/>
|
|
293
|
+
</div>
|
|
294
|
+
))}
|
|
295
|
+
<div ref={bottomRef} />
|
|
296
|
+
</ConversationWallpaper>
|
|
297
|
+
|
|
298
|
+
{failure ? (
|
|
299
|
+
<p role="alert" className="px-4 py-2 text-sm text-red-600 dark:text-red-400">
|
|
300
|
+
{failure}
|
|
301
|
+
</p>
|
|
302
|
+
) : null}
|
|
303
|
+
|
|
304
|
+
{/* Separado da falha de ENVIO: são causas diferentes e confundi-las manda o operador
|
|
305
|
+
investigar assinatura de webhook quando o problema é sessão. Amarelo, não vermelho — a
|
|
306
|
+
mensagem foi entregue; o que faltou foi poder ler a conversa de volta. */}
|
|
307
|
+
{loadFailure ? (
|
|
308
|
+
<p role="status" className="px-4 py-2 text-sm text-amber-700 dark:text-amber-400">
|
|
309
|
+
{loadFailure}
|
|
310
|
+
</p>
|
|
311
|
+
) : null}
|
|
312
|
+
|
|
313
|
+
<MessageComposer
|
|
314
|
+
onSend={(text) => void handleSend(text)}
|
|
315
|
+
onAttach={uploadFile ? (file) => void handleAttach(file) : undefined}
|
|
316
|
+
/* Gravando, o campo diz o que falta fazer: o botão é um interruptor e o segundo toque é
|
|
317
|
+
que envia — sem esse aviso o operador grava, não vê nada acontecer e conclui que o
|
|
318
|
+
microfone está quebrado. */
|
|
319
|
+
placeholder={
|
|
320
|
+
isRecording ? 'Gravando… toque no quadrado para ouvir' : (placeholder ?? 'Escreva como o cliente…')
|
|
321
|
+
}
|
|
322
|
+
idleAction={
|
|
323
|
+
uploadFile ? (
|
|
324
|
+
<AudioRecorderButton
|
|
325
|
+
onRecorded={(file) => void handleAttach(file)}
|
|
326
|
+
onFailure={(message) => setFailure(message)}
|
|
327
|
+
onRecordingChange={setIsRecording}
|
|
328
|
+
/>
|
|
329
|
+
) : undefined
|
|
330
|
+
}
|
|
331
|
+
/>
|
|
332
|
+
</div>
|
|
333
|
+
)
|
|
334
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bancada de teste manual de mídia — montável em uma linha por qualquer projeto que adote o SDK.
|
|
3
|
+
*
|
|
4
|
+
* Existe porque o defeito que ela pega não é pegável por teste automatizado: "o PDF abre?" depende
|
|
5
|
+
* do leitor do navegador, "o vídeo toca?" do decodificador, e "a aba abre?" da política do Chrome
|
|
6
|
+
* sobre `data:` URL. Teste unitário confere bytes; só o olho confere que o arquivo abre. Sem uma
|
|
7
|
+
* superfície pronta no pacote, cada projeto teria de montar a sua — e, na prática, nenhum montava.
|
|
8
|
+
*
|
|
9
|
+
* Traz o próprio store, o próprio mock e o próprio provider: o host não injeta nada. E não passa
|
|
10
|
+
* `onResolveMediaUrl` em lugar nenhum de propósito — é o `MessageBubble` resolvendo mídia pelo
|
|
11
|
+
* `ConversationsApi` do contexto, então se essa resolução automática quebrar, esta tela mostra.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { useMemo } from 'react'
|
|
15
|
+
import { ConversationsProvider } from '../providers/ConversationsProvider'
|
|
16
|
+
import { DocumentsLibrary } from '../DocumentsLibrary'
|
|
17
|
+
import { ConversationDocumentsPanel } from '../ConversationDocumentsPanel'
|
|
18
|
+
import { MessageBubble } from '../MessageBubble'
|
|
19
|
+
import { ConversationWallpaper } from '../Wallpaper'
|
|
20
|
+
import { createMockConversationsApi } from './createMockConversationsApi'
|
|
21
|
+
import { createMockSSEProvider } from './createMockSSEProvider'
|
|
22
|
+
import { createPreviewStore } from './previewStore'
|
|
23
|
+
import { PREVIEW_CONVERSATIONS, PREVIEW_DOCUMENTS, PREVIEW_MESSAGES } from './previewFixtures'
|
|
24
|
+
|
|
25
|
+
/** A conversa do fixture que carrega uma mensagem de cada tipo aceito. */
|
|
26
|
+
export const MEDIA_TYPES_CONVERSATION_ID = '5511944443333'
|
|
27
|
+
|
|
28
|
+
export type MediaTypesPreviewProps = {
|
|
29
|
+
/** Outra conversa do fixture, se o projeto tiver acrescentado a sua. */
|
|
30
|
+
conversationId?: string
|
|
31
|
+
className?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function MediaTypesPreview({
|
|
35
|
+
conversationId = MEDIA_TYPES_CONVERSATION_ID,
|
|
36
|
+
className,
|
|
37
|
+
}: MediaTypesPreviewProps) {
|
|
38
|
+
const store = useMemo(
|
|
39
|
+
() => createPreviewStore({ conversations: PREVIEW_CONVERSATIONS, messages: PREVIEW_MESSAGES }),
|
|
40
|
+
[],
|
|
41
|
+
)
|
|
42
|
+
const api = useMemo(() => createMockConversationsApi({ store }), [store])
|
|
43
|
+
const sse = useMemo(() => createMockSSEProvider({ store }), [store])
|
|
44
|
+
|
|
45
|
+
const messages = PREVIEW_MESSAGES[conversationId] ?? []
|
|
46
|
+
const documents = PREVIEW_DOCUMENTS[conversationId] ?? []
|
|
47
|
+
const mimeTypes = [...new Set(documents.map((document) => document.mimeType))]
|
|
48
|
+
|
|
49
|
+
return (
|
|
50
|
+
<ConversationsProvider api={api} sse={sse}>
|
|
51
|
+
<div className={className}>
|
|
52
|
+
<header className="border-b px-4 py-3 dark:border-gray-700">
|
|
53
|
+
<h1 className="text-lg font-semibold">Teste manual de mídia</h1>
|
|
54
|
+
<p className="text-sm text-gray-500">
|
|
55
|
+
{documents.length} arquivos, {mimeTypes.length} tipos. Clique no olho para abrir em aba nova e no
|
|
56
|
+
botão da bolha para carregar a mídia na thread — é o que teste automatizado não vê.
|
|
57
|
+
</p>
|
|
58
|
+
</header>
|
|
59
|
+
|
|
60
|
+
<div className="grid gap-4 p-4 lg:grid-cols-2">
|
|
61
|
+
<section className="space-y-3">
|
|
62
|
+
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-500">Biblioteca da empresa</h2>
|
|
63
|
+
{/* Sem paginar: a bancada serve para ver TODOS os tipos de uma vez. */}
|
|
64
|
+
<DocumentsLibrary perPage={documents.length || 20} />
|
|
65
|
+
</section>
|
|
66
|
+
|
|
67
|
+
<section className="space-y-3">
|
|
68
|
+
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-500">Painel da conversa</h2>
|
|
69
|
+
<ConversationDocumentsPanel conversationId={conversationId} open perPage={documents.length || 20} />
|
|
70
|
+
|
|
71
|
+
<h2 className="text-sm font-semibold uppercase tracking-wide text-gray-500">Bolhas na thread</h2>
|
|
72
|
+
<ConversationWallpaper className="max-h-[70vh] overflow-y-auto rounded-lg px-3 py-2">
|
|
73
|
+
{messages.map((message, index) => (
|
|
74
|
+
<MessageBubble
|
|
75
|
+
key={message.id}
|
|
76
|
+
message={message}
|
|
77
|
+
isMine={message.direction === 'outbound'}
|
|
78
|
+
isFirstInGroup={index === 0 || messages[index - 1]?.sender !== message.sender}
|
|
79
|
+
/>
|
|
80
|
+
))}
|
|
81
|
+
</ConversationWallpaper>
|
|
82
|
+
</section>
|
|
83
|
+
</div>
|
|
84
|
+
</div>
|
|
85
|
+
</ConversationsProvider>
|
|
86
|
+
)
|
|
87
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guarda a classificação de falha do simulador do cliente.
|
|
3
|
+
*
|
|
4
|
+
* O defeito que motivou o arquivo: o `refresh` tratava QUALQUER erro ao ler o transcript como
|
|
5
|
+
* "conversa ainda não existe", mostrava thread vazia e não dizia nada. Com sessão ausente (401) o
|
|
6
|
+
* sintoma era o pior possível — a mensagem ia para o webhook, era aceita, e a tela ficava igual.
|
|
7
|
+
* Quem olhava concluía que o envio estava quebrado.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, expect, it } from 'bun:test'
|
|
11
|
+
|
|
12
|
+
import { describeLoadFailure, isNotFound } from './ConversationPreview'
|
|
13
|
+
|
|
14
|
+
class HttpError extends Error {
|
|
15
|
+
constructor(
|
|
16
|
+
message: string,
|
|
17
|
+
readonly status: number,
|
|
18
|
+
) {
|
|
19
|
+
super(message)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
describe('isNotFound', () => {
|
|
24
|
+
// Primeiro contato: a conversa não existe e transcript vazio é o estado correto, sem alarme.
|
|
25
|
+
it('reconhece 404 como conversa inexistente', () => {
|
|
26
|
+
expect(isNotFound(new HttpError('Conversa não encontrada', 404))).toBe(true)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('não confunde 401 com conversa inexistente', () => {
|
|
30
|
+
expect(isNotFound(new HttpError('Unauthorized', 401))).toBe(false)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('erro sem status não é tratado como inexistente', () => {
|
|
34
|
+
expect(isNotFound(new Error('Failed to fetch'))).toBe(false)
|
|
35
|
+
expect(isNotFound(undefined)).toBe(false)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
// Aceita `statusCode` também: nem todo host nomeia o campo igual.
|
|
39
|
+
it('lê statusCode quando é esse o nome do campo', () => {
|
|
40
|
+
expect(isNotFound({ statusCode: 404 })).toBe(true)
|
|
41
|
+
})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
describe('describeLoadFailure', () => {
|
|
45
|
+
it('explica que falta sessão e que a mensagem FOI entregue', () => {
|
|
46
|
+
const mensagem = describeLoadFailure(new HttpError('Unauthorized', 401))
|
|
47
|
+
|
|
48
|
+
expect(mensagem).toContain('Sem sessão')
|
|
49
|
+
// O ponto central: não deixar o operador achar que o envio falhou.
|
|
50
|
+
expect(mensagem).toContain('entregue no webhook')
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('trata 403 igual a 401', () => {
|
|
54
|
+
expect(describeLoadFailure(new HttpError('Forbidden', 403))).toContain('Sem sessão')
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('preserva a mensagem do host em falha genérica', () => {
|
|
58
|
+
expect(describeLoadFailure(new HttpError('API fora do ar', 500))).toContain('API fora do ar')
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('tem texto para erro sem mensagem', () => {
|
|
62
|
+
expect(describeLoadFailure({}).length).toBeGreaterThan(0)
|
|
63
|
+
})
|
|
64
|
+
})
|