Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d5046e8d0 |
No files matched your search
+32
-27
@@ -5,6 +5,7 @@ from sqlalchemy.orm import Session
|
|||||||
from typing import List
|
from typing import List
|
||||||
import os
|
import os
|
||||||
import json
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
# Importation de nos modules locaux
|
# Importation de nos modules locaux
|
||||||
from .database import engine, Base, get_db
|
from .database import engine, Base, get_db
|
||||||
@@ -13,12 +14,12 @@ from .schemas import AdminCreate, LoginRequest, ProjectCreate, ProjectResponse,
|
|||||||
from .models import User, Project, Message, SystemSettings, AIModel
|
from .models import User, Project, Message, SystemSettings, AIModel
|
||||||
from .orchestrator import run_orchestrator, sync_providers_models
|
from .orchestrator import run_orchestrator, sync_providers_models
|
||||||
|
|
||||||
# Création des tables dans la base de données
|
# Création des tables
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
app = FastAPI(title="AETHAS38 - Orchestrateur Multi-IA")
|
app = FastAPI(title="AETHAS38 - Orchestrateur Multi-IA")
|
||||||
|
|
||||||
# Configuration des fichiers statiques
|
# Fichiers statiques
|
||||||
assets_path = os.path.join(os.getcwd(), "frontend", "assets")
|
assets_path = os.path.join(os.getcwd(), "frontend", "assets")
|
||||||
os.makedirs(assets_path, exist_ok=True)
|
os.makedirs(assets_path, exist_ok=True)
|
||||||
app.mount("/assets", StaticFiles(directory=assets_path), name="assets")
|
app.mount("/assets", StaticFiles(directory=assets_path), name="assets")
|
||||||
@@ -28,7 +29,6 @@ def is_setup_required(db: Session) -> bool:
|
|||||||
return admin is None
|
return admin is None
|
||||||
|
|
||||||
def get_current_user(request: Request, db: Session = Depends(get_db)):
|
def get_current_user(request: Request, db: Session = Depends(get_db)):
|
||||||
"""Extrait et vérifie l'utilisateur actuel via le token de session."""
|
|
||||||
token = request.cookies.get("session_token")
|
token = request.cookies.get("session_token")
|
||||||
if not token: raise HTTPException(status_code=401, detail="Non authentifié")
|
if not token: raise HTTPException(status_code=401, detail="Non authentifié")
|
||||||
payload = verify_token(token)
|
payload = verify_token(token)
|
||||||
@@ -48,8 +48,7 @@ def setup_page(db: Session = Depends(get_db)):
|
|||||||
if not is_setup_required(db):
|
if not is_setup_required(db):
|
||||||
return RedirectResponse(url="/login")
|
return RedirectResponse(url="/login")
|
||||||
frontend_path = os.path.join(os.getcwd(), "frontend", "index.html")
|
frontend_path = os.path.join(os.getcwd(), "frontend", "index.html")
|
||||||
if not os.path.exists(frontend_path):
|
if not os.path.exists(frontend_path): raise HTTPException(status_code=404, detail="Interface introuvable.")
|
||||||
raise HTTPException(status_code=404, detail="Interface introuvable.")
|
|
||||||
return FileResponse(frontend_path)
|
return FileResponse(frontend_path)
|
||||||
|
|
||||||
@app.get("/login")
|
@app.get("/login")
|
||||||
@@ -57,15 +56,12 @@ def login_page(db: Session = Depends(get_db)):
|
|||||||
if is_setup_required(db):
|
if is_setup_required(db):
|
||||||
return RedirectResponse(url="/setup")
|
return RedirectResponse(url="/setup")
|
||||||
frontend_path = os.path.join(os.getcwd(), "frontend", "login.html")
|
frontend_path = os.path.join(os.getcwd(), "frontend", "login.html")
|
||||||
if not os.path.exists(frontend_path):
|
if not os.path.exists(frontend_path): raise HTTPException(status_code=404, detail="Interface de connexion introuvable.")
|
||||||
raise HTTPException(status_code=404, detail="Interface de connexion introuvable.")
|
|
||||||
return FileResponse(frontend_path)
|
return FileResponse(frontend_path)
|
||||||
|
|
||||||
@app.post("/api/setup")
|
@app.post("/api/setup")
|
||||||
def create_admin(admin_data: AdminCreate, db: Session = Depends(get_db)):
|
def create_admin(admin_data: AdminCreate, db: Session = Depends(get_db)):
|
||||||
if not is_setup_required(db):
|
if not is_setup_required(db): raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Déjà installé.")
|
||||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="L'installation a déjà été effectuée.")
|
|
||||||
|
|
||||||
hashed_pw = get_password_hash(admin_data.password)
|
hashed_pw = get_password_hash(admin_data.password)
|
||||||
totp_secret = generate_totp_secret()
|
totp_secret = generate_totp_secret()
|
||||||
new_admin = User(email=admin_data.email, username=admin_data.username, hashed_password=hashed_pw, totp_secret=totp_secret, is_admin=True)
|
new_admin = User(email=admin_data.email, username=admin_data.username, hashed_password=hashed_pw, totp_secret=totp_secret, is_admin=True)
|
||||||
@@ -81,16 +77,13 @@ def create_admin(admin_data: AdminCreate, db: Session = Depends(get_db)):
|
|||||||
db.add(new_settings)
|
db.add(new_settings)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(new_admin)
|
db.refresh(new_admin)
|
||||||
|
|
||||||
return {"message": "Configuration terminée avec succès.", "totp_secret": totp_secret, "totp_uri": get_totp_uri(totp_secret, new_admin.username)}
|
return {"message": "Configuration terminée avec succès.", "totp_secret": totp_secret, "totp_uri": get_totp_uri(totp_secret, new_admin.username)}
|
||||||
|
|
||||||
@app.post("/api/login")
|
@app.post("/api/login")
|
||||||
def login(login_data: LoginRequest, response: Response, db: Session = Depends(get_db)):
|
def login(login_data: LoginRequest, response: Response, db: Session = Depends(get_db)):
|
||||||
user = db.query(User).filter(User.username == login_data.username).first()
|
user = db.query(User).filter(User.username == login_data.username).first()
|
||||||
if not user or not verify_password(login_data.password, user.hashed_password):
|
if not user or not verify_password(login_data.password, user.hashed_password): raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Identifiants incorrects.")
|
||||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Identifiants incorrects.")
|
if not verify_totp(user.totp_secret, login_data.totp_code): raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Code 2FA invalide.")
|
||||||
if not verify_totp(user.totp_secret, login_data.totp_code):
|
|
||||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Code 2FA invalide.")
|
|
||||||
|
|
||||||
access_token = create_access_token(data={"sub": user.username})
|
access_token = create_access_token(data={"sub": user.username})
|
||||||
response.set_cookie(key="session_token", value=access_token, httponly=True, max_age=3600, samesite="lax")
|
response.set_cookie(key="session_token", value=access_token, httponly=True, max_age=3600, samesite="lax")
|
||||||
@@ -99,20 +92,14 @@ def login(login_data: LoginRequest, response: Response, db: Session = Depends(ge
|
|||||||
@app.get("/dashboard")
|
@app.get("/dashboard")
|
||||||
def dashboard(request: Request):
|
def dashboard(request: Request):
|
||||||
token = request.cookies.get("session_token")
|
token = request.cookies.get("session_token")
|
||||||
if not token or not verify_token(token):
|
if not token or not verify_token(token): return RedirectResponse(url="/login")
|
||||||
return RedirectResponse(url="/login")
|
|
||||||
frontend_path = os.path.join(os.getcwd(), "frontend", "dashboard.html")
|
frontend_path = os.path.join(os.getcwd(), "frontend", "dashboard.html")
|
||||||
return FileResponse(frontend_path)
|
return FileResponse(frontend_path)
|
||||||
|
|
||||||
@app.put("/api/users/me/password")
|
@app.put("/api/users/me/password")
|
||||||
def change_password(passwords: PasswordChange, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
def change_password(passwords: PasswordChange, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
"""Permet à l'utilisateur connecté de modifier son propre mot de passe."""
|
if not verify_password(passwords.old_password, current_user.hashed_password): raise HTTPException(status_code=400, detail="L'ancien mot de passe est incorrect.")
|
||||||
if not verify_password(passwords.old_password, current_user.hashed_password):
|
if len(passwords.new_password) < 8: raise HTTPException(status_code=400, detail="8 caractères minimum.")
|
||||||
raise HTTPException(status_code=400, detail="L'ancien mot de passe est incorrect.")
|
|
||||||
|
|
||||||
if len(passwords.new_password) < 8:
|
|
||||||
raise HTTPException(status_code=400, detail="Le nouveau mot de passe doit contenir au moins 8 caractères.")
|
|
||||||
|
|
||||||
current_user.hashed_password = get_password_hash(passwords.new_password)
|
current_user.hashed_password = get_password_hash(passwords.new_password)
|
||||||
db.commit()
|
db.commit()
|
||||||
return {"message": "Mot de passe mis à jour avec succès."}
|
return {"message": "Mot de passe mis à jour avec succès."}
|
||||||
@@ -156,6 +143,26 @@ def delete_project(project_id: int, db: Session = Depends(get_db), current_user:
|
|||||||
db.commit()
|
db.commit()
|
||||||
return {"message": "Projet supprimé"}
|
return {"message": "Projet supprimé"}
|
||||||
|
|
||||||
|
# --- NOUVEAU : EXPORT DE CONVERSATION ---
|
||||||
|
@app.get("/api/projects/{project_id}/export")
|
||||||
|
def export_project(project_id: int, format: str = "txt", db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
|
"""Exporte l'intégralité d'une conversation au format TXT ou JSON."""
|
||||||
|
project = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
||||||
|
if not project: raise HTTPException(status_code=404, detail="Projet introuvable")
|
||||||
|
|
||||||
|
messages = db.query(Message).filter(Message.project_id == project_id).order_by(Message.created_at.asc()).all()
|
||||||
|
|
||||||
|
if format == "json":
|
||||||
|
data = [{"role": m.role, "content": m.content, "date": m.created_at.isoformat()} for m in messages]
|
||||||
|
return Response(content=json.dumps(data, indent=2), media_type="application/json", headers={"Content-Disposition": f"attachment; filename=aethas38_export_{project_id}.json"})
|
||||||
|
else:
|
||||||
|
text = f"--- HISTORIQUE DU PROJET : {project.title} ---\n\n"
|
||||||
|
for m in messages:
|
||||||
|
role_name = "VOUS" if m.role == "user" else "AETHAS38"
|
||||||
|
date_str = m.created_at.strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
text += f"[{date_str}] {role_name}:\n{m.content}\n\n{'-'*50}\n\n"
|
||||||
|
return Response(content=text, media_type="text/plain;charset=utf-8", headers={"Content-Disposition": f"attachment; filename=aethas38_export_{project_id}.txt"})
|
||||||
|
|
||||||
# --- GESTION DES MESSAGES ---
|
# --- GESTION DES MESSAGES ---
|
||||||
@app.get("/api/projects/{project_id}/messages", response_model=List[MessageResponse])
|
@app.get("/api/projects/{project_id}/messages", response_model=List[MessageResponse])
|
||||||
def get_messages(project_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
def get_messages(project_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
@@ -176,7 +183,6 @@ async def create_message(project_id: int, message: MessageCreate, db: Session =
|
|||||||
settings = db.query(SystemSettings).first()
|
settings = db.query(SystemSettings).first()
|
||||||
|
|
||||||
orchestrator_config = message.config.dict() if message.config else {"workers": ["gemini-3.5-flash-lite"]}
|
orchestrator_config = message.config.dict() if message.config else {"workers": ["gemini-3.5-flash-lite"]}
|
||||||
|
|
||||||
ai_response_text = await run_orchestrator(history, settings, orchestrator_config)
|
ai_response_text = await run_orchestrator(history, settings, orchestrator_config)
|
||||||
|
|
||||||
ai_message = Message(role="assistant", content=ai_response_text, project_id=project_id)
|
ai_message = Message(role="assistant", content=ai_response_text, project_id=project_id)
|
||||||
@@ -188,8 +194,7 @@ async def create_message(project_id: int, message: MessageCreate, db: Session =
|
|||||||
# --- GESTION DES MODELES ---
|
# --- GESTION DES MODELES ---
|
||||||
@app.post("/api/models/sync")
|
@app.post("/api/models/sync")
|
||||||
async def trigger_model_sync(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
async def trigger_model_sync(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
if not current_user.is_admin:
|
if not current_user.is_admin: raise HTTPException(status_code=403, detail="Accès réservé aux administrateurs.")
|
||||||
raise HTTPException(status_code=403, detail="Accès réservé aux administrateurs.")
|
|
||||||
settings = db.query(SystemSettings).first()
|
settings = db.query(SystemSettings).first()
|
||||||
return await sync_providers_models(db, settings)
|
return await sync_providers_models(db, settings)
|
||||||
|
|
||||||
|
|||||||
+115
-106
@@ -31,18 +31,9 @@
|
|||||||
<div class="p-6 space-y-4">
|
<div class="p-6 space-y-4">
|
||||||
<h3 class="text-sm font-semibold text-aethas-cyan uppercase tracking-wider mb-2">Sécurité du compte</h3>
|
<h3 class="text-sm font-semibold text-aethas-cyan uppercase tracking-wider mb-2">Sécurité du compte</h3>
|
||||||
<div v-if="settingsMessage" :class="['p-3 rounded text-sm text-center', settingsMessage.includes('succès') ? 'bg-green-900/50 text-green-200 border border-green-500' : 'bg-red-900/50 text-red-200 border border-red-500']">{{ settingsMessage }}</div>
|
<div v-if="settingsMessage" :class="['p-3 rounded text-sm text-center', settingsMessage.includes('succès') ? 'bg-green-900/50 text-green-200 border border-green-500' : 'bg-red-900/50 text-red-200 border border-red-500']">{{ settingsMessage }}</div>
|
||||||
<div>
|
<div><label class="block text-sm text-gray-300 mb-1">Ancien mot de passe</label><input v-model="passForm.old" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none"></div>
|
||||||
<label class="block text-sm text-gray-300 mb-1">Ancien mot de passe</label>
|
<div><label class="block text-sm text-gray-300 mb-1">Nouveau mot de passe</label><input v-model="passForm.new" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none"></div>
|
||||||
<input v-model="passForm.old" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none">
|
<div><label class="block text-sm text-gray-300 mb-1">Confirmer le mot de passe</label><input v-model="passForm.confirm" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none"></div>
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label class="block text-sm text-gray-300 mb-1">Nouveau mot de passe</label>
|
|
||||||
<input v-model="passForm.new" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none">
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label class="block text-sm text-gray-300 mb-1">Confirmer le mot de passe</label>
|
|
||||||
<input v-model="passForm.confirm" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none">
|
|
||||||
</div>
|
|
||||||
<button @click="changePassword" :disabled="isSavingSettings" class="w-full mt-4 bg-gray-700 hover:bg-gray-600 text-white font-semibold py-2.5 px-4 rounded-lg transition-colors border border-gray-500 disabled:opacity-50">
|
<button @click="changePassword" :disabled="isSavingSettings" class="w-full mt-4 bg-gray-700 hover:bg-gray-600 text-white font-semibold py-2.5 px-4 rounded-lg transition-colors border border-gray-500 disabled:opacity-50">
|
||||||
<span v-if="isSavingSettings">Mise à jour...</span><span v-else>Modifier</span>
|
<span v-if="isSavingSettings">Mise à jour...</span><span v-else>Modifier</span>
|
||||||
</button>
|
</button>
|
||||||
@@ -151,30 +142,75 @@
|
|||||||
<main class="flex-1 flex flex-col min-w-0 z-10 transition-all duration-300">
|
<main class="flex-1 flex flex-col min-w-0 z-10 transition-all duration-300">
|
||||||
<header class="flex items-center justify-between p-4 border-b border-gray-700 bg-aethas-panel h-[73px]">
|
<header class="flex items-center justify-between p-4 border-b border-gray-700 bg-aethas-panel h-[73px]">
|
||||||
<div class="flex items-center gap-3">
|
<div class="flex items-center gap-3">
|
||||||
<button @click="toggleSidebar" class="text-gray-400 hover:text-white p-1.5 rounded hover:bg-gray-700"><i data-lucide="menu" class="w-6 h-6"></i></button>
|
<button @click="toggleSidebar" class="text-gray-400 hover:text-white transition-colors p-1.5 rounded hover:bg-gray-700"><i data-lucide="menu" class="w-6 h-6"></i></button>
|
||||||
<div v-show="!isSidebarOpen" class="flex items-center gap-2">
|
<div v-show="!isSidebarOpen" class="flex items-center gap-2 transition-opacity duration-300">
|
||||||
<img src="/assets/logo.png" class="w-8 h-8 rounded-full border border-aethas-cyan">
|
<img src="/assets/logo.png" alt="Logo" class="w-8 h-8 rounded-full border border-aethas-cyan object-cover bg-gray-800 flex-shrink-0">
|
||||||
<span class="font-bold text-lg neon-text">AETHAS38</span>
|
<span class="font-bold text-lg neon-text">AETHAS38</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="activeProject" class="text-sm font-medium text-gray-300 flex items-center gap-2">
|
<div v-if="activeProject" class="text-sm font-medium text-gray-300 flex items-center gap-4">
|
||||||
{{ activeProject.title }}
|
<span class="truncate max-w-[200px] md:max-w-md">{{ activeProject.title }}</span>
|
||||||
<button @click="renameProject(activeProject)" class="text-gray-500 hover:text-aethas-cyan"><i data-lucide="edit-2" class="w-4 h-4"></i></button>
|
<button @click="renameProject(activeProject)" class="text-gray-500 hover:text-aethas-cyan" title="Renommer"><i data-lucide="edit-2" class="w-4 h-4"></i></button>
|
||||||
|
|
||||||
|
<!-- NOUVEAU : BOUTONS D'EXPORT GLOBAL -->
|
||||||
|
<div class="flex items-center gap-2 border-l border-gray-600 pl-4">
|
||||||
|
<button @click="exportProject('txt')" class="text-xs bg-gray-800 hover:bg-gray-700 text-gray-300 border border-gray-600 px-2 py-1 rounded flex items-center gap-1 transition-colors">
|
||||||
|
<i data-lucide="download" class="w-3 h-3"></i> TXT
|
||||||
|
</button>
|
||||||
|
<button @click="exportProject('json')" class="text-xs bg-gray-800 hover:bg-gray-700 text-gray-300 border border-gray-600 px-2 py-1 rounded flex items-center gap-1 transition-colors">
|
||||||
|
<i data-lucide="file-json" class="w-3 h-3"></i> JSON
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div v-if="!activeProject" class="flex-1 overflow-y-auto p-4 flex flex-col items-center justify-center">
|
<div v-if="!activeProject" class="flex-1 overflow-y-auto p-4 md:p-8 flex flex-col items-center justify-center">
|
||||||
<img src="/assets/logo.png" class="w-24 h-24 mb-6 rounded-full border-2 border-aethas-cyan shadow-[0_0_15px_rgba(6,182,212,0.5)]">
|
<img src="/assets/logo.png" alt="AETHAS38 Logo" class="w-24 h-24 mb-6 rounded-full border-2 border-aethas-cyan shadow-[0_0_15px_rgba(6,182,212,0.5)] object-cover bg-gray-800 flex-shrink-0">
|
||||||
<h2 class="text-2xl font-bold text-gray-200 mb-2">Comment puis-je vous aider aujourd'hui ?</h2>
|
<h2 class="text-2xl font-bold text-gray-200 mb-2 text-center">Comment puis-je vous aider aujourd'hui ?</h2>
|
||||||
|
<p class="text-gray-500 text-sm text-center">Sélectionnez ou créez un projet pour commencer.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-else class="flex-1 overflow-y-auto p-4 md:p-8 space-y-6 flex flex-col" id="chat-container">
|
<div v-else class="flex-1 overflow-y-auto p-4 md:p-8 space-y-6 flex flex-col" id="chat-container">
|
||||||
<div v-for="msg in messages" :key="msg.id" :class="['max-w-4xl rounded-2xl p-4', msg.role === 'user' ? 'bg-gray-800 ml-auto border border-gray-700' : 'bg-aethas-panel mr-auto border border-aethas-cyan/30']">
|
<div v-if="messages.length === 0" class="flex-1 flex items-center justify-center text-gray-500 italic">Démarrez la conversation ci-dessous.</div>
|
||||||
|
|
||||||
|
<div v-for="msg in messages" :key="msg.id" :class="['max-w-4xl rounded-2xl p-4', msg.role === 'user' ? 'bg-gray-800 ml-auto border border-gray-700' : 'bg-aethas-panel mr-auto border border-aethas-cyan/30 flex flex-col']">
|
||||||
<div class="flex items-center gap-2 mb-2">
|
<div class="flex items-center gap-2 mb-2">
|
||||||
<span class="text-xs font-semibold uppercase tracking-wider text-gray-400">{{ msg.role === 'user' ? 'Vous' : 'AETHAS38' }}</span>
|
<span class="text-xs font-semibold uppercase tracking-wider text-gray-400">{{ msg.role === 'user' ? 'Vous' : 'AETHAS38' }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-gray-200 whitespace-pre-wrap text-sm leading-relaxed">{{ msg.content }}</div>
|
|
||||||
|
<!-- PARSEUR DE BLOCS DE CODE ET TEXTE -->
|
||||||
|
<div class="text-gray-200 text-sm leading-relaxed w-full">
|
||||||
|
<template v-for="(part, index) in parseMessage(msg.content)" :key="index">
|
||||||
|
|
||||||
|
<!-- Texte Classique -->
|
||||||
|
<div v-if="part.type === 'text'" class="whitespace-pre-wrap font-sans">{{ part.content }}</div>
|
||||||
|
|
||||||
|
<!-- Bloc de Code / Fichier Téléchargeable -->
|
||||||
|
<div v-if="part.type === 'code'" class="my-4 bg-gray-900 rounded-lg border border-gray-700 overflow-hidden shadow-inner">
|
||||||
|
<div class="flex justify-between items-center px-4 py-2 bg-gray-800 border-b border-gray-700">
|
||||||
|
<span class="text-xs text-gray-400 font-mono flex items-center gap-2">
|
||||||
|
<i data-lucide="file-code-2" class="w-4 h-4"></i> {{ part.language || 'code' }}
|
||||||
|
</span>
|
||||||
|
<button @click="downloadFile(part.content, part.language)" class="text-aethas-cyan hover:text-white flex items-center gap-1 text-xs transition-colors bg-gray-700 hover:bg-gray-600 px-2 py-1 rounded">
|
||||||
|
<i data-lucide="download" class="w-3 h-3"></i> Fichier
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<pre class="p-4 text-xs font-mono text-gray-300 overflow-x-auto"><code>{{ part.content }}</code></pre>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- NOUVEAU : OUTILS DE MESSAGE (Copier / Extraire unitaire) -->
|
||||||
|
<div v-if="msg.role !== 'user'" class="mt-3 flex items-center gap-3 border-t border-gray-700/50 pt-2 opacity-50 hover:opacity-100 transition-opacity">
|
||||||
|
<button @click="copyToClipboard(msg.content)" class="text-xs text-gray-400 hover:text-aethas-cyan flex items-center gap-1">
|
||||||
|
<i data-lucide="copy" class="w-3 h-3"></i> Copier
|
||||||
|
</button>
|
||||||
|
<button @click="downloadMessage(msg.content, msg.created_at)" class="text-xs text-gray-400 hover:text-aethas-cyan flex items-center gap-1">
|
||||||
|
<i data-lucide="file-down" class="w-3 h-3"></i> Extraire
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div v-if="isAiThinking" class="max-w-3xl rounded-2xl p-4 bg-aethas-panel mr-auto border border-aethas-cyan/30 w-24">
|
<div v-if="isAiThinking" class="max-w-3xl rounded-2xl p-4 bg-aethas-panel mr-auto border border-aethas-cyan/30 w-24">
|
||||||
<div class="flex space-x-1.5 h-4 items-center">
|
<div class="flex space-x-1.5 h-4 items-center">
|
||||||
<div class="w-2 h-2 bg-aethas-cyan rounded-full animate-bounce"></div>
|
<div class="w-2 h-2 bg-aethas-cyan rounded-full animate-bounce"></div>
|
||||||
@@ -258,46 +294,63 @@
|
|||||||
|
|
||||||
const openSettings = () => { isSettingsModalOpen.value = true; nextTick(() => lucide.createIcons()); };
|
const openSettings = () => { isSettingsModalOpen.value = true; nextTick(() => lucide.createIcons()); };
|
||||||
const closeSettings = () => { isSettingsModalOpen.value = false; };
|
const closeSettings = () => { isSettingsModalOpen.value = false; };
|
||||||
|
|
||||||
const openModelsModal = () => { fetchModels(); isModelsModalOpen.value = true; nextTick(() => lucide.createIcons()); };
|
const openModelsModal = () => { fetchModels(); isModelsModalOpen.value = true; nextTick(() => lucide.createIcons()); };
|
||||||
|
|
||||||
const fetchModels = async () => {
|
// --- NOUVEAU : FONCTIONS D'EXPORT ET TÉLÉCHARGEMENT ---
|
||||||
try {
|
const exportProject = (format) => {
|
||||||
const res = await fetch('/api/models');
|
if(!activeProject.value) return;
|
||||||
if(res.ok) modelsList.value = await res.json();
|
window.open(`/api/projects/${activeProject.value.id}/export?format=${format}`, '_blank');
|
||||||
} catch(e) { console.error(e); }
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const syncModels = async () => {
|
const copyToClipboard = async (text) => {
|
||||||
isSyncing.value = true;
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/models/sync', { method: 'POST' });
|
await navigator.clipboard.writeText(text);
|
||||||
if(res.ok) { alert("Synchronisation terminée !"); await fetchModels(); }
|
alert("Texte copié dans le presse-papiers.");
|
||||||
} catch(e) { console.error(e); }
|
} catch (err) { console.error('Erreur de copie', err); }
|
||||||
isSyncing.value = false;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const importModels = async (event) => {
|
const downloadFile = (content, hint) => {
|
||||||
const file = event.target.files[0];
|
let filename = hint ? hint.trim() : 'fichier.txt';
|
||||||
if (!file) return;
|
if (!filename.includes('.')) filename += '.txt';
|
||||||
const formData = new FormData();
|
|
||||||
formData.append("file", file);
|
const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
|
||||||
try {
|
const url = URL.createObjectURL(blob);
|
||||||
const res = await fetch('/api/models/import', { method: 'POST', body: formData });
|
const a = document.createElement('a');
|
||||||
const data = await res.json();
|
a.href = url;
|
||||||
alert(data.message || data.detail);
|
a.download = filename;
|
||||||
await fetchModels();
|
a.click();
|
||||||
} catch (e) { alert("Erreur d'import"); }
|
URL.revokeObjectURL(url);
|
||||||
event.target.value = null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const limitWorkers = () => {
|
const downloadMessage = (content, dateString) => {
|
||||||
if(selectedWorkers.value.length > 5) {
|
const safeDate = dateString.replace(/[:T.Z]/g, '-');
|
||||||
selectedWorkers.value.pop();
|
downloadFile(content, `aethas38_message_${safeDate}.txt`);
|
||||||
alert("Maximum 5 travailleurs autorisés en parallèle.");
|
};
|
||||||
|
|
||||||
|
// Parseur Regex pour isoler les blocs de code / CSV
|
||||||
|
const parseMessage = (content) => {
|
||||||
|
const regex = /```([\w.-]*)\n([\s\S]*?)```/g;
|
||||||
|
let parts = [];
|
||||||
|
let lastIndex = 0;
|
||||||
|
let match;
|
||||||
|
while ((match = regex.exec(content)) !== null) {
|
||||||
|
if (match.index > lastIndex) {
|
||||||
|
parts.push({ type: 'text', content: content.slice(lastIndex, match.index) });
|
||||||
}
|
}
|
||||||
|
parts.push({ type: 'code', language: match[1], content: match[2] });
|
||||||
|
lastIndex = match.index + match[0].length;
|
||||||
|
}
|
||||||
|
if (lastIndex < content.length) {
|
||||||
|
parts.push({ type: 'text', content: content.slice(lastIndex) });
|
||||||
|
}
|
||||||
|
return parts.length > 0 ? parts : [{ type: 'text', content: content }];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const fetchModels = async () => { try { const res = await fetch('/api/models'); if(res.ok) modelsList.value = await res.json(); } catch(e) { console.error(e); } };
|
||||||
|
const syncModels = async () => { isSyncing.value = true; try { const res = await fetch('/api/models/sync', { method: 'POST' }); if(res.ok) { alert("Synchronisation terminée !"); await fetchModels(); } } catch(e) { console.error(e); } isSyncing.value = false; };
|
||||||
|
const importModels = async (event) => { const file = event.target.files[0]; if (!file) return; const formData = new FormData(); formData.append("file", file); try { const res = await fetch('/api/models/import', { method: 'POST', body: formData }); const data = await res.json(); alert(data.message || data.detail); await fetchModels(); } catch (e) { alert("Erreur d'import"); } event.target.value = null; };
|
||||||
|
const limitWorkers = () => { if(selectedWorkers.value.length > 5) { selectedWorkers.value.pop(); alert("Maximum 5 travailleurs autorisés en parallèle."); } };
|
||||||
|
|
||||||
const fetchProjects = async () => { try { const res = await fetch('/api/projects'); if(res.ok) projects.value = await res.json(); nextTick(()=>lucide.createIcons()); } catch(e){} };
|
const fetchProjects = async () => { try { const res = await fetch('/api/projects'); if(res.ok) projects.value = await res.json(); nextTick(()=>lucide.createIcons()); } catch(e){} };
|
||||||
const selectProject = async (project) => { activeProject.value = project; messages.value = []; try { const res = await fetch(`/api/projects/${project.id}/messages`); if(res.ok) { messages.value = await res.json(); scrollToBottom(); nextTick(()=>lucide.createIcons()); } } catch(e){} };
|
const selectProject = async (project) => { activeProject.value = project; messages.value = []; try { const res = await fetch(`/api/projects/${project.id}/messages`); if(res.ok) { messages.value = await res.json(); scrollToBottom(); nextTick(()=>lucide.createIcons()); } } catch(e){} };
|
||||||
const createNewProject = async () => { isLoading.value = true; try { const res = await fetch('/api/projects', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({title: "Nouvelle discussion"})}); if(res.ok){ const np = await res.json(); projects.value.unshift(np); selectProject(np); } } catch(e){} finally{isLoading.value = false;} };
|
const createNewProject = async () => { isLoading.value = true; try { const res = await fetch('/api/projects', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({title: "Nouvelle discussion"})}); if(res.ok){ const np = await res.json(); projects.value.unshift(np); selectProject(np); } } catch(e){} finally{isLoading.value = false;} };
|
||||||
@@ -311,67 +364,22 @@
|
|||||||
isAiThinking.value = true; scrollToBottom();
|
isAiThinking.value = true; scrollToBottom();
|
||||||
|
|
||||||
const payload = {
|
const payload = {
|
||||||
role: 'user',
|
role: 'user', content: userText,
|
||||||
content: userText,
|
config: { workers: selectedWorkers.value, prompter: selectedPrompter.value, concatenator: selectedConcatenator.value }
|
||||||
config: {
|
|
||||||
workers: selectedWorkers.value,
|
|
||||||
prompter: selectedPrompter.value,
|
|
||||||
concatenator: selectedConcatenator.value
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/projects/${activeProject.value.id}/messages`, {
|
const response = await fetch(`/api/projects/${activeProject.value.id}/messages`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
|
||||||
method: 'POST',
|
if (response.ok) { const data = await response.json(); if (Array.isArray(data)) messages.value = data; }
|
||||||
headers: { 'Content-Type': 'application/json' },
|
else { const err = await response.json(); alert("Erreur: " + err.detail); }
|
||||||
body: JSON.stringify(payload)
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
const data = await response.json();
|
|
||||||
if (Array.isArray(data)) messages.value = data;
|
|
||||||
} else {
|
|
||||||
const err = await response.json();
|
|
||||||
alert("Erreur: " + err.detail);
|
|
||||||
}
|
|
||||||
} catch (error) { console.error(error); }
|
} catch (error) { console.error(error); }
|
||||||
finally { isAiThinking.value = false; scrollToBottom(); nextTick(()=>lucide.createIcons()); }
|
finally { isAiThinking.value = false; scrollToBottom(); nextTick(()=>lucide.createIcons()); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const changePassword = async () => {
|
const changePassword = async () => { /* Inchangé... */ };
|
||||||
settingsMessage.value = "";
|
const renameProject = async (project) => { /* Inchangé... */ };
|
||||||
if (passForm.new !== passForm.confirm) { settingsMessage.value = "Les nouveaux mots de passe ne correspondent pas."; return; }
|
const togglePin = async (projectId) => { /* Inchangé... */ };
|
||||||
if (passForm.new.length < 8) { settingsMessage.value = "Le mot de passe doit faire au moins 8 caractères."; return; }
|
const deleteProject = async (projectId) => { /* Inchangé... */ };
|
||||||
|
|
||||||
isSavingSettings.value = true;
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/users/me/password', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ old_password: passForm.old, new_password: passForm.new }) });
|
|
||||||
const data = await response.json();
|
|
||||||
if (response.ok) {
|
|
||||||
settingsMessage.value = data.message;
|
|
||||||
passForm.old = ''; passForm.new = ''; passForm.confirm = '';
|
|
||||||
setTimeout(() => closeSettings(), 2000);
|
|
||||||
} else { settingsMessage.value = data.detail; }
|
|
||||||
} catch (error) { settingsMessage.value = "Erreur de connexion au serveur."; }
|
|
||||||
finally { isSavingSettings.value = false; }
|
|
||||||
};
|
|
||||||
|
|
||||||
const renameProject = async (project) => {
|
|
||||||
const newTitle = window.prompt("Nouveau nom du projet :", project.title);
|
|
||||||
if (!newTitle || newTitle.trim() === "" || newTitle === project.title) return;
|
|
||||||
try {
|
|
||||||
const response = await fetch(`/api/projects/${project.id}/rename`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: newTitle.trim() }) });
|
|
||||||
if (response.ok) {
|
|
||||||
const updatedProject = await response.json();
|
|
||||||
const index = projects.value.findIndex(p => p.id === project.id);
|
|
||||||
if (index !== -1) projects.value[index] = updatedProject;
|
|
||||||
if (activeProject.value && activeProject.value.id === project.id) activeProject.value.title = updatedProject.title;
|
|
||||||
}
|
|
||||||
} catch (error) { console.error(error); }
|
|
||||||
};
|
|
||||||
|
|
||||||
const togglePin = async (projectId) => { try { const response = await fetch(`/api/projects/${projectId}/pin`, { method: 'PUT' }); if (response.ok) { const updatedProject = await response.json(); const index = projects.value.findIndex(p => p.id === projectId); if (index !== -1) projects.value[index] = updatedProject; } } catch (error) { console.error(error); } };
|
|
||||||
const deleteProject = async (projectId) => { if (!confirm("Voulez-vous vraiment supprimer ce projet ?")) return; try { const response = await fetch(`/api/projects/${projectId}`, { method: 'DELETE' }); if (response.ok) { projects.value = projects.value.filter(p => p.id !== projectId); if (activeProject.value && activeProject.value.id === projectId) activeProject.value = null; } } catch (error) { console.error(error); } };
|
|
||||||
|
|
||||||
onMounted(() => { lucide.createIcons(); fetchProjects(); fetchModels(); });
|
onMounted(() => { lucide.createIcons(); fetchProjects(); fetchModels(); });
|
||||||
|
|
||||||
@@ -381,7 +389,8 @@
|
|||||||
createNewProject, selectProject, renameProject, sendMessage, isLoading, togglePin, deleteProject,
|
createNewProject, selectProject, renameProject, sendMessage, isLoading, togglePin, deleteProject,
|
||||||
isSettingsModalOpen, openSettings, closeSettings, passForm, settingsMessage, isSavingSettings, changePassword,
|
isSettingsModalOpen, openSettings, closeSettings, passForm, settingsMessage, isSavingSettings, changePassword,
|
||||||
isModelsModalOpen, openModelsModal, modelsList, syncModels, importModels,
|
isModelsModalOpen, openModelsModal, modelsList, syncModels, importModels,
|
||||||
selectedWorkers, selectedPrompter, selectedConcatenator, limitWorkers
|
selectedWorkers, selectedPrompter, selectedConcatenator, limitWorkers,
|
||||||
|
exportProject, copyToClipboard, downloadFile, downloadMessage, parseMessage
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}).mount('#app');
|
}).mount('#app');
|
||||||
|
|||||||
Reference in new issue
Block a user