Files
ai-agent/backend/test_guest_cron.py
gabrielvidalandClaude Opus 5.5 b3b58674ef feat(cron): a guest job's RIEN_DE_NOUVEAU reply is silent; the mailed result renders tables
A final reply of exactly RIEN_DE_NOUVEAU (or NOTHING_NEW) sends no push and
no mail — the run stays in the history — so a job can poll hourly and only
speak when there's news. The mail's light markdown now renders GitHub-style
tables (alignment row included) instead of raw | lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 18:31:57 +01:00

323 lines
17 KiB
Python

"""A guest's own scheduled jobs (cron/guests.py, cron/guest_routes.py): the
REST a guest's page and their runs' `ai-agent cron` use, the limits, how a
firing is pinned (as the guest, lean, confined, on Qwen with a Sonnet
fallback), the owner's view and extras, read-only runs + « Discuter », and
the delivery of a run's result.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
import unittest
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"PROJECTS_DIR": TMP / "projects",
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
(TMP / "projects" / "film").mkdir(parents=True)
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
import runs.service as run_service # noqa: E402
from cron import guests # noqa: E402
from users import access # noqa: E402
from users.caller import SESSION_COOKIE, guest_from_record # noqa: E402
from authz import routes as authz_routes # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
ORIGIN = {"Origin": "https://claude.example.test"}
JOB = {"name": "Revue de presse", "schedule": "15 8 * * 1-5",
"prompt": "Les 5 nouvelles santé du jour, en français."}
class GuestCron(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
for j in DEPS.cron_store.list():
DEPS.cron_store.delete(j["id"])
self.arthur = DEPS.users.create("arthur@example.com", "Arthur", models=["sonnet"])
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
self.c = TestClient(main.app)
self.pings = []
import notifications.service as notif
orig = notif._create_notify
notif._create_notify = lambda deps, d: self.pings.append(d) or {"id": "n"}
self.addCleanup(setattr, notif, "_create_notify", orig)
def guest(self, uid="arthur"):
c = TestClient(main.app, base_url="https://claude.example.test")
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(uid))
return c
def _capture(self):
calls = []
orig = run_service._send_message
run_service._send_message = lambda deps, prompt, **kw: (
calls.append((prompt, kw)) or {"sessionId": f"0000000{len(calls)}-0000-0000-0000-000000000000",
"pid": 1})
self.addCleanup(setattr, run_service, "_send_message", orig)
return calls
# ── the guest's REST ─────────────────────────────────────────────────────
def test_a_guest_creates_lists_edits_and_removes_their_job(self):
g = self.guest()
r = g.post("/api/me/cron", json=JOB, headers=ORIGIN)
self.assertEqual(r.status_code, 200, r.text)
j = r.json()
self.assertTrue(j["id"].startswith("arthur-"))
self.assertEqual((j["model"], j["project"], j["email"], j["allow"]),
("qwen", None, False, []))
self.assertIsNotNone(j["nextRun"])
stored = DEPS.cron_store.get(j["id"])
self.assertEqual(stored["owner"], "arthur")
self.assertIsNone(stored.get("promptFile"))
# the owner hears of it
self.assertTrue(any("Arthur scheduled a job" in p["title"] for p in self.pings))
self.assertEqual([x["id"] for x in g.get("/api/me/cron").json()["jobs"]], [j["id"]])
r = g.put(f"/api/me/cron/{j['id']}", json={"model": "sonnet", "email": True,
"enabled": False}, headers=ORIGIN)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual((r.json()["model"], r.json()["email"], r.json()["enabled"]),
("sonnet", True, False))
self.assertIsNone(r.json()["nextRun"])
self.assertEqual(g.delete(f"/api/me/cron/{j['id']}", headers=ORIGIN).status_code, 200)
self.assertIsNone(DEPS.cron_store.get(j["id"]))
def test_ids_fold_accents(self):
j = self.guest().post("/api/me/cron", json={**JOB, "name": "Veille pharma santé"},
headers=ORIGIN).json()
self.assertEqual(j["id"], "arthur-veille-pharma-sante")
def test_schedules_fire_at_most_once_an_hour(self):
g = self.guest()
for bad in ("*/15 * * * *", "0,30 8 * * *", "0-5 8 * * *", "nope"):
r = g.post("/api/me/cron", json={**JOB, "schedule": bad}, headers=ORIGIN)
self.assertEqual(r.status_code, 400, bad)
self.assertEqual(r.json()["detail"]["kind"], "cron_schedule")
for ok in ("0 */6 * * *", "30 7,19 * * *", "0 9 1 * *"):
self.assertEqual(g.post("/api/me/cron", json={**JOB, "schedule": ok},
headers=ORIGIN).status_code, 200, ok)
def test_the_job_limit_and_the_project_check(self):
DEPS.users.set_defaults({"cronLimits": {"maxJobs": 2}})
self.addCleanup(DEPS.users.set_defaults, {"cronLimits": {"maxJobs": 5}})
g = self.guest()
for _ in range(2):
self.assertEqual(g.post("/api/me/cron", json=JOB, headers=ORIGIN).status_code, 200)
r = g.post("/api/me/cron", json=JOB, headers=ORIGIN)
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (409, "cron_limit"))
# a project they don't hold chat on
r = self.guest("dom").post("/api/me/cron", json={**JOB, "project": "other"}, headers=ORIGIN)
self.assertEqual(r.json()["detail"]["kind"], "guest_project")
r = self.guest("dom").post("/api/me/cron", json={**JOB, "project": "film"}, headers=ORIGIN)
self.assertEqual(r.json()["project"], "film")
def test_nobody_reaches_another_guests_job(self):
j = self.guest().post("/api/me/cron", json=JOB, headers=ORIGIN).json()
d = self.guest("dom")
self.assertEqual(d.get("/api/me/cron").json()["jobs"], [])
for method, path in (("put", f"/api/me/cron/{j['id']}"), ("delete", f"/api/me/cron/{j['id']}"),
("post", f"/api/me/cron/{j['id']}/run")):
kw = {"json": {"enabled": False}} if method == "put" else {}
r = getattr(d, method)(path, headers=ORIGIN, **kw)
self.assertEqual(r.status_code, 404, path)
# the owner's are elsewhere, and a guest never reaches /api/cron
self.assertEqual(self.c.get("/api/me/cron", headers=OWNER_H).status_code, 404)
self.assertEqual(self.guest().get("/api/cron").status_code, 403)
def test_a_guest_cannot_grant_their_job_programs(self):
j = self.guest().post("/api/me/cron", json={**JOB, "allow": ["bash"], "effort": "max"},
headers=ORIGIN).json()
self.assertEqual(DEPS.cron_store.get(j["id"])["allow"], [])
# ── firing ───────────────────────────────────────────────────────────────
def test_a_qwen_job_fires_as_the_guest_lean_and_confined(self):
calls = self._capture()
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), dict(JOB))
out = guests.fire(DEPS, job)
prompt, kw = calls[0]
self.assertTrue(prompt.startswith('<ai-agent-from user="arthur"'))
self.assertEqual((kw["harness"], kw["model"], kw["worker"], kw["run_as"]),
("pi", guests.QWEN_MODEL, "local", "arthur"))
self.assertIn("web", kw["lean"]["allow"])
self.assertNotIn("WebSearch", kw["lean"]["tools"])
self.assertEqual(kw["cwd"], guests.job_dir("arthur"))
self.assertEqual(kw["scope"]["writeDirs"], [guests.job_dir("arthur"), "/tmp"])
self.assertIn("Your final reply is the result", kw["scope"]["systemPrompt"])
self.assertEqual(kw["stamp"], {"owner": "arthur", "projects": []})
m = DEPS.meta_store.peek(out["sessionId"])
self.assertEqual(m["cron"]["guest"], "arthur")
self.assertEqual(DEPS.cron_store.get(job["id"])["lastStatus"], "ok")
def test_the_fallback_runs_on_sonnet_with_web_tools(self):
calls = self._capture()
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), dict(JOB))
guests.fire(DEPS, job, fallback="EVOX2 asleep")
_, kw = calls[0]
self.assertEqual((kw["harness"], kw["model"], kw["account"]), ("claude", "sonnet", "personal"))
self.assertIn("WebSearch", kw["lean"]["tools"])
self.assertIn("maxBudgetUsd", kw["scope"]) # under their budget
self.assertTrue(DEPS.cron_store.get(job["id"])["lastStatus"].startswith("ok (fallback"))
def test_a_disabled_guests_job_does_not_fire(self):
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), dict(JOB))
DEPS.users.update("arthur", {"disabled": True})
guests.scheduler_fire(DEPS, job, probed=True)
self.assertTrue(DEPS.cron_store.get(job["id"])["lastStatus"].startswith("error"))
# ── the owner's side ─────────────────────────────────────────────────────
def test_the_owner_sees_and_extends_guest_jobs(self):
r = self.c.post("/api/cron", headers=OWNER_H, json={
**JOB, "owner": "arthur", "model": "sonnet", "allow": ["veille-pharma", "rm -rf"],
"effort": "medium"})
self.assertEqual(r.status_code, 200, r.text)
j = r.json()
self.assertEqual((j["owner"], j["ownerName"], j["allow"]),
("arthur", "Arthur", ["veille-pharma"]))
self.assertEqual(j["runConfig"]["effort"], "medium")
self.assertIn("veille-pharma", j["runConfig"]["lean"]["allow"])
self.assertEqual(self.pings, []) # no ping for his own doing
r = self.c.put(f"/api/cron/{j['id']}", headers=OWNER_H, json={"allow": []})
self.assertEqual(r.json()["allow"], [])
listed = {x["id"]: x for x in self.c.get("/api/cron", headers=OWNER_H).json()["jobs"]}
self.assertEqual(listed[j["id"]]["prompt"], JOB["prompt"])
# the guest sees the owner's extras, can't change them
mine = self.guest().get("/api/me/cron").json()["jobs"][0]
self.assertEqual(mine["id"], j["id"])
# ── conversations ────────────────────────────────────────────────────────
def test_a_job_run_is_read_only_but_stoppable_and_discussed_elsewhere(self):
calls = self._capture()
arthur = guest_from_record(DEPS.users.get("arthur"))
job = guests.create(DEPS, arthur, dict(JOB))
sid = guests.fire(DEPS, job)["sessionId"]
DEPS.meta_store.update(sid, {"owner": "arthur"})
self.assertFalse(access.can_send(DEPS, arthur, sid))
self.assertTrue(access.can_send(DEPS, arthur, sid, stop=True))
orig = guests.final_answer
guests.final_answer = lambda deps, s: ("c1", "Le résumé du jour.")
self.addCleanup(setattr, guests, "final_answer", orig)
r = self.guest().post(f"/api/me/cron/{job['id']}/discuss",
json={"sessionId": sid, "prompt": "Développe le point 2"},
headers=ORIGIN)
self.assertEqual(r.status_code, 200, r.text)
prompt, kw = calls[-1]
self.assertIn("Développe le point 2", prompt)
self.assertIn("Le résumé du jour.", prompt)
self.assertEqual((kw["harness"], kw.get("lean")), ("claude", None))
self.assertEqual(kw["stamp"]["cronChat"], {"id": job["id"], "from": sid})
chat = r.json()["sessionId"]
DEPS.meta_store.update(chat, {"owner": "arthur", "cronChat": {"id": job["id"], "from": sid}})
self.assertTrue(access.can_send(DEPS, arthur, chat))
DEPS.cron_store.delete(job["id"])
self.assertFalse(access.can_send(DEPS, arthur, chat))
def test_the_result_is_pushed_once_when_the_run_ends(self):
self._capture()
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), dict(JOB))
sid = guests.fire(DEPS, job)["sessionId"]
DEPS.meta_store.update(sid, {"exitedAt": "2026-11-04T08:20:00Z"})
orig = guests.final_answer
guests.final_answer = lambda deps, s: ("c1", "# Revue\n\n**ANSM** : " + "x" * 400)
self.addCleanup(setattr, guests, "final_answer", orig)
self.pings.clear()
self.assertEqual(guests.deliver_sweep(DEPS), 1)
self.assertEqual(guests.deliver_sweep(DEPS), 0) # once
p = self.pings[0]
self.assertEqual((p["title"], p["sessionId"], p["type"]), ("⏰ Revue de presse", sid, "success"))
self.assertLessEqual(len(p["message"]), guests.PUSH_CHARS)
self.assertNotIn("**", p["message"])
def test_a_nothing_new_reply_is_silent(self):
self._capture()
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), dict(JOB))
sid = guests.fire(DEPS, job)["sessionId"]
DEPS.meta_store.update(sid, {"exitedAt": "2026-11-04T08:20:00Z"})
orig = guests.final_answer
guests.final_answer = lambda deps, s: ("c1", " RIEN_DE_NOUVEAU\n")
self.addCleanup(setattr, guests, "final_answer", orig)
self.pings.clear()
self.assertEqual(guests.deliver_sweep(DEPS), 1)
self.assertEqual(guests.deliver_sweep(DEPS), 0) # handled, not retried
self.assertEqual(self.pings, [])
self.assertFalse(guests.is_silent("RIEN_DE_NOUVEAU depuis hier"))
def test_the_mailed_result_renders_tables(self):
md = ("## Jour\n\n| Jour | Gain | Coût |\n|---|---|---:|\n"
"| **24 nov.** | 🟩🟩 | 0,64 € |\n| 23 nov. | 🟩 | 0,48 € |\n\nfin")
html = guests._markdown_html(md, "https://v")
self.assertIn("<table", html)
self.assertIn(">Jour</th>", html)
self.assertIn('text-align:right">0,64 €</td>', html)
self.assertIn("<b>24 nov.</b></td>", html)
self.assertNotIn("|", html)
self.assertIn("<p>fin</p>", html)
def test_the_mailed_result_is_escaped_html(self):
html = guests._markdown_html("# Titre\n\n- **un** <b>x</b>\n- [lien](https://a.b/c)", "https://v")
self.assertIn("<h2>Titre</h2>", html)
self.assertIn("<li><b>un</b> &lt;b&gt;x&lt;/b&gt;</li>", html)
self.assertIn('<a href="https://a.b/c">lien</a>', html)
def test_their_runs_cli_reaches_their_jobs(self):
import re
paths = [("GET", "/api/me/cron"), ("POST", "/api/me/cron"),
("PUT", "/api/me/cron/arthur-x"), ("POST", "/api/me/cron/arthur-x/run")]
cli = guest_from_record(DEPS.users.create("cli@example.com", "Cli")).narrowed("cli")
table = authz_routes.matcher(main.app)
for m, p in paths:
self.assertTrue(cli.allows(table.required(m, p), m), p)
def test_new_guests_get_the_cli(self):
from authz import policy
self.assertTrue(policy.has(DEPS.users.create("new@example.com", "New"), "cli.use"))
if __name__ == "__main__":
unittest.main()
class RealDelivery(unittest.TestCase):
"""The delivery through the real notify path (no stub): a feed entry for
the run's session, its meta stamped."""
def test_deliver_records_a_push_for_the_guest(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
DEPS.users.create("arthur@example.com", "Arthur", models=["sonnet"])
calls = []
orig = run_service._send_message
run_service._send_message = lambda deps, prompt, **kw: (
calls.append(kw) or {"sessionId": "0000000a-0000-0000-0000-000000000000", "pid": 1})
self.addCleanup(setattr, run_service, "_send_message", orig)
job = guests.create(DEPS, guest_from_record(DEPS.users.get("arthur")), dict(JOB), as_owner=True)
sid = guests.fire(DEPS, job)["sessionId"]
DEPS.meta_store.update(sid, {"owner": "arthur", "exitedAt": "2026-11-04T08:20:00Z"})
orig_fa = guests.final_answer
guests.final_answer = lambda deps, s: ("c1", "Le résumé.")
self.addCleanup(setattr, guests, "final_answer", orig_fa)
orig_dep = guests._maintenance
guests._maintenance = lambda deps: True # a cutover: wait
self.assertEqual(guests.deliver_sweep(DEPS), 0)
guests._maintenance = orig_dep
self.assertEqual(guests.deliver_sweep(DEPS), 1)
entries = [e for e in DEPS.notify_store.log(limit=50) if e.get("sessionId") == sid]
self.assertEqual(len(entries), 1, entries)
self.assertEqual(entries[0]["title"], "⏰ Revue de presse")
self.assertIn("arthur", entries[0]["to"])