All files / apps/web/src/backoffice/pages AgentEdit.jsx

0% Statements 0/88
0% Branches 0/95
0% Functions 0/41
0% Lines 0/82

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { useState, useEffect } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { 
  ArrowLeft, 
  Bot, 
  Save,
  Trash2,
  Database,
  Brain,
  MessageSquare,
  CheckCircle,
  XCircle,
  Plus,
  X,
  Code,
  Copy,
  Check,
  Key,
  ExternalLink
} from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import api from '../../services/api';
import toast from 'react-hot-toast';
import { useOrganizationStore } from '../../store/organizationStore';
import ModelSelector from '../../components/ModelSelector';
import EntitySidebar from '../../components/EntitySidebar';
import BackofficeEntityPage from '../components/BackofficeEntityPage';
 
export default function AgentEdit() {
  const navigate = useNavigate();
  const { id } = useParams();
  const { currentOrganization } = useOrganizationStore();
  const organizationId = currentOrganization?.id;
  const queryClient = useQueryClient();
  const isNew = id === 'new';
 
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    knowledgeBaseIds: [],
    llmModel: 'deepseek/deepseek-v4-flash',
    systemPrompt: 'Tu es un assistant helpful qui répond aux questions en utilisant le contexte fourni.',
    maxSessionMessages: 20,
    apiKeyId: null,
  });
 
  const [showKbSelector, setShowKbSelector] = useState(false);
  const [integCopied, setIntegCopied] = useState(false);
  const embedUrl = `${window.location.origin}/agent-embed/${id}`;
  const embedCode = `<iframe src="${embedUrl}" width="100%" height="600" frameborder="0"></iframe>`;
 
  const { data: agent, isLoading } = useQuery({
    queryKey: ['agent', id],
    queryFn: async () => {
      if (isNew) return null;
      const response = await api.get(`/agents/${id}`);
      return response.data.data?.agent || response.data.data;
    },
    enabled: !isNew
  });
 
  const { data: agentsList, isLoading: agentsListLoading } = useQuery({
    queryKey: ['agents', organizationId],
    queryFn: async () => {
      const response = await api.get('/agents');
      return response.data.data?.agents || [];
    }
  });
 
  const { data: knowledgeBases } = useQuery({
    queryKey: ['knowledge-bases'],
    queryFn: async () => {
      const response = await api.get('/knowledge-bases');
      return response.data.data?.knowledge_bases || response.data.data || [];
    }
  });
 
  const { data: apiKeys } = useQuery({
    queryKey: ['api-keys', organizationId],
    queryFn: async () => {
      const response = await api.get('/api-keys');
      return response.data.data || [];
    },
    enabled: !!organizationId
  });
 
  useEffect(() => {
    if (agent) {
      setFormData({
        name: agent.name || '',
        description: agent.description || '',
        knowledgeBaseIds: agent.knowledgeBaseIds || [],
        llmModel: agent.llmModel || 'qwen/qwen3-32b',
        systemPrompt: agent.systemPrompt || 'Tu es un assistant helpful qui répond aux questions en utilisant le contexte fourni.',
        maxSessionMessages: agent.maxSessionMessages || 20,
        apiKeyId: agent.apiKeyId || null,
      });
    }
  }, [agent]);
 
  const saveAgent = useMutation({
    mutationFn: async (data) => {
      const payload = {
        ...data,
        organizationId
      };
      
      if (isNew) {
        return api.post('/agents', payload);
      } else {
        return api.put(`/agents/${id}`, payload);
      }
    },
    onSuccess: () => {
      toast.success(isNew ? 'Agent créé' : 'Agent mis à jour');
      queryClient.invalidateQueries(['agents']);
      navigate(`/${organizationId}/backoffice/agents`);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Erreur lors de la sauvegarde');
    }
  });
 
  const deleteAgent = useMutation({
    mutationFn: async () => {
      return api.delete(`/agents/${id}`);
    },
    onSuccess: () => {
      toast.success('Agent supprimé');
      queryClient.invalidateQueries(['agents']);
      navigate(`/${organizationId}/backoffice/agents`);
    },
    onError: (error) => {
      toast.error(error.response?.data?.message || 'Erreur lors de la suppression');
    }
  });
 
  const handleSubmit = (e) => {
    e.preventDefault();
    saveAgent.mutate(formData);
  };
 
  const handleChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };
 
  const toggleKb = (kbId) => {
    setFormData(prev => ({
      ...prev,
      knowledgeBaseIds: prev.knowledgeBaseIds.includes(kbId)
        ? prev.knowledgeBaseIds.filter(id => id !== kbId)
        : [...prev.knowledgeBaseIds, kbId]
    }));
  };
 
  const selectedKbs = knowledgeBases?.filter(kb => formData.knowledgeBaseIds.includes(kb._id)) || [];
 
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    );
  }
 
  const sidebar = (
    <EntitySidebar
      items={agentsList || []}
      selectedId={isNew ? null : id}
      getItemHref={(a) => `/${organizationId}/backoffice/agents/${a.id}`}
      searchPlaceholder="Rechercher un agent..."
      emptyMessage="Aucun agent disponible"
      title="Agents"
      icon={Bot}
      iconClass="text-purple-600"
      backofficeTo={`/${organizationId}/backoffice/agents/new`}
      backofficeManageLabel="Créer un agent"
      backofficeCreateLabel="Créer un agent"
      createOnly
      loading={agentsListLoading}
      filterFn={(a) => `${a.name} ${a.description || ''}`}
      renderItem={(a, 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'}`}>
              {a.name}
            </span>
          </div>
          {a.description && (
            <div className="text-xs text-gray-500 truncate mt-0.5">{a.description}</div>
          )}
        </>
      )}
    />
  );
 
  return (
    <BackofficeEntityPage selectedId={isNew ? null : id} sidebar={sidebar}>
      <div className="flex-1 min-h-0 overflow-y-auto p-3 sm:p-6">
        <div className="space-y-6">
      <div className="flex justify-end gap-2">
        {!isNew && (
          <>
            <Link
              to={`/${organizationId}/agent-chat/${id}`}
              className="flex items-center px-3 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
              title="Exploiter cet agent dans le frontoffice"
            >
              <ExternalLink className="w-4 h-4 mr-2" />
              Exploiter
            </Link>
            <button
              onClick={() => {
                if (confirm('Êtes-vous sûr de vouloir supprimer cet agent ?')) {
                  deleteAgent.mutate();
                }
              }}
              className="flex items-center px-3 py-2 text-red-600 border border-red-300 rounded-lg hover:bg-red-50"
            >
              <Trash2 className="w-4 h-4 mr-2" />
              Supprimer
            </button>
          </>
        )}
        <button
          onClick={handleSubmit}
          disabled={saveAgent.isLoading}
          className="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
        >
          <Save className="w-5 h-5 mr-2" />
          {saveAgent.isLoading ? 'Sauvegarde...' : isNew ? 'Créer' : 'Sauvegarder'}
        </button>
      </div>
 
      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center mb-4">
            <Bot className="w-6 h-6 text-indigo-600 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Informations</h3>
          </div>
          
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Nom de l'agent *
              </label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => handleChange('name', e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                placeholder="Ex: Assistant Technique"
                required
              />
            </div>
 
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Description
              </label>
              <textarea
                value={formData.description}
                onChange={(e) => handleChange('description', e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                placeholder="Description de l'agent..."
                rows={2}
              />
            </div>
          </div>
        </div>
 
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center mb-4">
            <Brain className="w-6 h-6 text-purple-600 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Configuration LLM</h3>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Modèle LLM
              </label>
              <ModelSelector
                value={formData.llmModel || 'deepseek/deepseek-v4-flash'}
                onChange={(val) => handleChange('llmModel', val)}
              />
            </div>
 
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Messages en mémoire
              </label>
              <input
                type="number"
                value={formData.maxSessionMessages}
                onChange={(e) => handleChange('maxSessionMessages', parseInt(e.target.value, 10))}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                min={5}
                max={100}
              />
              <p className="text-xs text-gray-500 mt-1">Nombre de messages conservés dans l'historique</p>
            </div>
          </div>
 
          <div className="mt-4">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Prompt système
            </label>
            <textarea
              value={formData.systemPrompt}
              onChange={(e) => handleChange('systemPrompt', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent font-mono text-sm"
              placeholder="Tu es un assistant helpful..."
              rows={4}
              maxLength={2000}
            />
            <p className="text-xs text-gray-500 mt-1">
              {formData.systemPrompt.length}/2000 caractères
            </p>
          </div>
        </div>
 
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center">
              <Database className="w-6 h-6 text-green-600 mr-2" />
              <h3 className="text-lg font-medium text-gray-900">Bases de Connaissances</h3>
            </div>
            <button
              type="button"
              onClick={() => setShowKbSelector(true)}
              className="flex items-center px-3 py-1 text-indigo-600 border border-indigo-300 rounded-lg hover:bg-indigo-50"
            >
              <Plus className="w-4 h-4 mr-1" />
              Ajouter
            </button>
          </div>
 
          <div className="flex flex-wrap gap-2">
            {selectedKbs.length === 0 ? (
              <div className="text-sm text-gray-500 italic">
                Aucune base de connaissances sélectionnée. L'agent ne pourra pas répondre avec précision.
              </div>
            ) : (
              selectedKbs.map(kb => (
                <span
                  key={kb._id}
                  className="inline-flex items-center px-3 py-1 bg-green-100 text-green-700 rounded-lg text-sm"
                >
                  <Database className="w-4 h-4 mr-1" />
                  {kb.name}
                  <button
                    type="button"
                    onClick={() => toggleKb(kb._id)}
                    className="ml-2 text-green-600 hover:text-green-800"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </span>
              ))
            )}
          </div>
 
          <div className="mt-4 p-4 bg-gray-50 rounded-lg flex items-start">
            <MessageSquare className="w-5 h-5 text-gray-400 mr-2 mt-0.5" />
            <div className="text-sm text-gray-600">
              <strong>Agent RAG:</strong> L'agent utilisera ces bases de connaissances pour répondre 
              aux questions. Seules les bases de connaissances configurées et indexées seront utilisées.
            </div>
          </div>
        </div>
 
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center mb-4">
            <Key className="w-6 h-6 text-amber-600 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Clé d'API</h3>
          </div>
          <div className="space-y-2">
            <label className="block text-sm font-medium text-gray-700">
              Clé API pour diffusion publique
            </label>
            <select
              value={formData.apiKeyId || ''}
              onChange={(e) => {
                setFormData(prev => ({
                  ...prev,
                  apiKeyId: e.target.value || null,
                }));
              }}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500"
            >
              <option value="">Pas de clé API</option>
              {apiKeys?.map((ak) => (
                <option key={ak._id || ak.id} value={ak._id || ak.id}>
                  {ak.name} — {ak.keyPrefix}...
                </option>
              ))}
            </select>
            <p className="text-xs text-gray-500 mt-1">
              Requise pour diffuser l'agent publiquement (iframe).
              La régénération d'une clé mettra automatiquement à jour les agents qui l'utilisent.
            </p>
          </div>
        </div>
      </form>
 
      {!isNew && formData.apiKeyId && (
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center mb-4">
            <Code className="w-6 h-6 text-purple-600 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">Intégration Iframe</h3>
          </div>
 
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                URL de l'agent
              </label>
              <a
                href={`${window.location.origin}/agent-embed/${id}`}
                target="_blank"
                rel="noopener noreferrer"
                className="text-indigo-600 hover:text-indigo-800 underline text-sm font-mono break-all"
              >
                {`${window.location.origin}/agent-embed/${id}`}
              </a>
            </div>
 
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Code d'intégration
              </label>
              <div className="relative">
                <pre className="p-4 bg-gray-900 text-gray-100 rounded-lg text-sm overflow-x-auto">
                  {`<iframe src="${window.location.origin}/agent-embed/${id}"`}
                  {'\n'}
                  {`        width="100%" height="600" frameborder="0"></iframe>`}
                </pre>
                <button
                  onClick={() => {
                    const code = `<iframe src="${window.location.origin}/agent-embed/${id}" width="100%" height="600" frameborder="0"></iframe>`;
                    navigator.clipboard.writeText(code);
                    setIntegCopied(true);
                    setTimeout(() => setIntegCopied(false), 2000);
                    toast.success('Code copié !');
                  }}
                  className="absolute top-2 right-2 p-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
                  title="Copier le code"
                >
                  {integCopied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                </button>
              </div>
            </div>
 
            <div className="p-4 bg-purple-50 border border-purple-200 rounded-lg">
              <h4 className="font-medium text-purple-900 mb-2">Comment utiliser</h4>
              <ol className="text-sm text-purple-700 space-y-1 list-decimal list-inside">
                <li>Copiez le code d'intégration ci-dessus</li>
                <li>Collez-le dans n'importe quelle page HTML</li>
                <li>L'agent s'affichera dans une iframe, sans header ni sidebar du site</li>
              </ol>
            </div>
          </div>
        </div>
      )}
 
      {showKbSelector && knowledgeBases && (
        <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-2xl w-full max-h-[80vh] overflow-y-auto">
            <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
              <h3 className="text-lg font-medium text-gray-900">Sélectionner les Bases de Connaissances</h3>
              <button
                onClick={() => setShowKbSelector(false)}
                className="text-gray-400 hover:text-gray-500"
              >
                <X className="w-6 h-6" />
              </button>
            </div>
            <div className="p-6">
              {knowledgeBases.length === 0 ? (
                <div className="text-center py-8">
                  <Database className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                  <p className="text-gray-500">Aucune base de connaissances disponible</p>
                  <button
                    onClick={() => {
                      setShowKbSelector(false);
                      navigate(`/${organizationId}/backoffice/knowledge/new`);
                    }}
                    className="mt-4 text-indigo-600 hover:text-indigo-700 font-medium"
                  >
                    Créer une base de connaissances
                  </button>
                </div>
              ) : (
                <div className="space-y-2">
                  {knowledgeBases.map(kb => {
                    const isSelected = formData.knowledgeBaseIds.includes(kb._id);
                    return (
                      <div
                        key={kb._id}
                        onClick={() => toggleKb(kb._id)}
                        className={`p-4 rounded-lg border cursor-pointer transition-colors ${
                          isSelected
                            ? 'border-indigo-500 bg-indigo-50'
                            : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                        }`}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex items-center">
                            {isSelected ? (
                              <CheckCircle className="w-5 h-5 text-indigo-600 mr-3" />
                            ) : (
                              <div className="w-5 h-5 border-2 border-gray-300 rounded mr-3" />
                            )}
                            <div>
                              <div className="font-medium text-gray-900">{kb.name}</div>
                              <div className="text-sm text-gray-500">{kb.description || 'Aucune description'}</div>
                            </div>
                          </div>
                          <div className="text-sm text-gray-500">
                            {kb.engine || 'meilisearch'}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
            <div className="px-6 py-4 border-t border-gray-200 flex justify-end">
              <button
                onClick={() => setShowKbSelector(false)}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
              >
                Valider ({formData.knowledgeBaseIds.length} sélectionné{formData.knowledgeBaseIds.length > 1 ? 's' : ''})
              </button>
            </div>
          </div>
        </div>
      )}
        </div>
      </div>
    </BackofficeEntityPage>
  );
}