Instance de test : préparation et test de bout en bout sans envoi
fil() écarte les activités (privées dans LibreDesk) ; les outils des agents tournent avec le Python courant. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
39fa4cc708
commit
690204a634
8 files changed
+134
-4
No files matched your search
@@ -20,3 +20,4 @@
|
||||
| `.claude/skills/support/SKILL.md` §5 | `knowledge/support/redaction.md` | fbb84bf | 2026-11-05 | §5 seul ; une note : sortie mail, le corps et les pièces passent par `ecrire_mail` ; sortie PDF, vaut pour les textes de la présentation |
|
||||
- `.claude/skills/presentation/image-de-la-cause.py` → `tools/figures/` : le nom des cibles en jaune sur fond sombre, seulement celles de `--cibles` (x, y de l'export), titre sans nom de station (2026-11-05).
|
||||
- `Support-Agent/API/` → `agents/` de `Support-AI`, commit 94e0f0b, 2026-11-09 : sans `tools/typst/` (sortie PDF inutilisée), `cases/`, `docs/`. Les lignes ci-dessus restent vraies, chemins relatifs à `agents/`.
|
||||
- `agents/support/outils.py` : `PY = sys.executable` au lieu de `API/.venv/bin/python` (Support-AI, 2026-11-09 : les outils sont lancés par le Python du cycle, sur le poste comme sur le runner).
|
||||
@@ -10,6 +10,7 @@ import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
@@ -17,7 +18,7 @@ from typing import Callable
|
||||
from PIL import Image
|
||||
|
||||
API = Path(__file__).resolve().parents[1]
|
||||
PY = str(API / ".venv" / "bin" / "python")
|
||||
PY = sys.executable # Support-AI : le Python qui nous lance (pas de agents/.venv, sur le poste ni sur le runner)
|
||||
TOOLS = API / "tools"
|
||||
TYPST = TOOLS / "typst"
|
||||
KNOWLEDGE = API / "knowledge"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
Bonjour,
|
||||
|
||||
Sur notre site, la station LENZSPITZE, plusieurs cibles montrent des pics sur les courbes dans la nuit du 26 au 27 octobre 2026. Le reste du mois paraît calme.
|
||||
|
||||
S'agit-il d'un mouvement réel de l'ouvrage, ou d'un problème de mesure ? Nous devons en rendre compte à la direction des travaux.
|
||||
|
||||
Merci d'avance,
|
||||
Client Test
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Prépare une instance de test neuve : boîte e-mail (SMTP = Mailpit), étiquettes du contrat, rôle « Agent IA », son
|
||||
agent et sa clé, une conversation du contact avec le mail du fichier, étiquetée tri:diagnostic. Écrit
|
||||
instance-de-test/.env (LIBREDESK_URL, LIBREDESK_API_KEY, LIBREDESK_API_SECRET, CONVERSATION).
|
||||
|
||||
python -I instance-de-test/preparer.py <mot de passe System> <fichier du mail>
|
||||
"""
|
||||
import html
|
||||
import http.cookiejar
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
B = "http://127.0.0.1:9100"
|
||||
ETIQUETTES = ["tri:diagnostic", "diag:en-cours", "diag:fait", "diag:erreur", "diag:ignore", "diag:relancer"]
|
||||
PERMISSIONS = ["conversations:read", "conversations:read_all", "messages:read", "messages:write_private",
|
||||
"conversations:update_tags"]
|
||||
jar = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||
|
||||
|
||||
def req(m, p, body=None):
|
||||
"""Une requête de l'admin (session) ; s'arrête sur une erreur."""
|
||||
r = urllib.request.Request(B + p, method=m, data=json.dumps(body).encode() if body is not None else None,
|
||||
headers={"Content-Type": "application/json", "X-CSRFTOKEN": "t0k3n"})
|
||||
try:
|
||||
with op.open(r) as x:
|
||||
return json.loads(x.read() or b"{}").get("data")
|
||||
except urllib.error.HTTPError as e:
|
||||
sys.exit(f"{m} {p} : {e.code} {e.read().decode()[:300]}")
|
||||
|
||||
|
||||
def main(mot_de_passe: str, fichier: str) -> None:
|
||||
req("POST", "/api/v1/auth/login", {"email": "System", "password": mot_de_passe})
|
||||
for c in jar:
|
||||
c.secure = False # cookies Secure : http local
|
||||
jar.set_cookie(http.cookiejar.Cookie(0, "csrf_token", "t0k3n", None, False, "127.0.0.1", False, False, "/", True,
|
||||
False, None, False, None, None, {})) # le serveur compare cookie et en-tête
|
||||
smtp = {"enabled": True, "host": "mailpit", "port": 1025, "username": "", "password": "", "auth_protocol": "none",
|
||||
"tls_type": "none", "max_conns": 1, "max_msg_retries": 0, "idle_timeout": "5s", "pool_wait_timeout": "5s",
|
||||
"hello_hostname": ""}
|
||||
imap = {"host": "127.0.0.1", "port": 1, "username": "x", "password": "x", "mailbox": "INBOX",
|
||||
"read_interval": "1h", "scan_inbox_since": "1h", "tls_type": "none"}
|
||||
boite = req("POST", "/api/v1/inboxes", {"name": "Test", "channel": "email", "enabled": True, "csat_enabled": False,
|
||||
"from": "Support <support@example.com>",
|
||||
"config": {"auth_type": "password", "from": "Support <support@example.com>",
|
||||
"smtp": [smtp], "imap": [imap]}})
|
||||
for nom in ETIQUETTES:
|
||||
req("POST", "/api/v1/tags", {"name": nom})
|
||||
req("POST", "/api/v1/roles", {"name": "Agent IA", "description": "notes privées seulement",
|
||||
"permissions": PERMISSIONS})
|
||||
agent = req("POST", "/api/v1/agents", {"first_name": "Agent", "last_name": "IA", "email": "agent-ia@example.com",
|
||||
"roles": ["Agent IA"], "send_welcome_email": False, "enabled": True})
|
||||
cle = req("POST", f"/api/v1/agents/{agent['id']}/api-key")
|
||||
texte = Path(fichier).read_text().strip()
|
||||
contenu = "".join(f"<p>{html.escape(p).replace(chr(10), '<br>')}</p>" for p in texte.split("\n\n"))
|
||||
conv = req("POST", "/api/v1/conversations", {"inbox_id": boite["id"], "contact_email": "client@example.com",
|
||||
"first_name": "Client", "last_name": "Test", "initiator": "contact",
|
||||
"subject": "Courbes de la station", "content": contenu})
|
||||
req("POST", f"/api/v1/conversations/{conv['uuid']}/tags", {"tags": ["tri:diagnostic"], "action": "add_tags"})
|
||||
env = Path(__file__).with_name(".env")
|
||||
env.write_text(f"LIBREDESK_URL={B}\nLIBREDESK_API_KEY={cle['api_key']}\nLIBREDESK_API_SECRET={cle['api_secret']}\n"
|
||||
f"CONVERSATION={conv['uuid']}\n")
|
||||
print(f"prête : conversation {conv['uuid']}, réglages dans {env}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(*sys.argv[1:3])
|
||||
@@ -68,8 +68,8 @@ def fil(messages: list[dict], moi: int) -> tuple[str, str]:
|
||||
blocs, notes = [], []
|
||||
for m in sorted(messages, key=lambda m: m["created_at"], reverse=True):
|
||||
texte = (m.get("text_content") or m.get("content") or "").strip()
|
||||
if m.get("private"):
|
||||
if m.get("sender_id") != moi and texte:
|
||||
if m.get("private"): # les activités (« X added tag … ») sont privées aussi : seules les notes comptent
|
||||
if m.get("type") == "outgoing" and m.get("sender_id") != moi and texte:
|
||||
notes.append(texte)
|
||||
continue
|
||||
if m.get("type") not in ("incoming", "outgoing") or not texte:
|
||||
|
||||
@@ -56,6 +56,11 @@ class TestDiagnostic(unittest.TestCase):
|
||||
r = self.lancer(reponse([Bloc(type="text", text="Quelle station ?")], "end_turn"))
|
||||
self.assertEqual((r.statut, r.texte), ("ignore", "Quelle station ?"))
|
||||
|
||||
def test_outils_lances_par_le_python_courant(self):
|
||||
import sys
|
||||
import outils # agents/support, mis dans sys.path par diagnostic.py
|
||||
self.assertEqual(outils.PY, sys.executable) # pas agents/.venv, absent sur le runner
|
||||
|
||||
def test_erreur_api_leve(self):
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.lancer(ConnectionError("API injoignable"))
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""De bout en bout sur l'instance de test préparée (instance-de-test/preparer.py), sans appel à l'API Anthropic.
|
||||
Sauté sans LIBREDESK_TEST_URL."""
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from support_diagnostic.diagnostic import Resultat
|
||||
from support_diagnostic.libredesk import LibreDesk
|
||||
from support_diagnostic.run import Config, traiter
|
||||
|
||||
MAILPIT = "http://127.0.0.1:9125/api/v1/messages"
|
||||
|
||||
|
||||
def mailpit() -> int:
|
||||
return json.load(urllib.request.urlopen(MAILPIT))["messages_count"]
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("LIBREDESK_TEST_URL"), "instance de test non préparée")
|
||||
class TestInstance(unittest.TestCase):
|
||||
def test_bout_en_bout_sans_envoi(self):
|
||||
conv = os.environ["CONVERSATION"]
|
||||
cfg = Config.depuis_env({**os.environ, "DRY_RUN": "false", "ALLOWED_CONVERSATION_IDS": conv})
|
||||
ld = LibreDesk(cfg.url, cfg.cle, cfg.secret, ecrire=True)
|
||||
avant = mailpit()
|
||||
mails = []
|
||||
|
||||
def diag(mail, images, contexte, donnees, cases):
|
||||
mails.append(mail)
|
||||
return Resultat("fait", "Bonjour,\n\nProposition factice.", [], 0.0, None)
|
||||
|
||||
self.assertEqual(traiter(ld, cfg, diag), {conv: "fait"})
|
||||
self.assertIn("LENZSPITZE", mails[0])
|
||||
etiquettes = ld.etiquettes(conv)
|
||||
self.assertIn("diag:fait", etiquettes)
|
||||
self.assertNotIn("diag:en-cours", etiquettes)
|
||||
dernier = max((m for m in ld.messages(conv) if m["type"] != "activity"), key=lambda m: m["created_at"])
|
||||
self.assertIs(dernier["private"], True)
|
||||
self.assertIn("BROUILLON IA", dernier["content"])
|
||||
self.assertIn("Proposition factice.", dernier["content"])
|
||||
self.assertEqual(mailpit(), avant)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+1
-1
@@ -148,7 +148,7 @@ class TestCycle(unittest.TestCase):
|
||||
msg("incoming", "Mes courbes ?", quand="2026-11-09T08:00:00Z"),
|
||||
msg("outgoing", "BROUILLON IA ancien", private=True, sender=MOI, quand="2026-11-09T09:00:00Z"),
|
||||
msg("outgoing", "C'est Crissier, station LENZSPITZE", private=True, sender=7, quand="2026-11-09T10:00:00Z"),
|
||||
msg("activity", "Marc a posé diag:relancer", sender=7, quand="2026-11-09T10:01:00Z"),
|
||||
msg("activity", "Marc a posé diag:relancer", private=True, sender=7, quand="2026-11-09T10:01:00Z"),
|
||||
], MOI)
|
||||
self.assertIn("Mes courbes ?", mail)
|
||||
self.assertNotIn("BROUILLON", mail + contexte)
|
||||
|
||||
Reference in new issue
Block a user