@orbe-agro/client-core 5.6.343 → 5.6.345
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/@ecme/assets/styles/app.css +52 -26
- package/dist/@ecme/assets/styles/tailwind/index.css +52 -26
- package/dist/@ecme/components/template/Footer.js +1 -1
- package/dist/@ecme/components/view/ChatBox/ChatBox.js +3 -1
- package/dist/@ecme/components/view/ChatBox/ChatBox.js.map +1 -1
- package/dist/@ecme/components/view/ChatBox/components/ChatInput.js +19 -16
- package/dist/@ecme/components/view/ChatBox/components/ChatInput.js.map +1 -1
- package/dist/@ecme/index.js +3 -1
- package/dist/@ecme/services/AiService.js +31 -2
- package/dist/@ecme/services/AiService.js.map +1 -1
- package/dist/@ecme/services/index.js +3 -1
- package/dist/@ecme/views/concepts/ai/Chat/components/ChatView.js +55 -43
- package/dist/@ecme/views/concepts/ai/Chat/components/ChatView.js.map +1 -1
- package/dist/@ecme/views/concepts/ai/Chat/components/FormatoCard.js +81 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/FormatoCard.js.map +1 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.js +35 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.js.map +1 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/ModeloERaciocinio.js +142 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/ModeloERaciocinio.js.map +1 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/PlanilhaNaMensagem.js +47 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/PlanilhaNaMensagem.js.map +1 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/RelatorioNaMensagem.js +64 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/RelatorioNaMensagem.js.map +1 -0
- package/dist/@ecme/views/concepts/ai/Chat/components/ToolCallChip.js +9 -4
- package/dist/@ecme/views/concepts/ai/Chat/components/ToolCallChip.js.map +1 -1
- package/dist/@ecme/views/concepts/ai/Chat/components/toolPresentation.js +18 -1
- package/dist/@ecme/views/concepts/ai/Chat/components/toolPresentation.js.map +1 -1
- package/dist/@ecme/views/concepts/ai/Chat/hooks/useChatSend.js +96 -51
- package/dist/@ecme/views/concepts/ai/Chat/hooks/useChatSend.js.map +1 -1
- package/dist/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.js +31 -0
- package/dist/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.js.map +1 -0
- package/dist/@ecme/views/concepts/ai/Chat/hooks/useModelos.js +31 -0
- package/dist/@ecme/views/concepts/ai/Chat/hooks/useModelos.js.map +1 -0
- package/dist/@ecme/views/concepts/ai/Chat/imagens.js +57 -0
- package/dist/@ecme/views/concepts/ai/Chat/imagens.js.map +1 -0
- package/dist/@ecme/views/concepts/ai/Chat/store/modeloStore.js +15 -0
- package/dist/@ecme/views/concepts/ai/Chat/store/modeloStore.js.map +1 -0
- package/dist/@types/@ecme/components/view/ChatBox/ChatBox.d.ts.map +1 -1
- package/dist/@types/@ecme/components/view/ChatBox/components/ChatInput.d.ts +3 -0
- package/dist/@types/@ecme/components/view/ChatBox/components/ChatInput.d.ts.map +1 -1
- package/dist/@types/@ecme/services/AiService.d.ts +25 -5
- package/dist/@types/@ecme/services/AiService.d.ts.map +1 -1
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/ChatView.d.ts.map +1 -1
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/FormatoCard.d.ts +16 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/FormatoCard.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.d.ts +13 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/ModeloERaciocinio.d.ts +16 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/ModeloERaciocinio.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/PlanilhaNaMensagem.d.ts +14 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/PlanilhaNaMensagem.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/RelatorioNaMensagem.d.ts +15 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/RelatorioNaMensagem.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/ToolCallChip.d.ts.map +1 -1
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/toolPresentation.d.ts.map +1 -1
- package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useChatSend.d.ts +3 -1
- package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useChatSend.d.ts.map +1 -1
- package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.d.ts +16 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useModelos.d.ts +26 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/hooks/useModelos.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/imagens.d.ts +27 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/imagens.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/store/modeloStore.d.ts +27 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/store/modeloStore.d.ts.map +1 -0
- package/dist/@types/@ecme/views/concepts/ai/Chat/types.d.ts +148 -24
- package/dist/@types/@ecme/views/concepts/ai/Chat/types.d.ts.map +1 -1
- package/dist/@types/base/configs/endpoints.config/endpoints.navigation.d.ts +8 -0
- package/dist/@types/base/configs/endpoints.config/endpoints.navigation.d.ts.map +1 -1
- package/dist/@types/base/configs/endpoints.config/transportadora/contratoFrete.d.ts +8 -0
- package/dist/@types/base/configs/endpoints.config/transportadora/contratoFrete.d.ts.map +1 -1
- package/dist/@types/base/services/modules/transportadora/ContratoFrete/ContratoFreteService.d.ts +2 -0
- package/dist/@types/base/services/modules/transportadora/ContratoFrete/ContratoFreteService.d.ts.map +1 -1
- package/dist/base/assets/styles/init.css +59 -30
- package/dist/base/configs/endpoints.config/transportadora/contratoFrete.js +3 -1
- package/dist/base/configs/endpoints.config/transportadora/contratoFrete.js.map +1 -1
- package/dist/base/index.js +3 -1
- package/dist/base/services/index.js +3 -1
- package/dist/base/services/modules/index.js +3 -1
- package/dist/base/services/modules/transportadora/ContratoFrete/ContratoFreteService.js +14 -0
- package/dist/base/services/modules/transportadora/ContratoFrete/ContratoFreteService.js.map +1 -1
- package/dist/base/services/modules/transportadora/index.js +3 -1
- package/lib/@ecme/components/view/ChatBox/ChatBox.tsx +2 -0
- package/lib/@ecme/components/view/ChatBox/components/ChatInput.tsx +23 -16
- package/lib/@ecme/services/AiService.ts +57 -5
- package/lib/@ecme/views/concepts/ai/Chat/components/ChatView.tsx +59 -40
- package/lib/@ecme/views/concepts/ai/Chat/components/FormatoCard.tsx +123 -0
- package/lib/@ecme/views/concepts/ai/Chat/components/ImagensDaMensagem.tsx +54 -0
- package/lib/@ecme/views/concepts/ai/Chat/components/ModeloERaciocinio.tsx +200 -0
- package/lib/@ecme/views/concepts/ai/Chat/components/PlanilhaNaMensagem.tsx +65 -0
- package/lib/@ecme/views/concepts/ai/Chat/components/RelatorioNaMensagem.tsx +77 -0
- package/lib/@ecme/views/concepts/ai/Chat/components/ToolCallChip.tsx +18 -9
- package/lib/@ecme/views/concepts/ai/Chat/components/toolPresentation.ts +20 -0
- package/lib/@ecme/views/concepts/ai/Chat/hooks/useChatSend.ts +193 -78
- package/lib/@ecme/views/concepts/ai/Chat/hooks/useImagemDoStorage.ts +53 -0
- package/lib/@ecme/views/concepts/ai/Chat/hooks/useModelos.ts +63 -0
- package/lib/@ecme/views/concepts/ai/Chat/imagens.ts +86 -0
- package/lib/@ecme/views/concepts/ai/Chat/store/modeloStore.ts +25 -0
- package/lib/@ecme/views/concepts/ai/Chat/types.ts +157 -24
- package/lib/base/configs/endpoints.config/transportadora/contratoFrete.ts +2 -0
- package/lib/base/services/modules/transportadora/ContratoFrete/ContratoFreteService.ts +14 -0
- package/package.json +1 -1
- package/dist/@ecme/views/concepts/ai/Chat/components/EsforcoRaciocinio.js +0 -85
- package/dist/@ecme/views/concepts/ai/Chat/components/EsforcoRaciocinio.js.map +0 -1
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/EsforcoRaciocinio.d.ts +0 -14
- package/dist/@types/@ecme/views/concepts/ai/Chat/components/EsforcoRaciocinio.d.ts.map +0 -1
- package/lib/@ecme/views/concepts/ai/Chat/components/EsforcoRaciocinio.tsx +0 -115
|
@@ -1,16 +1,63 @@
|
|
|
1
1
|
import { usGenerativeChatStore } from '../store/generativeChatStore'
|
|
2
2
|
import { useEsforcoStore } from '../store/esforcoStore'
|
|
3
|
+
import useModelos from './useModelos'
|
|
3
4
|
import { resumeChat, streamChat } from '@/services/AiService'
|
|
5
|
+
import type { ResumeChatParams } from '@/services/AiService'
|
|
4
6
|
import { useAuth } from '@/auth'
|
|
5
7
|
import dayjs from 'dayjs'
|
|
6
8
|
import uniqueId from 'lodash/uniqueId'
|
|
7
9
|
import { novoIdDeConversa } from '../utils'
|
|
8
|
-
import
|
|
10
|
+
import {
|
|
11
|
+
TITULO_SO_IMAGEM,
|
|
12
|
+
paraImagemEnviada,
|
|
13
|
+
paraImagensDaMensagem,
|
|
14
|
+
} from '../imagens'
|
|
15
|
+
import type {
|
|
16
|
+
ChatEvent,
|
|
17
|
+
Conversation,
|
|
18
|
+
Espera,
|
|
19
|
+
FormatoDoRelatorio,
|
|
20
|
+
RelatorioDoChat,
|
|
21
|
+
ToolCall,
|
|
22
|
+
} from '../types'
|
|
9
23
|
|
|
10
24
|
/** Resposta genérica exibida no chat quando a comunicação com a IA falha. */
|
|
11
25
|
const AI_ERROR_MESSAGE =
|
|
12
26
|
'Desculpe, estou com um pequeno problema de comunicação e não consigo te atender no momento. Tente novamente em instantes.'
|
|
13
27
|
|
|
28
|
+
/** As pausas que a retomada responde, pelo campo que cada uma ocupa na mensagem. */
|
|
29
|
+
type Pendencia = 'pendingApproval' | 'pendingInput' | 'pendingFormat'
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* As ferramentas `ids` param de girar: não estão executando, estão esperando o
|
|
33
|
+
* usuário responder a pausa — senão o chip giraria para sempre.
|
|
34
|
+
*/
|
|
35
|
+
const pausar = (tools: ToolCall[], ids: string[], espera: Espera) => {
|
|
36
|
+
const pausadas = new Set(ids)
|
|
37
|
+
return tools.map((tool) =>
|
|
38
|
+
pausadas.has(tool.id)
|
|
39
|
+
? { ...tool, running: false, aguardando: espera }
|
|
40
|
+
: tool,
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* As ferramentas que a falha deixou no meio — girando ou esperando o usuário —
|
|
46
|
+
* terminam como "Não concluída". As que já tinham terminado ficam como estavam.
|
|
47
|
+
*/
|
|
48
|
+
const encerrar = (tools: ToolCall[]) =>
|
|
49
|
+
tools.map((tool) =>
|
|
50
|
+
tool.running || tool.aguardando
|
|
51
|
+
? {
|
|
52
|
+
...tool,
|
|
53
|
+
running: false,
|
|
54
|
+
aguardando: undefined,
|
|
55
|
+
progresso: undefined,
|
|
56
|
+
isError: true,
|
|
57
|
+
}
|
|
58
|
+
: tool,
|
|
59
|
+
)
|
|
60
|
+
|
|
14
61
|
const useChatSend = () => {
|
|
15
62
|
const { user } = useAuth()
|
|
16
63
|
const {
|
|
@@ -21,10 +68,11 @@ const useChatSend = () => {
|
|
|
21
68
|
updateConversation,
|
|
22
69
|
setIsTyping,
|
|
23
70
|
} = usGenerativeChatStore()
|
|
24
|
-
//
|
|
71
|
+
// Os dois vão em toda ida ao modelo: envio, aprovação e formulário.
|
|
25
72
|
const esforco = useEsforcoStore((state) => state.esforco)
|
|
73
|
+
const modelo = useModelos().escolhido?.id
|
|
26
74
|
|
|
27
|
-
const creteMyMessage = (id: string, prompt: string) => {
|
|
75
|
+
const creteMyMessage = (id: string, prompt: string, imagens: File[]) => {
|
|
28
76
|
pushConversation(id, {
|
|
29
77
|
id: uniqueId('ai-conversation-'),
|
|
30
78
|
sender: {
|
|
@@ -33,6 +81,7 @@ const useChatSend = () => {
|
|
|
33
81
|
avatarImageUrl: user.avatar ?? undefined,
|
|
34
82
|
},
|
|
35
83
|
content: prompt,
|
|
84
|
+
imagens: paraImagensDaMensagem(imagens),
|
|
36
85
|
timestamp: dayjs().toDate(),
|
|
37
86
|
type: 'regular',
|
|
38
87
|
isMyMessage: true,
|
|
@@ -72,20 +121,53 @@ const useChatSend = () => {
|
|
|
72
121
|
/**
|
|
73
122
|
* Consome um stream escrevendo numa mensagem que já existe.
|
|
74
123
|
*
|
|
75
|
-
* Compartilhado pelo envio e
|
|
76
|
-
*
|
|
124
|
+
* Compartilhado pelo envio e pelas retomadas: quando o usuário responde a
|
|
125
|
+
* uma pausa, a resposta continua na MESMA mensagem, então o acumulador de
|
|
77
126
|
* texto e de ferramentas precisa partir do que já está lá.
|
|
78
127
|
*/
|
|
79
128
|
const consumirStream = async (
|
|
80
129
|
chatId: string,
|
|
81
130
|
messageId: string,
|
|
82
131
|
executar: (onEvent: (evento: ChatEvent) => void) => Promise<void>,
|
|
83
|
-
inicial: {
|
|
132
|
+
inicial: {
|
|
133
|
+
texto: string
|
|
134
|
+
tools: ToolCall[]
|
|
135
|
+
relatorios: RelatorioDoChat[]
|
|
136
|
+
},
|
|
84
137
|
) => {
|
|
85
138
|
// Acumulados localmente: o store guarda o resultado, mas ler de volta a
|
|
86
139
|
// cada token para concatenar seria uma corrida com o próprio set().
|
|
87
140
|
let texto = inicial.texto
|
|
88
141
|
let tools = inicial.tools
|
|
142
|
+
let relatorios = inicial.relatorios
|
|
143
|
+
// Um stream só termina bem com `done` ou com uma pausa. Acabar sem
|
|
144
|
+
// nenhum dos dois é conexão cortada no meio — e vira falha.
|
|
145
|
+
let terminou = false
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Encerra a resposta com erro, sem apagar o que já chegou.
|
|
149
|
+
*
|
|
150
|
+
* Um caminho só para os três jeitos de falhar: o evento `error`, a
|
|
151
|
+
* requisição que cai e o stream que acaba sem `done` nem pausa. As
|
|
152
|
+
* ferramentas que ainda giravam ou esperavam param como "Não concluída"
|
|
153
|
+
* — senão o chip ficava "Aguardando o formato" para sempre. Sem nada na
|
|
154
|
+
* mensagem, ela vira o aviso de erro, como antes.
|
|
155
|
+
*/
|
|
156
|
+
const falhar = () => {
|
|
157
|
+
terminou = true
|
|
158
|
+
tools = encerrar(tools)
|
|
159
|
+
const chegouAlgo =
|
|
160
|
+
Boolean(texto.trim()) ||
|
|
161
|
+
tools.length > 0 ||
|
|
162
|
+
relatorios.length > 0
|
|
163
|
+
updateConversation(
|
|
164
|
+
chatId,
|
|
165
|
+
messageId,
|
|
166
|
+
chegouAlgo
|
|
167
|
+
? { content: texto, tools, falhou: true }
|
|
168
|
+
: { content: AI_ERROR_MESSAGE, isError: true },
|
|
169
|
+
)
|
|
170
|
+
}
|
|
89
171
|
|
|
90
172
|
const aplicar = (evento: ChatEvent) => {
|
|
91
173
|
switch (evento.type) {
|
|
@@ -113,7 +195,8 @@ const useChatSend = () => {
|
|
|
113
195
|
? {
|
|
114
196
|
...tool,
|
|
115
197
|
running: false,
|
|
116
|
-
|
|
198
|
+
aguardando: undefined,
|
|
199
|
+
progresso: undefined,
|
|
117
200
|
result: evento.data.content,
|
|
118
201
|
isError: evento.data.is_error,
|
|
119
202
|
}
|
|
@@ -122,38 +205,61 @@ const useChatSend = () => {
|
|
|
122
205
|
updateConversation(chatId, messageId, { tools })
|
|
123
206
|
break
|
|
124
207
|
|
|
125
|
-
case '
|
|
126
|
-
// O tool_start já marcou estas ferramentas como "running".
|
|
127
|
-
// Elas não estão executando: estão paradas esperando o
|
|
128
|
-
// clique — senão o chip giraria para sempre.
|
|
129
|
-
const pausadas = new Set(
|
|
130
|
-
evento.data.calls.map((call) => call.id),
|
|
131
|
-
)
|
|
208
|
+
case 'tool_progress':
|
|
132
209
|
tools = tools.map((tool) =>
|
|
133
|
-
|
|
134
|
-
? { ...tool,
|
|
210
|
+
tool.id === evento.data.id
|
|
211
|
+
? { ...tool, progresso: evento.data.texto }
|
|
135
212
|
: tool,
|
|
136
213
|
)
|
|
214
|
+
updateConversation(chatId, messageId, { tools })
|
|
215
|
+
break
|
|
216
|
+
|
|
217
|
+
case 'approval_required':
|
|
218
|
+
// O tool_start já marcou estas ferramentas como "running";
|
|
219
|
+
// elas estão paradas esperando a confirmação.
|
|
220
|
+
terminou = true
|
|
221
|
+
tools = pausar(
|
|
222
|
+
tools,
|
|
223
|
+
evento.data.calls.map((call) => call.id),
|
|
224
|
+
'confirmacao',
|
|
225
|
+
)
|
|
137
226
|
updateConversation(chatId, messageId, {
|
|
138
227
|
tools,
|
|
139
228
|
pendingApproval: evento.data,
|
|
140
229
|
})
|
|
141
230
|
break
|
|
142
|
-
|
|
231
|
+
|
|
232
|
+
case 'format_required':
|
|
233
|
+
// O mesmo com o gerar_relatorio: parado esperando o formato.
|
|
234
|
+
terminou = true
|
|
235
|
+
tools = pausar(tools, [evento.data.chamada], 'formato')
|
|
236
|
+
updateConversation(chatId, messageId, {
|
|
237
|
+
tools,
|
|
238
|
+
pendingFormat: evento.data,
|
|
239
|
+
})
|
|
240
|
+
break
|
|
143
241
|
|
|
144
242
|
case 'input_required':
|
|
145
243
|
// Diferente da aprovação, aqui nenhuma ferramenta foi
|
|
146
244
|
// pedida ao ERP: o agente só percebeu que faltam campos.
|
|
147
245
|
// Por isso não há chip de ferramenta para ajustar.
|
|
246
|
+
terminou = true
|
|
148
247
|
updateConversation(chatId, messageId, {
|
|
149
248
|
pendingInput: evento.data,
|
|
150
249
|
})
|
|
151
250
|
break
|
|
152
251
|
|
|
153
|
-
case '
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
252
|
+
case 'report_data':
|
|
253
|
+
// HTML ou planilha. Cada versão tem o próprio id: a
|
|
254
|
+
// personalização chega como outro relatório, e nenhum
|
|
255
|
+
// substitui o anterior.
|
|
256
|
+
relatorios = [
|
|
257
|
+
...relatorios.filter(
|
|
258
|
+
(relatorio) => relatorio.id !== evento.data.id,
|
|
259
|
+
),
|
|
260
|
+
evento.data,
|
|
261
|
+
]
|
|
262
|
+
updateConversation(chatId, messageId, { relatorios })
|
|
157
263
|
break
|
|
158
264
|
|
|
159
265
|
case 'done':
|
|
@@ -168,148 +274,157 @@ const useChatSend = () => {
|
|
|
168
274
|
// esquecido tudo. No primeiro envio `inicial.texto` é '',
|
|
169
275
|
// então nada muda ali.
|
|
170
276
|
texto = inicial.texto + evento.data.content
|
|
277
|
+
terminou = true
|
|
171
278
|
updateConversation(chatId, messageId, { content: texto })
|
|
172
279
|
break
|
|
173
280
|
|
|
174
281
|
case 'error':
|
|
175
|
-
|
|
176
|
-
content: evento.data.message || AI_ERROR_MESSAGE,
|
|
177
|
-
isError: true,
|
|
178
|
-
})
|
|
282
|
+
falhar()
|
|
179
283
|
break
|
|
180
284
|
}
|
|
181
285
|
}
|
|
182
286
|
|
|
183
287
|
try {
|
|
184
288
|
await executar(aplicar)
|
|
289
|
+
if (!terminou) {
|
|
290
|
+
falhar()
|
|
291
|
+
}
|
|
185
292
|
} catch {
|
|
186
|
-
|
|
187
|
-
content: texto || AI_ERROR_MESSAGE,
|
|
188
|
-
isError: !texto,
|
|
189
|
-
})
|
|
293
|
+
falhar()
|
|
190
294
|
} finally {
|
|
191
295
|
setIsTyping(false)
|
|
192
296
|
}
|
|
193
297
|
}
|
|
194
298
|
|
|
195
|
-
|
|
299
|
+
/**
|
|
300
|
+
* A conversão para base64 roda dentro do `executar`: se a leitura de um
|
|
301
|
+
* arquivo falhar, cai no mesmo `catch` de uma falha de rede e vira a
|
|
302
|
+
* mensagem de erro do chat.
|
|
303
|
+
*/
|
|
304
|
+
const sendMessage = async (
|
|
305
|
+
chatId: string,
|
|
306
|
+
prompt: string,
|
|
307
|
+
imagens: File[],
|
|
308
|
+
) => {
|
|
196
309
|
const messageId = createAiMessage(chatId)
|
|
197
310
|
await consumirStream(
|
|
198
311
|
chatId,
|
|
199
312
|
messageId,
|
|
200
|
-
(onEvent) =>
|
|
313
|
+
async (onEvent) =>
|
|
201
314
|
streamChat({
|
|
202
315
|
prompt,
|
|
203
316
|
conversationId: chatId,
|
|
204
317
|
esforco,
|
|
318
|
+
modelo,
|
|
319
|
+
imagens: imagens.length
|
|
320
|
+
? await Promise.all(imagens.map(paraImagemEnviada))
|
|
321
|
+
: undefined,
|
|
205
322
|
onEvent,
|
|
206
323
|
}),
|
|
207
|
-
{ texto: '', tools: [] },
|
|
324
|
+
{ texto: '', tools: [], relatorios: [] },
|
|
208
325
|
)
|
|
209
326
|
}
|
|
210
327
|
|
|
211
|
-
const createConversation = async (
|
|
328
|
+
const createConversation = async (
|
|
329
|
+
chatId: string,
|
|
330
|
+
prompt: string,
|
|
331
|
+
imagens: File[],
|
|
332
|
+
) => {
|
|
212
333
|
setSelectedConversation(chatId)
|
|
213
|
-
await sendMessage(chatId, prompt)
|
|
334
|
+
await sendMessage(chatId, prompt, imagens)
|
|
214
335
|
}
|
|
215
336
|
|
|
216
|
-
const handleSend = async (prompt: string) => {
|
|
337
|
+
const handleSend = async (prompt: string, imagens: File[] = []) => {
|
|
217
338
|
setIsTyping(true)
|
|
218
339
|
if (selectedConversation) {
|
|
219
|
-
creteMyMessage(selectedConversation, prompt)
|
|
220
|
-
await sendMessage(selectedConversation, prompt)
|
|
340
|
+
creteMyMessage(selectedConversation, prompt, imagens)
|
|
341
|
+
await sendMessage(selectedConversation, prompt, imagens)
|
|
221
342
|
} else {
|
|
222
343
|
const newId = novoIdDeConversa()
|
|
223
344
|
pushChatHistory({
|
|
224
345
|
id: newId,
|
|
225
|
-
title: prompt,
|
|
346
|
+
title: prompt.trim() || TITULO_SO_IMAGEM,
|
|
226
347
|
lastConversation: '',
|
|
227
348
|
createdTime: dayjs().unix(),
|
|
228
349
|
updatedTime: dayjs().unix(),
|
|
229
350
|
enable: true,
|
|
230
351
|
})
|
|
231
|
-
creteMyMessage(newId, prompt)
|
|
232
|
-
await createConversation(newId, prompt)
|
|
352
|
+
creteMyMessage(newId, prompt, imagens)
|
|
353
|
+
await createConversation(newId, prompt, imagens)
|
|
233
354
|
}
|
|
234
355
|
}
|
|
235
356
|
|
|
236
357
|
/**
|
|
237
|
-
*
|
|
358
|
+
* Responde a pausa pendente da mensagem e retoma a conversa.
|
|
238
359
|
*
|
|
239
|
-
* Continua escrevendo na
|
|
240
|
-
* conteúdo
|
|
360
|
+
* Continua escrevendo na MESMA mensagem: por isso o acumulador parte do
|
|
361
|
+
* conteúdo, das ferramentas e dos relatórios que já estão lá.
|
|
241
362
|
*/
|
|
242
|
-
const
|
|
363
|
+
const retomar = async (
|
|
243
364
|
chatId: string,
|
|
244
365
|
messageId: string,
|
|
245
|
-
|
|
366
|
+
pendencia: Pendencia,
|
|
367
|
+
resposta: Pick<ResumeChatParams, 'approved' | 'dados' | 'formato'>,
|
|
246
368
|
) => {
|
|
247
369
|
const mensagem = usGenerativeChatStore
|
|
248
370
|
.getState()
|
|
249
371
|
.chatHistory.find((chat) => chat.id === chatId)
|
|
250
372
|
?.conversation?.find((item) => item.id === messageId)
|
|
251
373
|
|
|
252
|
-
if (!mensagem?.
|
|
374
|
+
if (!mensagem?.[pendencia]) {
|
|
253
375
|
return
|
|
254
376
|
}
|
|
255
377
|
|
|
256
378
|
setIsTyping(true)
|
|
257
379
|
// Some com o card antes da chamada: dois cliques rápidos enviariam duas
|
|
258
380
|
// retomadas, e a segunda falha (o interrupt já foi consumido).
|
|
259
|
-
updateConversation(chatId, messageId, {
|
|
381
|
+
updateConversation(chatId, messageId, { [pendencia]: undefined })
|
|
260
382
|
|
|
261
383
|
await consumirStream(
|
|
262
384
|
chatId,
|
|
263
385
|
messageId,
|
|
264
386
|
(onEvent) =>
|
|
265
387
|
resumeChat({
|
|
266
|
-
|
|
388
|
+
...resposta,
|
|
267
389
|
conversationId: chatId,
|
|
268
390
|
esforco,
|
|
391
|
+
modelo,
|
|
269
392
|
onEvent,
|
|
270
393
|
}),
|
|
271
|
-
{
|
|
394
|
+
{
|
|
395
|
+
texto: mensagem.content ?? '',
|
|
396
|
+
tools: mensagem.tools ?? [],
|
|
397
|
+
relatorios: mensagem.relatorios ?? [],
|
|
398
|
+
},
|
|
272
399
|
)
|
|
273
400
|
}
|
|
274
401
|
|
|
275
|
-
/**
|
|
276
|
-
|
|
277
|
-
*
|
|
278
|
-
* Mesma mecânica do `handleApproval`: continua na MESMA mensagem, então o
|
|
279
|
-
* acumulador parte do que já está lá.
|
|
280
|
-
*/
|
|
281
|
-
const handleDataSubmit = async (
|
|
402
|
+
/** Aprova ou nega a operação pendente. */
|
|
403
|
+
const handleApproval = (
|
|
282
404
|
chatId: string,
|
|
283
405
|
messageId: string,
|
|
284
|
-
|
|
285
|
-
) => {
|
|
286
|
-
const mensagem = usGenerativeChatStore
|
|
287
|
-
.getState()
|
|
288
|
-
.chatHistory.find((chat) => chat.id === chatId)
|
|
289
|
-
?.conversation?.find((item) => item.id === messageId)
|
|
290
|
-
|
|
291
|
-
if (!mensagem?.pendingInput) {
|
|
292
|
-
return
|
|
293
|
-
}
|
|
406
|
+
approved: boolean,
|
|
407
|
+
) => retomar(chatId, messageId, 'pendingApproval', { approved })
|
|
294
408
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
409
|
+
/** Envia os dados que faltavam; `null` = fechou o formulário sem preencher. */
|
|
410
|
+
const handleDataSubmit = (
|
|
411
|
+
chatId: string,
|
|
412
|
+
messageId: string,
|
|
413
|
+
dados: Record<string, unknown> | null,
|
|
414
|
+
) => retomar(chatId, messageId, 'pendingInput', { dados })
|
|
299
415
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
)
|
|
307
|
-
}
|
|
416
|
+
/** Envia o formato do relatório; `null` = fechou a escolha sem escolher. */
|
|
417
|
+
const handleFormato = (
|
|
418
|
+
chatId: string,
|
|
419
|
+
messageId: string,
|
|
420
|
+
formato: FormatoDoRelatorio | null,
|
|
421
|
+
) => retomar(chatId, messageId, 'pendingFormat', { formato })
|
|
308
422
|
|
|
309
423
|
return {
|
|
310
424
|
handleSend,
|
|
311
425
|
handleApproval,
|
|
312
426
|
handleDataSubmit,
|
|
427
|
+
handleFormato,
|
|
313
428
|
}
|
|
314
429
|
}
|
|
315
430
|
|
|
@@ -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,63 @@
|
|
|
1
|
+
import useSWR from 'swr'
|
|
2
|
+
import { useSessionUserDataStore } from '@base/store/auth/sessionUserData'
|
|
3
|
+
import { apiGetModelos } from '@/services/AiService'
|
|
4
|
+
import { useModeloStore } from '../store/modeloStore'
|
|
5
|
+
import type { GetModelosResponse } from '../types'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Funcionalidade do AUTH que libera a troca de modelo. O backend confere a
|
|
9
|
+
* mesma e recusa (403) o modelo enviado por quem não a tem.
|
|
10
|
+
*/
|
|
11
|
+
const ESCOLHER_MODELO = 'ESCOLHER_MODELO_ORBE_AI'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Os modelos que o chat oferece e o que vale agora.
|
|
15
|
+
*
|
|
16
|
+
* Só quem tem a funcionalidade `ESCOLHER_MODELO` escolhe. Para os outros,
|
|
17
|
+
* `modelos` fica vazio (o seletor não aparece) e `escolhido` indefinido (o
|
|
18
|
+
* chat não envia modelo e vale o padrão do backend).
|
|
19
|
+
*
|
|
20
|
+
* `escolhido` é o modelo salvo no navegador enquanto ele estiver na lista do
|
|
21
|
+
* backend; senão, o padrão. Assim um modelo que saiu do .env volta ao padrão
|
|
22
|
+
* em vez de virar 422. `atual` é o modelo que responde, com ou sem escolha: é
|
|
23
|
+
* por ele que o chat sabe se pode mandar imagem.
|
|
24
|
+
*
|
|
25
|
+
* Sem a lista (backend antigo, sem a rota, ou fora do ar), `modelos` fica
|
|
26
|
+
* vazio e `escolhido` indefinido: o chat não envia modelo e vale o padrão do
|
|
27
|
+
* backend. A falha não é definitiva: o SWR tenta de novo, com intervalo
|
|
28
|
+
* crescente, e o seletor aparece sozinho quando o backend volta, como depois
|
|
29
|
+
* de um restart. O 404 de um backend antigo também se repete, em silêncio
|
|
30
|
+
* (o interceptor do axios só reage a 401/403/419/440), até o deploy.
|
|
31
|
+
*/
|
|
32
|
+
const useModelos = () => {
|
|
33
|
+
// A lista é igual para todo usuário (vem do .env), então a chave não
|
|
34
|
+
// precisa do usuário, ao contrário da lista de conversas.
|
|
35
|
+
const { data } = useSWR(
|
|
36
|
+
'/ai/chat/models',
|
|
37
|
+
() => apiGetModelos<GetModelosResponse>(),
|
|
38
|
+
{
|
|
39
|
+
revalidateOnFocus: false,
|
|
40
|
+
revalidateOnReconnect: false,
|
|
41
|
+
},
|
|
42
|
+
)
|
|
43
|
+
const salvo = useModeloStore((state) => state.modelo)
|
|
44
|
+
// O seletor devolve o boolean, e não a função: assim o chat re-renderiza
|
|
45
|
+
// quando as funcionalidades da sessão mudam.
|
|
46
|
+
const podeEscolher = useSessionUserDataStore((state) =>
|
|
47
|
+
state.checkUserFunctionalityNameAccess(ESCOLHER_MODELO),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
const lista = data?.modelos ?? []
|
|
51
|
+
const padrao = lista.find((modelo) => modelo.id === data?.padrao)
|
|
52
|
+
const escolhido = podeEscolher
|
|
53
|
+
? (lista.find((modelo) => modelo.id === salvo) ?? padrao)
|
|
54
|
+
: undefined
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
modelos: podeEscolher ? lista : [],
|
|
58
|
+
escolhido,
|
|
59
|
+
atual: escolhido ?? padrao,
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export default useModelos
|
|
@@ -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
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { create } from 'zustand'
|
|
2
|
+
import { persist } from 'zustand/middleware'
|
|
3
|
+
|
|
4
|
+
type ModeloState = {
|
|
5
|
+
/** Id do modelo escolhido; null = nunca escolheu, vale o padrão. */
|
|
6
|
+
modelo: string | null
|
|
7
|
+
setModelo: (payload: string) => void
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Modelo escolhido no chat.
|
|
12
|
+
*
|
|
13
|
+
* Persistido no navegador, como o nível de raciocínio (`esforcoStore`): é
|
|
14
|
+
* preferência de uso, não dado da conversa. Guarda só o id; quem confere se
|
|
15
|
+
* ele ainda está na lista do backend é o `useModelos`.
|
|
16
|
+
*/
|
|
17
|
+
export const useModeloStore = create<ModeloState>()(
|
|
18
|
+
persist(
|
|
19
|
+
(set) => ({
|
|
20
|
+
modelo: null,
|
|
21
|
+
setModelo: (payload) => set(() => ({ modelo: payload })),
|
|
22
|
+
}),
|
|
23
|
+
{ name: 'orbe-ai-modelo' },
|
|
24
|
+
),
|
|
25
|
+
)
|