Relecture : relance en échec, verrou, liste blanche, réponse invérifiable, étiquettes du contrat, clé hors LibreDesk, test d'instance local seulement
tests / tests (push) Failing after 1m5s
tests / tests (push) Failing after 1m5s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b48d756883
commit
d65e9b49d0
6 files changed
+77
-17
No files matched your search
@@ -19,10 +19,11 @@ class LibreDesk:
|
||||
self._auth = f"token {cle}:{secret}"
|
||||
|
||||
def _requete(self, methode: str, chemin: str, corps: dict | None = None) -> bytes:
|
||||
r = urllib.request.Request(urllib.parse.urljoin(self.url + "/", chemin.lstrip("/")), method=methode,
|
||||
data=json.dumps(corps).encode() if corps is not None else None,
|
||||
url = urllib.parse.urljoin(self.url + "/", chemin.lstrip("/"))
|
||||
r = urllib.request.Request(url, method=methode, data=json.dumps(corps).encode() if corps is not None else None,
|
||||
headers={"Content-Type": "application/json"})
|
||||
r.add_unredirected_header("Authorization", self._auth) # pas vers S3 si une pièce redirige
|
||||
if urllib.parse.urlsplit(url)[:2] == urllib.parse.urlsplit(self.url)[:2]: # la clé ne va qu'à LibreDesk
|
||||
r.add_unredirected_header("Authorization", self._auth) # ni à S3 si une pièce y redirige
|
||||
with urllib.request.urlopen(r, timeout=30) as rep:
|
||||
return rep.read()
|
||||
|
||||
@@ -82,6 +83,8 @@ class LibreDesk:
|
||||
{"message": html, "private": True, "sender_type": "agent"})
|
||||
except urllib.error.HTTPError as e:
|
||||
raise Garde(f"note privée refusée ({e.code}) sur {uuid}") from e
|
||||
except Exception as e: # injoignable, délai, réponse illisible : rien ne prouve une note privée
|
||||
raise Garde(f"réponse invérifiable à la note sur {uuid} : {type(e).__name__}: {e}") from e
|
||||
if not isinstance(m, dict) or m.get("private") is not True:
|
||||
raise Garde(f"la réponse de LibreDesk n'est pas une note privée ({uuid}) : {str(m)[:200]}")
|
||||
return m
|
||||
@@ -16,6 +16,7 @@ from typing import Mapping
|
||||
from .libredesk import Garde, LibreDesk
|
||||
|
||||
TRI, EN_COURS, RELANCER = "tri:diagnostic", "diag:en-cours", "diag:relancer"
|
||||
ETIQUETTES = [TRI, EN_COURS, "diag:fait", "diag:erreur", "diag:ignore", RELANCER] # le contrat (README)
|
||||
ENTETE = "<p><strong>🤖 BROUILLON IA — à relire, ne pas envoyer tel quel</strong></p>"
|
||||
TYPES_IMAGE = {"image/png", "image/jpeg", "image/gif", "image/webp"}
|
||||
TAILLE_MIN = 10_000 # ponytail: octets, écarte les logos des signatures (comme Support-Agent)
|
||||
@@ -28,7 +29,7 @@ class Config:
|
||||
cle: str
|
||||
secret: str
|
||||
ecrire: bool
|
||||
autorisees: set[str] | None # None : toutes (« * »)
|
||||
autorisees: set[str] | None # None : toutes (« * ») ; vide (simulation sans liste) : aucune
|
||||
plafond: int
|
||||
conversation: str # "" : toutes les éligibles
|
||||
donnees: Path
|
||||
@@ -41,9 +42,9 @@ class Config:
|
||||
return None
|
||||
ecrire = env.get("DRY_RUN", "true").strip() == "false"
|
||||
liste = env.get("ALLOWED_CONVERSATION_IDS", "").strip()
|
||||
if ecrire and not liste:
|
||||
autorisees = None if liste == "*" else {u.strip() for u in liste.split(",") if u.strip()}
|
||||
if ecrire and autorisees is not None and not autorisees: # « , » ne vaut pas « * »
|
||||
raise ValueError("DRY_RUN=false exige ALLOWED_CONVERSATION_IDS (des uuid séparés par des virgules, ou *)")
|
||||
autorisees = None if liste == "*" else {u.strip() for u in liste.split(",") if u.strip()} or None
|
||||
return Config(env["LIBREDESK_URL"], env["LIBREDESK_API_KEY"], env["LIBREDESK_API_SECRET"], ecrire, autorisees,
|
||||
int(env.get("MAX_CONVERSATIONS_PER_RUN") or 3), env.get("CONVERSATION", "").strip(),
|
||||
Path(env.get("AIMSIGHT_DATA") or "data"),
|
||||
@@ -52,7 +53,7 @@ class Config:
|
||||
|
||||
def eligible(etiquettes: list[str]) -> bool:
|
||||
diag = [t for t in etiquettes if t.startswith("diag:")]
|
||||
return TRI in etiquettes and (not diag or RELANCER in diag)
|
||||
return TRI in etiquettes and EN_COURS not in diag and (not diag or RELANCER in diag)
|
||||
|
||||
|
||||
def _objet(s: str | None) -> str:
|
||||
@@ -130,10 +131,13 @@ def traiter(ld, cfg: Config, diag=None) -> dict[str, str]:
|
||||
if diag is None:
|
||||
from .diagnostic import diagnostiquer as diag
|
||||
debut, execution, statuts, couts = time.monotonic(), _execution(), {}, {}
|
||||
ids = ld.ids_etiquettes()
|
||||
if cfg.ecrire and (manque := [t for t in ETIQUETTES if t not in ids]):
|
||||
raise RuntimeError(f"étiquettes absentes de LibreDesk, à créer par un admin : {manque}")
|
||||
if cfg.conversation:
|
||||
candidates = [cfg.conversation]
|
||||
else:
|
||||
candidates = [c["uuid"] for c in ld.conversations(ld.ids_etiquettes()[TRI])]
|
||||
candidates = [c["uuid"] for c in ld.conversations(ids[TRI])]
|
||||
for uuid in candidates:
|
||||
if len(statuts) >= cfg.plafond:
|
||||
break
|
||||
@@ -145,15 +149,16 @@ def traiter(ld, cfg: Config, diag=None) -> dict[str, str]:
|
||||
statuts[uuid], couts[uuid] = r.statut, r.cout
|
||||
except Garde:
|
||||
try:
|
||||
ld.etiqueter(uuid, ["diag:erreur"], [EN_COURS])
|
||||
finally:
|
||||
raise
|
||||
ld.etiqueter(uuid, ["diag:erreur"], [EN_COURS, RELANCER])
|
||||
except Exception as e2: # noqa: BLE001 — c'est le Garde qui doit remonter
|
||||
print(f"[erreur] {uuid} : {type(e2).__name__}: {e2}", flush=True)
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 — une conversation en échec n'arrête pas les autres
|
||||
print(f"[erreur] {uuid} : {type(e).__name__}: {e}", flush=True)
|
||||
statuts[uuid], couts[uuid] = "erreur", 0.0
|
||||
for essai in (lambda: ld.note_privee(uuid, f"{ENTETE}<p>Diagnostic en échec : {html.escape(type(e).__name__)}."
|
||||
f"</p><hr><p><small>Exécution {html.escape(execution)}</small></p>"),
|
||||
lambda: ld.etiqueter(uuid, ["diag:erreur"], [EN_COURS])):
|
||||
lambda: ld.etiqueter(uuid, ["diag:erreur"], [EN_COURS, RELANCER])):
|
||||
try:
|
||||
essai()
|
||||
except Garde:
|
||||
|
||||
@@ -9,7 +9,7 @@ class FauxLibreDesk:
|
||||
def __init__(self):
|
||||
self.requetes: list[tuple[str, str, dict | None]] = [] # (méthode, chemin avec la requête, corps JSON)
|
||||
self.entetes: list[dict] = []
|
||||
self.reponses: dict[tuple[str, str], object] = {} # (méthode, chemin sans requête) → data, ou un code d'erreur
|
||||
self.reponses: dict[tuple[str, str], object] = {} # (méthode, chemin sans requête) → data, code d'erreur, ou bytes bruts
|
||||
faux = self
|
||||
|
||||
class Gestion(BaseHTTPRequestHandler):
|
||||
@@ -23,7 +23,8 @@ class FauxLibreDesk:
|
||||
if callable(r):
|
||||
r = r(self.path)
|
||||
code = r if isinstance(r, int) else 200
|
||||
texte = json.dumps({"message": "erreur"} if isinstance(r, int) else {"data": r}).encode()
|
||||
texte = r if isinstance(r, bytes) else json.dumps(
|
||||
{"message": "erreur"} if isinstance(r, int) else {"data": r}).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(texte)))
|
||||
|
||||
@@ -3,6 +3,7 @@ Sauté sans LIBREDESK_TEST_URL."""
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
@@ -20,8 +21,12 @@ def mailpit() -> int:
|
||||
@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):
|
||||
url = os.environ["LIBREDESK_TEST_URL"]
|
||||
if urllib.parse.urlsplit(url).hostname not in ("127.0.0.1", "localhost"): # jamais la production
|
||||
self.fail(f"LIBREDESK_TEST_URL doit être l'instance locale, pas {url}")
|
||||
conv = os.environ["CONVERSATION"]
|
||||
cfg = Config.depuis_env({**os.environ, "DRY_RUN": "false", "ALLOWED_CONVERSATION_IDS": conv})
|
||||
cfg = Config.depuis_env({**os.environ, "LIBREDESK_URL": url, "DRY_RUN": "false",
|
||||
"ALLOWED_CONVERSATION_IDS": conv})
|
||||
ld = LibreDesk(cfg.url, cfg.cle, cfg.secret, ecrire=True)
|
||||
if not set(ld.etiquettes(conv)) <= {"tri:diagnostic"}: # déjà traitée : relancer, comme un humain
|
||||
ld.etiqueter(conv, ["diag:relancer"])
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import socket
|
||||
import unittest
|
||||
import urllib.parse
|
||||
|
||||
@@ -35,6 +36,26 @@ class TestLibreDesk(unittest.TestCase):
|
||||
with self.assertRaises(Garde):
|
||||
self.ld().note_privee("c1", "<p>x</p>")
|
||||
|
||||
def test_reponse_illisible_leve_garde(self):
|
||||
self.faux.reponses[NOTE] = b"<html>proxy</html>"
|
||||
with self.assertRaises(Garde):
|
||||
self.ld().note_privee("c1", "<p>x</p>")
|
||||
with socket.socket() as libre: # un port fermé : injoignable
|
||||
libre.bind(("127.0.0.1", 0))
|
||||
port = libre.getsockname()[1]
|
||||
with self.assertRaises(Garde):
|
||||
LibreDesk(f"http://127.0.0.1:{port}", "k", "s", ecrire=True).note_privee("c1", "<p>x</p>")
|
||||
|
||||
def test_piece_n_envoie_la_cle_qu_a_libredesk(self):
|
||||
ailleurs = FauxLibreDesk()
|
||||
self.addCleanup(ailleurs.arreter)
|
||||
ailleurs.reponses[("GET", "/s3/capture.png")] = b"png"
|
||||
self.assertEqual(self.ld().piece(ailleurs.url + "/s3/capture.png"), b"png")
|
||||
self.assertNotIn("Authorization", ailleurs.entetes[-1])
|
||||
self.faux.reponses[("GET", "/uploads/capture.png")] = b"png"
|
||||
self.ld().piece("/uploads/capture.png")
|
||||
self.assertEqual(self.faux.entetes[-1]["Authorization"], "token k:s")
|
||||
|
||||
def test_simulation_n_ecrit_rien(self):
|
||||
ld = self.ld(ecrire=False)
|
||||
self.assertIsNone(ld.note_privee("c1", "<p>x</p>"))
|
||||
|
||||
+27
-2
@@ -3,7 +3,7 @@ from pathlib import Path
|
||||
|
||||
from support_diagnostic.diagnostic import Resultat
|
||||
from support_diagnostic.libredesk import Garde
|
||||
from support_diagnostic.run import Config, eligible, fil, note, traiter
|
||||
from support_diagnostic.run import ETIQUETTES, Config, eligible, fil, note, traiter
|
||||
|
||||
ENTETE = "<p><strong>🤖 BROUILLON IA — à relire, ne pas envoyer tel quel</strong></p>"
|
||||
MOI = 4
|
||||
@@ -29,7 +29,7 @@ class FauxLD:
|
||||
return MOI
|
||||
|
||||
def ids_etiquettes(self):
|
||||
return {"tri:diagnostic": 1}
|
||||
return {t: i for i, t in enumerate(ETIQUETTES)}
|
||||
|
||||
def conversations(self, avec):
|
||||
return [{"uuid": u} for u, t in self.tags.items() if "tri:diagnostic" in t]
|
||||
@@ -76,6 +76,11 @@ class TestConfig(unittest.TestCase):
|
||||
self.assertIsNone(cfg().autorisees)
|
||||
self.assertEqual(cfg(ALLOWED_CONVERSATION_IDS="c1, c2").autorisees, {"c1", "c2"})
|
||||
|
||||
def test_liste_blanche_mal_formee(self):
|
||||
for v in (",", " , ", ",,"):
|
||||
with self.assertRaises(ValueError, msg=v):
|
||||
cfg(ALLOWED_CONVERSATION_IDS=v)
|
||||
|
||||
def test_kill_switch(self):
|
||||
self.assertIsNone(Config.depuis_env({**ENV, "KILL_SWITCH": "1"}))
|
||||
for v in ("false", "0", ""):
|
||||
@@ -92,6 +97,7 @@ class TestCycle(unittest.TestCase):
|
||||
self.assertTrue(eligible(["tri:diagnostic", "diag:fait", "diag:relancer"]))
|
||||
self.assertFalse(eligible([]))
|
||||
self.assertFalse(eligible(["diag:relancer"]))
|
||||
self.assertFalse(eligible(["tri:diagnostic", "diag:fait", "diag:relancer", "diag:en-cours"]))
|
||||
|
||||
def test_plafond_et_liste_blanche(self):
|
||||
ld = FauxLD({f"c{i}": ["tri:diagnostic"] for i in range(1, 6)})
|
||||
@@ -136,6 +142,25 @@ class TestCycle(unittest.TestCase):
|
||||
self.assertEqual(sorted(ld.tags["c1"]), ["diag:erreur", "tri:diagnostic"])
|
||||
self.assertIn("RuntimeError", ld.notes[0][1])
|
||||
|
||||
def test_relance_en_echec_n_est_plus_eligible(self):
|
||||
ld = FauxLD({"c1": ["tri:diagnostic", "diag:fait", "diag:relancer"]})
|
||||
|
||||
def panne(*a):
|
||||
raise RuntimeError("agents en panne")
|
||||
traiter(ld, cfg(), panne)
|
||||
self.assertFalse(eligible(ld.tags["c1"]), ld.tags["c1"])
|
||||
ld = FauxLD({"c1": ["tri:diagnostic", "diag:fait", "diag:relancer"]}, note_leve=Garde("pas privée"))
|
||||
with self.assertRaises(Garde):
|
||||
traiter(ld, cfg(), diag_fait)
|
||||
self.assertFalse(eligible(ld.tags["c1"]), ld.tags["c1"])
|
||||
|
||||
def test_etiquettes_manquantes_arrete_avant_ecriture(self):
|
||||
ld = FauxLD({"c1": ["tri:diagnostic"]})
|
||||
ld.ids_etiquettes = lambda: {"tri:diagnostic": 1, "diag:en-cours": 2}
|
||||
with self.assertRaises(RuntimeError):
|
||||
traiter(ld, cfg(CONVERSATION="c1"), diag_fait)
|
||||
self.assertEqual((ld.notes, ld.tags["c1"], ld.lus), ([], ["tri:diagnostic"], []))
|
||||
|
||||
def test_garde_arrete_tout(self):
|
||||
ld = FauxLD({"c1": ["tri:diagnostic"], "c2": ["tri:diagnostic"]}, note_leve=Garde("pas privée"))
|
||||
with self.assertRaises(Garde):
|
||||
|
||||
Reference in new issue
Block a user