@orbe-agro/client-core 5.6.337 → 5.6.338

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.
Files changed (48) hide show
  1. package/dist/@ecme/assets/styles/app.css +13 -0
  2. package/dist/@ecme/assets/styles/tailwind/index.css +13 -0
  3. package/dist/@ecme/components/template/Footer.js +1 -1
  4. package/dist/@ecme/components/view/ChatBox/ChatBox.js +3 -1
  5. package/dist/@ecme/components/view/ChatBox/ChatBox.js.map +1 -1
  6. package/dist/@ecme/components/view/ChatBox/components/ChatInput.js +16 -14
  7. package/dist/@ecme/components/view/ChatBox/components/ChatInput.js.map +1 -1
  8. package/dist/@ecme/index.js +2 -1
  9. package/dist/@ecme/services/AiService.js +13 -1
  10. package/dist/@ecme/services/AiService.js.map +1 -1
  11. package/dist/@ecme/services/index.js +2 -1
  12. package/dist/@ecme/views/concepts/ai/Chat/components/ChatView.js +11 -3
  13. package/dist/@ecme/views/concepts/ai/Chat/components/ChatView.js.map +1 -1
  14. package/dist/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.js +35 -0
  15. package/dist/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.js.map +1 -0
  16. package/dist/@ecme/views/concepts/ai/Chat/hooks/useChatSend.js +14 -11
  17. package/dist/@ecme/views/concepts/ai/Chat/hooks/useChatSend.js.map +1 -1
  18. package/dist/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.js +31 -0
  19. package/dist/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.js.map +1 -0
  20. package/dist/@ecme/views/concepts/ai/Chat/imagens.js +57 -0
  21. package/dist/@ecme/views/concepts/ai/Chat/imagens.js.map +1 -0
  22. package/dist/@types/@ecme/components/view/ChatBox/ChatBox.d.ts.map +1 -1
  23. package/dist/@types/@ecme/components/view/ChatBox/components/ChatInput.d.ts +3 -0
  24. package/dist/@types/@ecme/components/view/ChatBox/components/ChatInput.d.ts.map +1 -1
  25. package/dist/@types/@ecme/services/AiService.d.ts +12 -2
  26. package/dist/@types/@ecme/services/AiService.d.ts.map +1 -1
  27. package/dist/@types/@ecme/views/concepts/ai/Chat/components/ChatView.d.ts.map +1 -1
  28. package/dist/@types/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.d.ts +13 -0
  29. package/dist/@types/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.d.ts.map +1 -0
  30. package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useChatSend.d.ts +1 -1
  31. package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useChatSend.d.ts.map +1 -1
  32. package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.d.ts +16 -0
  33. package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.d.ts.map +1 -0
  34. package/dist/@types/@ecme/views/concepts/ai/Chat/imagens.d.ts +27 -0
  35. package/dist/@types/@ecme/views/concepts/ai/Chat/imagens.d.ts.map +1 -0
  36. package/dist/@types/@ecme/views/concepts/ai/Chat/types.d.ts +38 -0
  37. package/dist/@types/@ecme/views/concepts/ai/Chat/types.d.ts.map +1 -1
  38. package/dist/base/assets/styles/init.css +13 -0
  39. package/lib/@ecme/components/view/ChatBox/ChatBox.tsx +2 -0
  40. package/lib/@ecme/components/view/ChatBox/components/ChatInput.tsx +20 -14
  41. package/lib/@ecme/services/AiService.ts +27 -2
  42. package/lib/@ecme/views/concepts/ai/Chat/components/ChatView.tsx +13 -3
  43. package/lib/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.tsx +54 -0
  44. package/lib/@ecme/views/concepts/ai/Chat/hooks/useChatSend.ts +33 -11
  45. package/lib/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.ts +53 -0
  46. package/lib/@ecme/views/concepts/ai/Chat/imagens.ts +86 -0
  47. package/lib/@ecme/views/concepts/ai/Chat/types.ts +42 -0
  48. package/package.json +1 -1
@@ -13,6 +13,8 @@ import ToolCallChip from './ToolCallChip'
13
13
  import ApprovalCard from './ApprovalCard'
14
14
  import DataRequestCard from './DataRequestCard'
15
15
  import EsforcoRaciocinio from './EsforcoRaciocinio'
16
+ import ImagensDaMensagem from './ImagensDaMensagem'
17
+ import { UPLOAD_DE_IMAGENS } from '../imagens'
16
18
  import { usGenerativeChatStore } from '../store/generativeChatStore'
17
19
  import useChatSend from '../hooks/useChatSend'
18
20
  import useConversationMessages from '../hooks/useConversationMessages'
@@ -81,11 +83,12 @@ const ChatView = ({
81
83
 
82
84
  const handleInputChange = async ({
83
85
  value,
86
+ attachments,
84
87
  }: {
85
88
  value: string
86
- attachments?: File[]
89
+ attachments: File[]
87
90
  }) => {
88
- await handleSend(value)
91
+ await handleSend(value, attachments)
89
92
  }
90
93
 
91
94
  const handleFinish = (id: string) => {
@@ -221,7 +224,13 @@ const ChatView = ({
221
224
  )
222
225
  }
223
226
 
224
- return message.content
227
+ const { imagens } = message as Conversation
228
+ return (
229
+ <div className="flex flex-col gap-2">
230
+ <ImagensDaMensagem imagens={imagens} />
231
+ {message.content}
232
+ </div>
233
+ )
225
234
  }}
226
235
  customAction={(message) => {
227
236
  if (message.sender.id === 'ai' && !message.isError) {
@@ -235,6 +244,7 @@ const ChatView = ({
235
244
  return null
236
245
  }}
237
246
  onInputChange={handleInputChange}
247
+ uploadProps={UPLOAD_DE_IMAGENS}
238
248
  inputActions={
239
249
  <EsforcoRaciocinio floatingClass={dropdownFloatingClass} />
240
250
  }
@@ -0,0 +1,54 @@
1
+ import { TbPhotoOff } from 'react-icons/tb'
2
+ import Skeleton from '@/components/ui/Skeleton'
3
+ import useImagemDoStorage from '../hooks/useImagemDoStorage'
4
+ import type { ImagemDaMensagem } from '../types'
5
+
6
+ const MINIATURA = 'h-40 max-w-[240px] rounded-lg object-cover'
7
+
8
+ const Miniatura = ({ imagem }: { imagem: ImagemDaMensagem }) => {
9
+ const { src, carregando, falhou } = useImagemDoStorage(imagem)
10
+
11
+ if (carregando) {
12
+ return <Skeleton width={160} height={160} className="rounded-lg" />
13
+ }
14
+
15
+ if (falhou || !src) {
16
+ return (
17
+ <div className="flex h-40 w-40 flex-col items-center justify-center gap-1 rounded-lg bg-white/10 text-xs">
18
+ <TbPhotoOff className="text-2xl" />
19
+ Imagem indisponível
20
+ </div>
21
+ )
22
+ }
23
+
24
+ return <img className={MINIATURA} src={src} alt="Imagem enviada" />
25
+ }
26
+
27
+ type ImagensDaMensagemProps = {
28
+ imagens?: ImagemDaMensagem[]
29
+ }
30
+
31
+ /**
32
+ * As imagens que o usuário enviou, em miniatura, acima do texto da mensagem.
33
+ *
34
+ * Serve a mensagem recém-enviada (blob local) e a que veio do histórico
35
+ * (baixada do object storage) - quem resolve de onde vem é o hook.
36
+ */
37
+ const ImagensDaMensagem = ({ imagens }: ImagensDaMensagemProps) => {
38
+ if (!imagens?.length) {
39
+ return null
40
+ }
41
+
42
+ return (
43
+ <div className="flex flex-wrap gap-2">
44
+ {imagens.map((imagem, indice) => (
45
+ <Miniatura
46
+ key={imagem.objectName ?? imagem.url ?? indice}
47
+ imagem={imagem}
48
+ />
49
+ ))}
50
+ </div>
51
+ )
52
+ }
53
+
54
+ export default ImagensDaMensagem
@@ -5,6 +5,11 @@ import { useAuth } from '@/auth'
5
5
  import dayjs from 'dayjs'
6
6
  import uniqueId from 'lodash/uniqueId'
7
7
  import { novoIdDeConversa } from '../utils'
8
+ import {
9
+ TITULO_SO_IMAGEM,
10
+ paraImagemEnviada,
11
+ paraImagensDaMensagem,
12
+ } from '../imagens'
8
13
  import type { ChatEvent, Conversation, ToolCall } from '../types'
9
14
 
10
15
  /** Resposta genérica exibida no chat quando a comunicação com a IA falha. */
@@ -24,7 +29,7 @@ const useChatSend = () => {
24
29
  // Vai em toda ida ao modelo: envio, aprovação e formulário.
25
30
  const esforco = useEsforcoStore((state) => state.esforco)
26
31
 
27
- const creteMyMessage = (id: string, prompt: string) => {
32
+ const creteMyMessage = (id: string, prompt: string, imagens: File[]) => {
28
33
  pushConversation(id, {
29
34
  id: uniqueId('ai-conversation-'),
30
35
  sender: {
@@ -33,6 +38,7 @@ const useChatSend = () => {
33
38
  avatarImageUrl: user.avatar ?? undefined,
34
39
  },
35
40
  content: prompt,
41
+ imagens: paraImagensDaMensagem(imagens),
36
42
  timestamp: dayjs().toDate(),
37
43
  type: 'regular',
38
44
  isMyMessage: true,
@@ -192,44 +198,60 @@ const useChatSend = () => {
192
198
  }
193
199
  }
194
200
 
195
- const sendMessage = async (chatId: string, prompt: string) => {
201
+ /**
202
+ * A conversão para base64 roda dentro do `executar`: se a leitura de um
203
+ * arquivo falhar, cai no mesmo `catch` de uma falha de rede e vira a
204
+ * mensagem de erro do chat.
205
+ */
206
+ const sendMessage = async (
207
+ chatId: string,
208
+ prompt: string,
209
+ imagens: File[],
210
+ ) => {
196
211
  const messageId = createAiMessage(chatId)
197
212
  await consumirStream(
198
213
  chatId,
199
214
  messageId,
200
- (onEvent) =>
215
+ async (onEvent) =>
201
216
  streamChat({
202
217
  prompt,
203
218
  conversationId: chatId,
204
219
  esforco,
220
+ imagens: imagens.length
221
+ ? await Promise.all(imagens.map(paraImagemEnviada))
222
+ : undefined,
205
223
  onEvent,
206
224
  }),
207
225
  { texto: '', tools: [] },
208
226
  )
209
227
  }
210
228
 
211
- const createConversation = async (chatId: string, prompt: string) => {
229
+ const createConversation = async (
230
+ chatId: string,
231
+ prompt: string,
232
+ imagens: File[],
233
+ ) => {
212
234
  setSelectedConversation(chatId)
213
- await sendMessage(chatId, prompt)
235
+ await sendMessage(chatId, prompt, imagens)
214
236
  }
215
237
 
216
- const handleSend = async (prompt: string) => {
238
+ const handleSend = async (prompt: string, imagens: File[] = []) => {
217
239
  setIsTyping(true)
218
240
  if (selectedConversation) {
219
- creteMyMessage(selectedConversation, prompt)
220
- await sendMessage(selectedConversation, prompt)
241
+ creteMyMessage(selectedConversation, prompt, imagens)
242
+ await sendMessage(selectedConversation, prompt, imagens)
221
243
  } else {
222
244
  const newId = novoIdDeConversa()
223
245
  pushChatHistory({
224
246
  id: newId,
225
- title: prompt,
247
+ title: prompt.trim() || TITULO_SO_IMAGEM,
226
248
  lastConversation: '',
227
249
  createdTime: dayjs().unix(),
228
250
  updatedTime: dayjs().unix(),
229
251
  enable: true,
230
252
  })
231
- creteMyMessage(newId, prompt)
232
- await createConversation(newId, prompt)
253
+ creteMyMessage(newId, prompt, imagens)
254
+ await createConversation(newId, prompt, imagens)
233
255
  }
234
256
  }
235
257
 
@@ -0,0 +1,53 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { apiGetImagemDoChat } from '@/services/AiService'
3
+ import type { ImagemDaMensagem } from '../types'
4
+
5
+ type EstadoDaImagem = {
6
+ src?: string
7
+ carregando: boolean
8
+ falhou: boolean
9
+ }
10
+
11
+ /**
12
+ * O endereço que a `<img>` usa para uma imagem da mensagem.
13
+ *
14
+ * A que acabou de ser enviada já tem o blob local (`url`). A que veio do
15
+ * histórico tem só o `objectName`, e é baixada aqui do object storage: o
16
+ * download exige o JWT, então a `<img>` não pode apontar direto para ele.
17
+ */
18
+ const useImagemDoStorage = ({
19
+ url,
20
+ objectName,
21
+ }: ImagemDaMensagem): EstadoDaImagem => {
22
+ const [baixada, setBaixada] = useState<string>()
23
+ const [falhou, setFalhou] = useState(false)
24
+
25
+ const precisaBaixar = !url && Boolean(objectName)
26
+
27
+ useEffect(() => {
28
+ if (!precisaBaixar || !objectName) {
29
+ return
30
+ }
31
+
32
+ // A mensagem pode sair da tela antes do download terminar.
33
+ let cancelado = false
34
+ setFalhou(false)
35
+
36
+ apiGetImagemDoChat(objectName)
37
+ .then(({ contentType, bytes }) => {
38
+ if (!cancelado) setBaixada(`data:${contentType};base64,${bytes}`)
39
+ })
40
+ .catch(() => {
41
+ if (!cancelado) setFalhou(true)
42
+ })
43
+
44
+ return () => {
45
+ cancelado = true
46
+ }
47
+ }, [precisaBaixar, objectName])
48
+
49
+ const src = url ?? baixada
50
+ return { src, carregando: precisaBaixar && !src && !falhou, falhou }
51
+ }
52
+
53
+ export default useImagemDoStorage
@@ -0,0 +1,86 @@
1
+ import type { UploadProps } from '@/components/ui/Upload'
2
+ import type { ImagemDaMensagem, ImagemEnviada, TipoDeImagem } from './types'
3
+
4
+ /**
5
+ * Imagens no chat de IA: o que o seletor aceita, como a imagem vai ao backend
6
+ * e como ela aparece na mensagem.
7
+ *
8
+ * Os limites espelham os do backend (`settings.py`: `chat_max_imagens` e
9
+ * `chat_max_bytes_por_imagem`; `imagem.py`: `TipoDeImagem`). A validacao aqui
10
+ * so evita a viagem: quem decide e o backend, que responde 422 fora deles.
11
+ */
12
+
13
+ export const TIPOS_DE_IMAGEM: ReadonlyArray<TipoDeImagem> = [
14
+ 'image/png',
15
+ 'image/jpeg',
16
+ 'image/webp',
17
+ ]
18
+
19
+ export const MAX_IMAGENS = 3
20
+
21
+ export const MAX_BYTES_POR_IMAGEM = 5 * 1024 * 1024
22
+
23
+ /** Titulo da conversa aberta so com imagem; o mesmo texto do backend. */
24
+ export const TITULO_SO_IMAGEM = 'Imagem enviada'
25
+
26
+ const ehTipoDeImagem = (tipo: string): tipo is TipoDeImagem =>
27
+ TIPOS_DE_IMAGEM.some((aceito) => aceito === tipo)
28
+
29
+ /**
30
+ * Confere as imagens escolhidas antes de entrarem na caixa de mensagem.
31
+ *
32
+ * Assinatura do `beforeUpload` do `Upload`: a string devolvida vira o toast
33
+ * de erro, e o arquivo nao entra.
34
+ */
35
+ const validarImagens: UploadProps['beforeUpload'] = (novas, atuais) => {
36
+ const arquivos = Array.from(novas ?? [])
37
+
38
+ if (arquivos.length + atuais.length > MAX_IMAGENS) {
39
+ return `Envie no máximo ${MAX_IMAGENS} imagens por mensagem.`
40
+ }
41
+ if (arquivos.some((arquivo) => !ehTipoDeImagem(arquivo.type))) {
42
+ return 'Envie imagens PNG, JPEG ou WEBP.'
43
+ }
44
+ if (arquivos.some((arquivo) => arquivo.size > MAX_BYTES_POR_IMAGEM)) {
45
+ return `Cada imagem pode ter até ${MAX_BYTES_POR_IMAGEM / (1024 * 1024)} MB.`
46
+ }
47
+ return true
48
+ }
49
+
50
+ /** Configuracao do seletor de imagens da caixa de mensagem. */
51
+ export const UPLOAD_DE_IMAGENS: Pick<UploadProps, 'accept' | 'beforeUpload'> = {
52
+ accept: TIPOS_DE_IMAGEM.join(','),
53
+ beforeUpload: validarImagens,
54
+ }
55
+
56
+ /** As imagens como a bolha do usuario mostra logo apos o envio. */
57
+ export const paraImagensDaMensagem = (arquivos: File[]): ImagemDaMensagem[] =>
58
+ arquivos.map((arquivo) => ({
59
+ mimeType: arquivo.type,
60
+ url: URL.createObjectURL(arquivo),
61
+ }))
62
+
63
+ /**
64
+ * A imagem como vai no corpo do /ai/chat/stream.
65
+ *
66
+ * O `readAsDataURL` devolve `data:<mime>;base64,<conteudo>`; o backend espera
67
+ * so o conteudo.
68
+ */
69
+ export const paraImagemEnviada = (arquivo: File): Promise<ImagemEnviada> =>
70
+ new Promise((resolve, reject) => {
71
+ if (!ehTipoDeImagem(arquivo.type)) {
72
+ reject(new Error(`Formato de imagem nao aceito: ${arquivo.type}`))
73
+ return
74
+ }
75
+ const mimeType = arquivo.type
76
+ const leitor = new FileReader()
77
+ leitor.onload = () => {
78
+ const dataUrl = String(leitor.result)
79
+ resolve({
80
+ mime_type: mimeType,
81
+ base64: dataUrl.slice(dataUrl.indexOf(',') + 1),
82
+ })
83
+ }
84
+ leitor.onerror = () => reject(leitor.error)
85
+ leitor.readAsDataURL(arquivo)
86
+ })
@@ -51,6 +51,14 @@ export type Conversation = {
51
51
  mediaUrl: string
52
52
  }>
53
53
  isMyMessage?: boolean
54
+ /**
55
+ * Imagens enviadas pelo usuario nesta mensagem.
56
+ *
57
+ * Campo proprio do chat de IA, e nao o `attachments` do template: aquele
58
+ * exige o `File`, e a mensagem vinda do historico so tem a referencia no
59
+ * object storage.
60
+ */
61
+ imagens?: ImagemDaMensagem[]
54
62
  /**
55
63
  * Liga a animacao de maquina de escrever do ChatCustomContent.
56
64
  *
@@ -187,6 +195,40 @@ export type HistoryChat = Omit<ChatHistory, 'conversation'> & {
187
195
  */
188
196
  export type Esforco = 'minimal' | 'medium' | 'high' | 'max'
189
197
 
198
+ /**
199
+ * Formatos de imagem aceitos no chat.
200
+ *
201
+ * O mesmo conjunto do backend (enum `TipoDeImagem`, em `imagem.py`): qualquer
202
+ * outro volta 422.
203
+ */
204
+ export type TipoDeImagem = 'image/png' | 'image/jpeg' | 'image/webp'
205
+
206
+ /** Imagem como vai no corpo do /ai/chat/stream: base64 sem o prefixo `data:`. */
207
+ export type ImagemEnviada = {
208
+ mime_type: TipoDeImagem
209
+ base64: string
210
+ }
211
+
212
+ /**
213
+ * Imagem exibida numa mensagem do usuario.
214
+ *
215
+ * Logo apos o envio ela vem do proprio arquivo (`url`, um blob local). No
216
+ * historico vem so a referencia no object storage (`objectName`), baixada
217
+ * quando a mensagem aparece.
218
+ */
219
+ export type ImagemDaMensagem = {
220
+ mimeType: string
221
+ url?: string
222
+ objectName?: string
223
+ }
224
+
225
+ /** Arquivo como o object storage devolve no download: `bytes` em base64. */
226
+ export type ArquivoDoStorage = {
227
+ contentType: string
228
+ bytes: string
229
+ fileName: string
230
+ }
231
+
190
232
  /** Resumo de uma conversa, como vem do GET /ai/chat/conversations. */
191
233
  export type ConversationSummary = {
192
234
  id: string
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orbe-agro/client-core",
3
- "version": "5.6.337",
3
+ "version": "5.6.338",
4
4
  "description": "Biblioteca principal de componentes e utilidades para os microfrontends do Orbe Agro.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",