All files / apps/web/src/frontoffice/components AgentChatContent.jsx

0% Statements 0/173
0% Branches 0/186
0% Functions 0/41
0% Lines 0/158

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { useState, useEffect, useRef, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { Bot, Send, Loader2, Plus, MessageSquare, User, ChevronRight, ChevronDown, RefreshCw, X, Settings } from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { agentConfigAPI, agentExecutionAPI, sendStreamMessage } from '../../services/api';
import EntitySidebar from '../../components/EntitySidebar';
import EntityPage from '../../components/EntityPage';
import ItemRecap from '../../components/ItemRecap';
import { useOrganizationStore } from '../../store/organizationStore';
import toast from 'react-hot-toast';
 
export default function AgentChatContent({ agentId, lazySession }) {
  const queryClient = useQueryClient();
  const { currentOrganization } = useOrganizationStore();
  const organizationId = currentOrganization?.id;
  const messagesEndRef = useRef(null);
 
  const [currentSessionId, setCurrentSessionId] = useState(null);
  const [message, setMessage] = useState('');
  const [expandedUrls, setExpandedUrls] = useState(new Set());
  const toggleUrl = (key) => {
    setExpandedUrls(prev => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key); else next.add(key);
      return next;
    });
  };
  const [isStreaming, setIsStreaming] = useState(false);
  const [streamingContent, setStreamingContent] = useState('');
  const [streamingPhase, setStreamingPhase] = useState(null);
  const [streamingSteps, setStreamingSteps] = useState([]);
 
  const { data: agentsList, isLoading: agentsListLoading } = useQuery({
    queryKey: ['agents'],
    queryFn: async () => {
      const response = await agentConfigAPI.list();
      return response.data.data?.agents || [];
    },
    enabled: !lazySession
  });
 
  const { data: selectedAgent, isLoading: agentsLoading } = useQuery({
    queryKey: ['agent', agentId],
    queryFn: async () => {
      if (!agentId) return null;
      try {
        const response = await agentConfigAPI.get(agentId);
        return response.data.data?.agent || response.data.data;
      } catch {
        return null;
      }
    },
    enabled: !!agentId
  });
 
  const { data: sessions } = useQuery({
    queryKey: ['agent-sessions', agentId],
    queryFn: async () => {
      if (!agentId) return [];
      const response = await agentExecutionAPI.listSessions(agentId);
      return response.data.data?.sessions || [];
    },
    enabled: !!agentId && !lazySession
  });
 
  const { data: messages } = useQuery({
    queryKey: ['session-messages', currentSessionId],
    queryFn: async () => {
      if (!currentSessionId) return [];
      const response = await agentExecutionAPI.getMessages(currentSessionId);
      return response.data.data?.session?.messages || [];
    },
    enabled: !!currentSessionId,
    staleTime: 30000
  });
 
  const createSession = useMutation({
    mutationFn: async () => {
      const response = await agentExecutionAPI.createSession(null, agentId);
      return response.data.data?.session;
    },
    onSuccess: (session) => {
      queryClient.invalidateQueries(['agent-sessions', agentId]);
      setCurrentSessionId(session.id);
      toast.success('Nouvelle session créée');
    },
    onError: () => {
      toast.error('Erreur lors de la création de la session');
    }
  });
 
  const selectSession = (sessionId) => {
    setCurrentSessionId(sessionId);
    queryClient.invalidateQueries(['session-messages', sessionId]);
  };
 
  const messagesContainerRef = useRef(null);
  const lastMessageCallbackRef = useCallback((node) => {
    if (node && messagesContainerRef.current) {
      messagesContainerRef.current.scrollTop = node.offsetTop;
    }
  }, []);
 
 
 
  useEffect(() => {
    if (messagesContainerRef.current && isStreaming) {
      messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
    }
  }, [streamingSteps, isStreaming]);
 
  useEffect(() => {
    if (!currentSessionId && sessions && sessions.length > 0) {
      setCurrentSessionId(sessions[0].id);
    }
  }, [sessions]);
 
 
 
  useEffect(() => {
    if (agentId && !currentSessionId && !lazySession) {
      agentExecutionAPI.listSessions(agentId).then(response => {
        const existingSessions = response.data.data?.sessions || [];
        if (existingSessions.length > 0) {
          setCurrentSessionId(existingSessions[0].id);
        }
      }).catch(() => {});
    }
  }, [agentId, lazySession]);
 
  const handleSendMessage = async (e) => {
    e.preventDefault();
    if (!message.trim() || isStreaming) return;
 
    const userMessage = message.trim();
    setMessage('');
    setIsStreaming(true);
    setStreamingContent('');
    setStreamingPhase(null);
    setStreamingSteps([{ type: 'init' }]);
 
    let sessionId = currentSessionId;
 
    if (!sessionId) {
      try {
        const response = await agentExecutionAPI.createSession(null, agentId);
        sessionId = response.data.data?.session?.id;
        setCurrentSessionId(sessionId);
      } catch (err) {
        toast.error("Erreur lors de la création de la session");
        setIsStreaming(false);
        setStreamingSteps([]);
        return;
      }
    }
 
    const optimisticMsg = { id: `optimistic-${Date.now()}`, role: 'user', content: userMessage, createdAt: new Date().toISOString() };
    queryClient.setQueryData(['session-messages', sessionId], (old) => [...(old || []), optimisticMsg]);
 
    try {
      const reader = await sendStreamMessage(sessionId, userMessage);
      const decoder = new TextDecoder();
      let buffer = '';
 
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
 
        buffer += decoder.decode(value, { stream: true });
        const parts = buffer.split('\n\n');
        buffer = parts.pop();
 
        for (const part of parts) {
          const lines = part.split('\n');
          let eventType = '';
          let eventData = '';
          for (const line of lines) {
            if (line.startsWith('event: ')) eventType = line.slice(7);
            else if (line.startsWith('data: ')) eventData = line.slice(6);
          }
          if (!eventData) continue;
 
          try {
            const data = JSON.parse(eventData);
 
            if (eventType === 'phase') {
              setStreamingPhase(data.phase);
            } else if (eventType === 'step') {
              setStreamingSteps((prev) => [...prev, data]);
            } else             if (eventType === 'result') {
              queryClient.invalidateQueries(['session-messages', sessionId]);
            } else if (eventType === 'error') {
              throw new Error(data.message || 'Server error');
            }
          } catch (parseErr) {
            if (parseErr.message && !parseErr.message.includes('JSON')) throw parseErr;
          }
        }
      }
 
      setIsStreaming(false);
      setStreamingContent('');
      setStreamingPhase(null);
      setStreamingSteps([]);
    } catch (error) {
      console.error('Error sending message:', error);
      queryClient.setQueryData(['session-messages', sessionId], (old) =>
        (old || []).filter((m) => m.id !== optimisticMsg.id)
      );
      toast.error(error.message || "Erreur lors de l'envoi du message");
      setIsStreaming(false);
      setStreamingContent('');
      setStreamingPhase(null);
      setStreamingSteps([]);
    }
  };
 
  if (agentsLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
      </div>
    );
  }
 
  const renderChatView = (lazy) => (
    <>
      <div className="border-b border-gray-200 p-3 flex-shrink-0 bg-white">
        <div className="flex items-center justify-between gap-2">
          {lazy ? (
            <span className="text-xl font-bold text-indigo-600">nooloom</span>
          ) : (
            <span />
          )}
          <div className="flex items-center gap-2">
            {lazy && organizationId && (
              <Link
                to={`/${organizationId}/backoffice/agents`}
                className="flex items-center px-3 py-1 text-sm text-purple-600 border border-purple-300 rounded-lg hover:bg-purple-50"
                title="Créer et gérer les agents dans le backoffice"
              >
                <Settings className="w-4 h-4 mr-1" />
                Gérer les agents
              </Link>
            )}
          </div>
        </div>
        {!lazy && (
          <div className="mt-3 flex items-center space-x-2 overflow-x-auto">
            <span className="text-sm text-gray-500 whitespace-nowrap">Sessions:</span>
            <button
              onClick={() => createSession.mutate()}
              className="flex items-center px-3 py-1 text-sm text-green-600 border border-green-300 rounded-lg hover:bg-green-50 whitespace-nowrap"
            >
              <Plus className="w-4 h-4 mr-1" />
              Session
            </button>
            {sessions && sessions.map((session) => (
              <button
                key={session.id}
                onClick={() => selectSession(session.id)}
                className={`px-3 py-1 text-sm rounded-lg whitespace-nowrap ${
                  currentSessionId === session.id
                    ? 'bg-indigo-100 text-indigo-700 border border-indigo-300'
                    : 'bg-gray-100 text-gray-600 border border-gray-200 hover:bg-gray-200'
                }`}
              >
                {new Date(session.createdAt).toLocaleDateString()}{' '}
                {new Date(session.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
              </button>
            ))}
          </div>
        )}
      </div>
 
      {!lazy && !currentSessionId ? (
        <div className="flex-1 flex items-center justify-center bg-gray-50">
          <div className="text-center">
            <MessageSquare className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <p className="text-gray-500 mb-4">Aucune session active</p>
            <button
              onClick={() => createSession.mutate()}
              className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
            >
              Créer une session
            </button>
          </div>
        </div>
      ) : (
        <>
          <div ref={messagesContainerRef} className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50 relative">
            {(!messages || messages.length === 0) && !isStreaming && (
              <div className="text-center py-8">
                <Bot className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                <p className="text-gray-500">
                  Envoyez un message pour commencer la conversation
                </p>
                {selectedAgent?.knowledgeBaseIds?.length > 0 && (
                  <p className="text-sm text-gray-400 mt-2">
                    L'agent utilisera {selectedAgent.knowledgeBaseIds.length} base(s) de connaissances
                  </p>
                )}
              </div>
            )}
 
            {messages?.map((msg, index) => (
              <div
                key={msg.id || index}
                ref={index === messages.length - 1 ? lastMessageCallbackRef : null}
                className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                <div
                  className={`max-w-[80%] rounded-lg px-4 py-2 ${
                    msg.role === 'user'
                      ? 'bg-indigo-600 text-white'
                      : 'bg-white border border-gray-200 text-gray-800'
                  }`}
                >
                  <div className="flex items-start">
                    {msg.role !== 'user' && (
                      <Bot className="w-4 h-4 text-indigo-600 mr-2 mt-1 flex-shrink-0" />
                    )}
                    {msg.role === 'user' && (
                      <User className="w-4 h-4 text-white mr-2 mt-1 flex-shrink-0" />
                    )}
                    <div className="flex-1">
                      <ReactMarkdown className="prose prose-sm max-w-none" remarkPlugins={[remarkGfm]}>
                        {msg.content}
                      </ReactMarkdown>
 
                      {msg.sources && msg.sources.length > 0 && (() => {
                        const groups = {};
                        for (const s of msg.sources) {
                          for (const f of s.facts || []) {
                            const url = f.url || 'sans-url';
                            if (!groups[url]) groups[url] = { url: f.url, facts: [], kbName: s.kbName };
                            groups[url].facts.push(f);
                          }
                        }
                        const groupList = Object.values(groups);
                        return (
                          <div className="mt-3 pt-2 border-t border-gray-200">
                            <div className="text-xs font-medium text-gray-500 mb-2">
                              Sources ({groupList.length} sources, {groupList.reduce((a, g) => a + g.facts.length, 0)} faits)
                            </div>
                            {groupList.map((group, gi) => {
                              const key = `${msg.id || index}-${gi}`;
                              const open = expandedUrls.has(key);
                              const url = group.url;
                              const isPdf = url?.includes('.pdf') || url?.includes('minio') || url?.includes('workflow');
                              return (
                                <div key={gi} className="mb-2 border border-gray-200 rounded-lg overflow-hidden">
                                  <button
                                    onClick={() => toggleUrl(key)}
                                    className="w-full flex items-center justify-between px-3 py-2 text-xs bg-gray-50 hover:bg-gray-100 text-left"
                                  >
                                    <div className="flex items-center gap-2 min-w-0">
                                      {open ? <ChevronDown className="w-3 h-3 flex-shrink-0 text-gray-400" /> : <ChevronRight className="w-3 h-3 flex-shrink-0 text-gray-400" />}
                                      {url ? (
                                        <a
                                          href={url}
                                          target="_blank"
                                          rel="noopener noreferrer"
                                          onClick={(e) => e.stopPropagation()}
                                          className="text-blue-600 hover:underline truncate"
                                          title={url}
                                        >
                                          {isPdf ? <span className="bg-red-100 text-red-600 px-1 py-0.5 rounded text-xs mr-1">PDF</span> : <span className="bg-green-100 text-green-600 px-1 py-0.5 rounded text-xs mr-1">WEB</span>}
                                          {url}
                                        </a>
                                      ) : <span className="text-gray-400 italic">Source sans URL</span>}
                                    </div>
                                    <span className="text-gray-400 ml-2 flex-shrink-0">{group.facts.length} fait{group.facts.length > 1 ? 's' : ''}</span>
                                  </button>
                                  {open && (
                                    <div className="border-t border-gray-200">
                                      {group.facts.map((fact, fi) => (
                                        <div key={fi} className="px-3 py-2 text-xs text-gray-600 border-b border-gray-100 last:border-b-0">
                                          <div className="flex items-center gap-2 mb-1">
                                            <span className="bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded font-medium flex-shrink-0">
                                              {(fact.score * 100).toFixed(0)}%
                                            </span>
                                            <span className="text-gray-400 truncate">{group.kbName}</span>
                                          </div>
                                          <div className="text-gray-700 bg-gray-50 p-2 rounded">{fact.text}</div>
                                          {fact.metadata && (
                                            <div className="mt-1 text-gray-400">
                                              {fact.metadata.description && <span>Description: {fact.metadata.description}</span>}
                                              {fact.metadata.title && <span className="ml-2">Titre: {fact.metadata.title}</span>}
                                            </div>
                                          )}
                                        </div>
                                      ))}
                                    </div>
                                  )}
                                </div>
                              );
                            })}
                          </div>
                        );
                      })()}
                    </div>
                  </div>
                </div>
              </div>
            ))}
 
            {isStreaming && (
              <div className="flex justify-start">
                <div className="max-w-[80%] rounded-lg px-4 py-3 bg-white border border-gray-200">
                  {streamingSteps
                    .filter(s => s.type === 'init' || (s.type === 'search_kb' && s.factsCount > 0))
                    .map((step, i) => (
                      <div key={i} className="text-sm text-gray-700 mb-1">
                        {step.type === 'init' && '💬 Initialisation communication'}
                        {step.type === 'search_kb' && (step.error
                          ? `⚠️ ${step.kbName}: échec`
                          : `${step.factsCount} ressource(s) trouvé(es) dans base ${step.kbName} : ${step.query}`
                        )}
                      </div>
                    ))}
                  {streamingSteps.length === 0 && (
                    <div className="flex items-center">
                      <Loader2 className="w-4 h-4 animate-spin text-indigo-600 mr-2" />
                      <span className="text-gray-500">En train de réfléchir...</span>
                    </div>
                  )}
                </div>
              </div>
            )}
 
            <div ref={messagesEndRef} />
          </div>
 
          <form onSubmit={handleSendMessage} className="border-t border-gray-200 p-4 bg-white flex-shrink-0">
            <div className="flex items-center space-x-2">
              <input
                type="text"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                onMouseDown={(e) => {
                  e.preventDefault();
                  e.target.focus({ preventScroll: true });
                }}
                placeholder="Tapez votre message..."
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
              />
              <button
                type="submit"
                disabled={!message.trim() || isStreaming}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isStreaming ? <Loader2 className="w-5 h-5 animate-spin" /> : <Send className="w-5 h-5" />}
              </button>
            </div>
          </form>
        </>
      )}
    </>
  );
 
  if (lazySession) {
    return (
      <div className="h-full flex flex-col">
        {agentId ? (
          renderChatView(true)
        ) : (
          <>
            <div className="border-b border-gray-200 p-4 flex-shrink-0 bg-white">
              <div className="flex items-center justify-between">
                <span className="text-xl font-bold text-indigo-600">nooloom</span>
                {organizationId && (
                  <Link
                    to={`/${organizationId}/backoffice/agents`}
                    className="flex items-center px-3 py-1.5 text-sm text-purple-600 border border-purple-300 rounded-lg hover:bg-purple-50 transition-colors"
                    title="Créer et gérer les agents dans le backoffice"
                  >
                    <Settings className="w-4 h-4 mr-1.5" />
                    Gérer les agents
                  </Link>
                )}
              </div>
            </div>
            <div className="flex-1 flex items-center justify-center bg-gray-50">
              <div className="text-center">
                <Bot className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <p className="text-gray-500 mb-4">Aucun agent sélectionné</p>
              </div>
            </div>
          </>
        )}
      </div>
    );
  }
 
  // Frontoffice : sidebar secondaire collée à la nav principale + chat
  return (
    <EntityPage
      selectedId={agentId}
      sidebar={
        <EntitySidebar
          items={agentsList || []}
          selectedId={agentId}
          getItemHref={(agent) =>
            organizationId ? `/${organizationId}/agent-chat/${agent.id}` : null
          }
          searchPlaceholder="Rechercher un agent..."
          emptyMessage="Aucun agent disponible"
          title="Agent Chat"
          icon={Bot}
          iconClass="text-purple-600"
          backofficeTo={organizationId ? `/${organizationId}/backoffice/agents` : null}
          backofficeManageLabel="Gérer les agents"
          backofficeCreateLabel="Créer un agent"
          loading={agentsListLoading}
          filterFn={(a) => `${a.name} ${a.description || ''}`}
          renderItem={(agent, isSelected) => (
            <>
              <div className="flex items-center">
                <Bot className={`w-4 h-4 mr-2 flex-shrink-0 ${isSelected ? 'text-purple-600' : 'text-gray-400'}`} />
                <span className={`text-sm font-medium truncate flex-1 ${isSelected ? 'text-gray-900' : 'text-gray-700'}`}>
                  {agent.name}
                </span>
              </div>
              {agent.description && (
                <div className="text-xs text-gray-500 truncate mt-0.5">{agent.description}</div>
              )}
            </>
          )}
        />
      }
    >
      {!agentId ? (
        <div className="flex-1 min-h-0 flex items-center justify-center">
          <div className="text-center">
            <Bot className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <p className="text-gray-500">Sélectionnez un agent pour commencer</p>
          </div>
        </div>
      ) : (
        <>
          <ItemRecap
            name={selectedAgent?.name}
            description={selectedAgent?.description}
            meta={
              <>
                <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded">
                  {selectedAgent?.knowledgeBaseIds?.length || 0} KBs
                </span>
                {selectedAgent?.llmModel && (
                  <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded">
                    {selectedAgent.llmModel.split('/')[1] || selectedAgent.llmModel}
                  </span>
                )}
              </>
            }
            actions={
              organizationId ? (
                <Link
                  to={`/${organizationId}/backoffice/agents/${agentId}`}
                  title="Modifier dans le backoffice"
                  className="p-1.5 rounded-md text-gray-400 hover:text-gray-600 hover:bg-gray-100"
                >
                  <Settings className="w-4 h-4" />
                </Link>
              ) : null
            }
          />
          <div className="flex-1 min-h-0 flex flex-col">
            {renderChatView(false)}
          </div>
        </>
      )}
    </EntityPage>
  );
}