Every sync re-added the oldest closed forms a machine still listed (new + changed), the GC dropped others, and each read published dozens of askform SSE events (~2/s since 12:50 on 2026-11-27). Every tab then refetched /api/inbox/waiting + /api/ask-form/forms, the 40-thread pool sat at 40/40 and every request waited 30 s (phones gave up: Traefik 499s). - store remembers what its GC dropped; skip_report() keeps the mirror from taking those back, or any closed form older than 30 days it doesn't hold - cap 1000 -> 5000 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
771 lines
40 KiB
Python
771 lines
40 KiB
Python
"""The ask-form mirror (askform/): the store, the per-machine sync against a
|
|
fake sidecar, the push on a new form, the events webhook and the routes.
|
|
``python -m pytest test_askform.py`` from ``backend/`` (its own process: the
|
|
env below is read at import)."""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
|
|
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", "ASKFORM_PATH": TMP / "af.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)
|
|
|
|
from fastapi import HTTPException # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from askform import links, service # noqa: E402
|
|
from askform.mirror import AskFormMirror # noqa: E402
|
|
from askform.store import AskFormStore # noqa: E402
|
|
from conversations import tree # noqa: E402
|
|
from users.caller import OWNER, guest_from_record # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
SID = "11111111-2222-4333-8444-555555555555"
|
|
FID = "project-setup_k3f9q2"
|
|
TOKEN = "w0rker"
|
|
|
|
|
|
def _iso(ago_s: float = 0) -> str:
|
|
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - ago_s))
|
|
|
|
|
|
def _form(fid=FID, status="pending", **kw):
|
|
return {"id": fid, "title": "Project setup", "status": status,
|
|
"createdAt": _iso(), "expiresAt": _iso(-86400), "meta": {"session": SID}, **kw}
|
|
|
|
|
|
class FakeSidecar(BaseHTTPRequestHandler):
|
|
"""A sidecar's /ask-form surface over an in-memory form list."""
|
|
forms: dict = {}
|
|
calls: list = []
|
|
health: dict = {"installed": True, "ok": True, "version": "v0.16.0"}
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def _send(self, code, obj):
|
|
data = json.dumps(obj).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def do_GET(self):
|
|
FakeSidecar.calls.append(("GET", self.path))
|
|
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
|
|
return self._send(401, {"detail": "unauthorized"})
|
|
if self.path == "/ask-form/health":
|
|
return self._send(200, FakeSidecar.health)
|
|
if self.path.startswith("/ask-form/forms/"):
|
|
fid = self.path.split("/")[3].split("?")[0]
|
|
f = self.forms.get(fid)
|
|
if not f:
|
|
return self._send(404, {"detail": {"message": "unknown", "kind": "askform"}})
|
|
out = dict(f)
|
|
if "fields=1" in self.path:
|
|
out["fields"] = [{"key": "stack", "label": "Stack", "type": "radio",
|
|
"options": [{"value": "vite", "label": "Vite"}]}]
|
|
return self._send(200, out)
|
|
if self.path.startswith("/ask-form/forms"):
|
|
return self._send(200, {"forms": list(self.forms.values()), "count": len(self.forms)})
|
|
self._send(404, {"detail": "nope"})
|
|
|
|
def do_POST(self):
|
|
FakeSidecar.calls.append(("POST", self.path))
|
|
if self.path == "/ask-form/embed":
|
|
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
|
|
FakeSidecar.health = {**FakeSidecar.health, "embedOrigins": body["origins"]}
|
|
return self._send(200, {"state": "wired"})
|
|
fid = self.path.split("/")[3]
|
|
f = self.forms.get(fid)
|
|
if not f:
|
|
return self._send(404, {"detail": {"message": "unknown", "kind": "askform"}})
|
|
f["status"] = "revoked"
|
|
f["closedAt"] = _iso()
|
|
self._send(200, f)
|
|
|
|
|
|
_srv = HTTPServer(("127.0.0.1", 0), FakeSidecar)
|
|
threading.Thread(target=_srv.serve_forever, daemon=True).start()
|
|
MACHINE = {"id": "mac-1", "url": f"http://127.0.0.1:{_srv.server_port}", "token": TOKEN,
|
|
"label": "worker mac-1"}
|
|
|
|
|
|
def _reset():
|
|
FakeSidecar.forms = {}
|
|
FakeSidecar.calls = []
|
|
FakeSidecar.health = {"installed": True, "ok": True, "version": "v0.16.0"}
|
|
DEPS.askform_store._forms = {}
|
|
DEPS.notify_store._data["notifications"] = [
|
|
e for e in DEPS.notify_store._data["notifications"]
|
|
if not str(e.get("title", "")).startswith("📋")]
|
|
|
|
|
|
class TestStore(unittest.TestCase):
|
|
def test_upsert_learn_claim(self):
|
|
st = AskFormStore(str(TMP / "store-test.json"))
|
|
rec, new, changed = st.upsert("lab", _form(url=f"http://127.0.0.1:7462/f/{FID}?token=a",
|
|
publicUrl=f"https://ask-form.xyz/f/{FID}?token=a"))
|
|
self.assertTrue(new and changed)
|
|
self.assertEqual((rec["sessionId"], rec["machine"], rec["pushed"]), (SID, "lab", False))
|
|
# The admin list omits the links: a later sync never drops them.
|
|
rec, new, changed = st.upsert("lab", _form())
|
|
self.assertFalse(new or changed)
|
|
self.assertEqual(rec["publicUrl"], f"https://ask-form.xyz/f/{FID}?token=a")
|
|
rec, _, changed = st.upsert("lab", _form(status="submitted", answers={"stack": "vite"}))
|
|
self.assertTrue(changed and rec["answers"] == {"stack": "vite"})
|
|
self.assertTrue(st.claim_push(FID))
|
|
self.assertFalse(st.claim_push(FID)) # once, ever
|
|
self.assertFalse(st.claim_push("unknown_aaaaaa"))
|
|
# learn(): a placeholder until its machine reports it.
|
|
ph = st.learn("other-form_aaaaaa", public_url="https://ask-form.xyz/f/other-form_aaaaaa?token=b")
|
|
self.assertTrue(ph["placeholder"] and ph["status"] == "pending")
|
|
rec, new, _ = st.upsert("mac-1", _form("other-form_aaaaaa"))
|
|
self.assertTrue(new) # first machine report
|
|
self.assertNotIn("placeholder", rec)
|
|
self.assertEqual(rec["publicUrl"], "https://ask-form.xyz/f/other-form_aaaaaa?token=b")
|
|
_, new, _ = st.upsert("mac-1", _form("other-form_aaaaaa"))
|
|
self.assertFalse(new)
|
|
self.assertIsNone(st.learn("not an id", url="x"))
|
|
self.assertEqual([r["id"] for r in st.list(status="pending")], ["other-form_aaaaaa"])
|
|
self.assertEqual(st.pending_machines(), {"mac-1"})
|
|
# Survives a reload.
|
|
again = AskFormStore(str(TMP / "store-test.json"))
|
|
self.assertEqual(again.get(FID)["answers"], {"stack": "vite"})
|
|
with self.assertRaises(ValueError):
|
|
st.upsert("lab", {"id": "bad id"})
|
|
|
|
def test_declined_keeps_the_reason(self):
|
|
st = AskFormStore(str(TMP / "store-decline.json"))
|
|
st.upsert("lab", _form())
|
|
files = [{"name": "why.png", "size": 1200, "path": "/x/why.png"}]
|
|
rec, _, changed = st.upsert("lab", _form(status="declined", reason="Not mine", reasonFiles=files))
|
|
self.assertTrue(changed)
|
|
self.assertEqual((rec["reason"], rec["reasonFiles"]), ("Not mine", files))
|
|
|
|
|
|
class TestMirror(unittest.TestCase):
|
|
def setUp(self):
|
|
_reset()
|
|
|
|
def test_sync_pushes_new_and_publishes_changes(self):
|
|
FakeSidecar.forms = {FID: _form()}
|
|
new, events = [], []
|
|
m = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=new.append, publish=events.append)
|
|
self.assertEqual(m.sync(MACHINE), 1)
|
|
self.assertEqual([r["id"] for r in new], [FID])
|
|
self.assertEqual(events[-1]["type"], "askform")
|
|
# Nothing new the second time; a submit publishes.
|
|
m.sync(MACHINE)
|
|
self.assertEqual(len(new), 1)
|
|
FakeSidecar.forms[FID]["status"] = "submitted"
|
|
FakeSidecar.forms[FID]["answers"] = {"stack": "vite"}
|
|
n_before = len(events)
|
|
m.sync(MACHINE)
|
|
self.assertEqual(len(events), n_before + 1)
|
|
self.assertEqual(DEPS.askform_store.get(FID)["status"], "submitted")
|
|
|
|
def test_a_form_learned_from_a_transcript_first_still_pushes(self):
|
|
"""The thread's transcript scan can meet a form (learn → placeholder)
|
|
before the mirror's poll does: its push must still go out."""
|
|
DEPS.askform_store.learn(FID, public_url=f"https://ask-form.xyz/f/{FID}?token=t",
|
|
session=SID)
|
|
FakeSidecar.forms = {FID: _form()}
|
|
new = []
|
|
m = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=new.append, publish=lambda e: None)
|
|
m.sync(MACHINE)
|
|
self.assertEqual([r["id"] for r in new], [FID])
|
|
self.assertEqual(new[0]["publicUrl"], f"https://ask-form.xyz/f/{FID}?token=t")
|
|
m.sync(MACHINE)
|
|
self.assertEqual(len(new), 1)
|
|
|
|
def test_tick_cadence_and_missing_machine(self):
|
|
FakeSidecar.forms = {FID: _form()}
|
|
m = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=lambda r: None, publish=lambda e: None,
|
|
fast=5, slow=60, missing=300)
|
|
self.assertLessEqual(m.tick(), 5) # a pending form: fast
|
|
FakeSidecar.forms = {}
|
|
DEPS.askform_store._forms = {}
|
|
m.poke("mac-1")
|
|
self.assertGreater(m.tick(), 5) # idle: slow
|
|
down = {**MACHINE, "id": "mac-2", "url": "http://127.0.0.1:1"}
|
|
m2 = AskFormMirror(DEPS.askform_store, machines=lambda: [down],
|
|
on_new=lambda r: None, publish=lambda e: None, missing=300)
|
|
self.assertEqual(m2.tick(), 60) # unreachable: slow retry, no raise
|
|
self.assertNotIn("mac-2", m2._missing)
|
|
|
|
|
|
def test_past_the_cap_a_sync_does_not_churn(self):
|
|
"""2026-11-27: past _MAX forms in all, every sync re-added the oldest
|
|
closed forms (new + changed), the GC dropped others, and each read
|
|
published dozens of SSE events. A dropped form must stay dropped."""
|
|
import askform.store as store_mod
|
|
old_max = store_mod._MAX
|
|
store_mod._MAX = 3
|
|
try:
|
|
FakeSidecar.forms = {
|
|
f"old-form-{i}_aaaaa{i}": _form(f"old-form-{i}_aaaaa{i}", "submitted",
|
|
createdAt=_iso(3600 * (10 - i)))
|
|
for i in range(5)}
|
|
events = []
|
|
m = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=lambda r: None, publish=events.append)
|
|
m.sync(MACHINE)
|
|
self.assertEqual(len(DEPS.askform_store._forms), 3)
|
|
first = len(events)
|
|
for _ in range(3):
|
|
m.sync(MACHINE)
|
|
self.assertEqual(len(events), first) # no churn, no SSE
|
|
self.assertEqual(len(DEPS.askform_store._forms), 3)
|
|
finally:
|
|
store_mod._MAX = old_max
|
|
|
|
def test_long_closed_forms_are_left_out_pending_ones_kept(self):
|
|
stale, live = "stale-form_bbbbb1", "stale-but-open_bbbbb2"
|
|
FakeSidecar.forms = {
|
|
stale: _form(stale, "submitted", createdAt=_iso(40 * 86400),
|
|
closedAt=_iso(40 * 86400)),
|
|
live: _form(live, "pending", createdAt=_iso(40 * 86400)),
|
|
}
|
|
events = []
|
|
m = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=lambda r: None, publish=events.append)
|
|
m.sync(MACHINE)
|
|
self.assertIsNone(DEPS.askform_store.get(stale))
|
|
self.assertIsNotNone(DEPS.askform_store.get(live))
|
|
|
|
|
|
class TestEmbed(unittest.TestCase):
|
|
HUBS = ["https://ai-agent.lab.gabvdl.xyz", "https://claude.lab.gabvdl.xyz"]
|
|
|
|
def setUp(self):
|
|
_reset()
|
|
|
|
def test_check_embed_asks_once_then_reads(self):
|
|
m = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=lambda r: None, publish=lambda e: None,
|
|
origins=lambda: self.HUBS, embed_every=600)
|
|
self.assertEqual(m.embed_origins("mac-1"), [])
|
|
self.assertEqual(m.check_embed(MACHINE), 10.0) # wired: look again soon
|
|
self.assertIn(("POST", "/ask-form/embed"), FakeSidecar.calls)
|
|
self.assertEqual(m.check_embed(MACHINE), 600) # now it lists the hub
|
|
self.assertEqual(m.embed_origins("mac-1"), self.HUBS)
|
|
self.assertEqual([c for c in FakeSidecar.calls if c[1] == "/ask-form/embed"],
|
|
[("POST", "/ask-form/embed")])
|
|
# tick() checks a machine once per embed_every, after its forms.
|
|
FakeSidecar.calls = []
|
|
m.tick()
|
|
m.poke("mac-1")
|
|
m.tick()
|
|
self.assertEqual(sum(1 for c in FakeSidecar.calls if c[1] == "/ask-form/health"), 1)
|
|
|
|
def test_hub_origins(self):
|
|
self.assertIn("https://ai-agent.lab.gabvdl.xyz", service.hub_origins())
|
|
|
|
def test_push_opens_the_app_when_the_machine_lets_it_frame(self):
|
|
proj = TMP / "t" / "-home-x-proj"
|
|
proj.mkdir(parents=True, exist_ok=True)
|
|
(proj / f"{SID}.jsonl").write_text(json.dumps({"type": "user", "sessionId": SID}) + "\n")
|
|
link = f"https://ask-form.xyz/f/{FID}?token=a"
|
|
DEPS.askform_mirror = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=lambda r: None, publish=lambda e: None)
|
|
DEPS.askform_store.upsert("mac-1", _form(publicUrl=link))
|
|
conv = service._conversation_url(DEPS, SID)
|
|
self.assertIn("/conversation/", conv)
|
|
pushes = []
|
|
orig = service._create_notify
|
|
service._create_notify = lambda deps, note: pushes.append(note)
|
|
try:
|
|
# Not framed by the app (an older ask-form): the form's own page.
|
|
service.push_new(DEPS, DEPS.askform_store.get(FID))
|
|
DEPS.askform_store._forms[FID]["pushed"] = False
|
|
DEPS.askform_mirror.embed["mac-1"] = list(self.HUBS)
|
|
service.push_new(DEPS, DEPS.askform_store.get(FID))
|
|
finally:
|
|
service._create_notify = orig
|
|
self.assertEqual(pushes[0]["url"], link)
|
|
self.assertEqual(pushes[1]["url"], f"{conv}?form={FID}")
|
|
rec = service.public(DEPS, OWNER, [DEPS.askform_store.get(FID)])[0]
|
|
self.assertEqual(rec["embedOrigins"], self.HUBS)
|
|
|
|
|
|
class TestServiceAndRoutes(unittest.TestCase):
|
|
def setUp(self):
|
|
_reset()
|
|
self._machines = service.machines
|
|
service.machines = lambda deps: [MACHINE]
|
|
DEPS.askform_mirror = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=lambda r: None, publish=lambda e: None)
|
|
self.c = TestClient(main.app, headers=OWNER_H)
|
|
|
|
def tearDown(self):
|
|
service.machines = self._machines
|
|
|
|
def _pushes(self):
|
|
return [e for e in DEPS.notify_store.log(500) if e.get("title", "").startswith("📋")]
|
|
|
|
def test_events_webhook_pushes_once_with_the_public_link(self):
|
|
ev = {"event": "created", "form": _form(url="http://127.0.0.1:7462/f/%s?token=a" % FID,
|
|
publicUrl="https://ask-form.xyz/f/%s?token=a" % FID,
|
|
description="Two choices before I scaffold.")}
|
|
r = self.c.post("/api/ask-form/events", json=ev)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["machine"], "lab")
|
|
pushes = self._pushes()
|
|
self.assertEqual(len(pushes), 1)
|
|
self.assertEqual(pushes[0]["url"], "https://ask-form.xyz/f/%s?token=a" % FID)
|
|
self.assertEqual(pushes[0]["body"], "Two choices before I scaffold.")
|
|
self.assertEqual(pushes[0]["sessionId"], SID)
|
|
# The same event again (a lost ack, a mirror pass): no second push.
|
|
self.c.post("/api/ask-form/events", json=ev)
|
|
self.c.post("/api/ask-form/events", json={"event": "submitted",
|
|
"form": _form(status="submitted", answers={"stack": "vite"})})
|
|
self.assertEqual(len(self._pushes()), 1)
|
|
self.assertEqual(DEPS.askform_store.get(FID)["status"], "submitted")
|
|
self.assertEqual(self.c.post("/api/ask-form/events",
|
|
json={"event": "nope", "form": _form()}).status_code, 400)
|
|
self.assertEqual(self.c.post("/api/ask-form/events",
|
|
json={"event": "created", "form": {"id": "bad id"}}).status_code, 400)
|
|
|
|
def test_old_forms_are_mirrored_not_pushed(self):
|
|
FakeSidecar.forms = {FID: _form(createdAt=_iso(3600))}
|
|
DEPS.askform_mirror.sync(MACHINE)
|
|
service.push_new(DEPS, DEPS.askform_store.get(FID))
|
|
self.assertEqual(self._pushes(), [])
|
|
self.assertEqual(self.c.get("/api/ask-form/forms").json()["count"], 1)
|
|
|
|
def test_list_get_with_fields_and_revoke(self):
|
|
FakeSidecar.forms = {FID: _form()}
|
|
DEPS.askform_mirror.sync(MACHINE)
|
|
lst = self.c.get("/api/ask-form/forms?status=pending").json()
|
|
self.assertEqual(lst["count"], 1)
|
|
self.assertNotIn("fields", lst["forms"][0])
|
|
self.assertTrue(lst["forms"][0]["forYou"])
|
|
one = self.c.get(f"/api/ask-form/forms/{FID}").json()
|
|
self.assertEqual(one["fields"][0]["key"], "stack")
|
|
self.assertEqual(one["fieldCount"], 1)
|
|
self.assertIn(("GET", f"/ask-form/forms/{FID}?fields=1"), FakeSidecar.calls)
|
|
# Cached: a second get doesn't go back to the machine.
|
|
n = len(FakeSidecar.calls)
|
|
self.c.get(f"/api/ask-form/forms/{FID}")
|
|
self.assertEqual(len(FakeSidecar.calls), n)
|
|
r = self.c.post(f"/api/ask-form/forms/{FID}/revoke")
|
|
self.assertEqual(r.json()["status"], "revoked")
|
|
self.assertIn(("POST", f"/ask-form/forms/{FID}/revoke"), FakeSidecar.calls)
|
|
self.assertEqual(self.c.get("/api/ask-form/forms/unknown_aaaaaa").status_code, 404)
|
|
self.assertEqual(self.c.get("/api/ask-form/forms/bad").status_code, 404) # never a hint
|
|
|
|
def test_recheck_reads_the_machine_now_and_clears_the_push_once(self):
|
|
from users import deliver
|
|
cleared, real_clear = [], deliver.clear
|
|
deliver.clear = lambda deps, sid, tag, kind="ask", **kw: cleared.append((sid, tag, kind))
|
|
events, real_publish = [], DEPS.hub.publish
|
|
DEPS.hub.publish = events.append
|
|
try:
|
|
FakeSidecar.forms = {FID: _form()}
|
|
DEPS.askform_mirror.sync(MACHINE)
|
|
self.c.get(f"/api/ask-form/forms/{FID}") # the spec, cached
|
|
# Answered on its page; no webhook has come yet.
|
|
FakeSidecar.forms[FID] = _form(status="submitted", answers={"stack": "vite"},
|
|
closedAt=_iso())
|
|
r = self.c.post(f"/api/ask-form/forms/{FID}/recheck")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()
|
|
self.assertEqual((body["status"], body["answers"]), ("submitted", {"stack": "vite"}))
|
|
self.assertEqual(body["fields"][0]["key"], "stack") # the recap can label them
|
|
self.assertIn(("GET", f"/ask-form/forms/{FID}"), FakeSidecar.calls)
|
|
self.assertEqual(cleared, [(SID, FID, "form")])
|
|
self.assertEqual([e["status"] for e in events if e.get("type") == "askform"], ["submitted"])
|
|
# The webhook arriving afterwards, or another recheck: nothing new.
|
|
self.c.post("/api/ask-form/events", json={"event": "submitted", "form": FakeSidecar.forms[FID]})
|
|
self.c.post(f"/api/ask-form/forms/{FID}/recheck")
|
|
self.assertEqual(len(cleared), 1)
|
|
self.assertEqual(self.c.post("/api/ask-form/forms/unknown_aaaaaa/recheck").status_code, 404)
|
|
finally:
|
|
deliver.clear = real_clear
|
|
DEPS.hub.publish = real_publish
|
|
|
|
def test_guest_sees_only_their_conversations(self):
|
|
gsid = "22222222-2222-4333-8444-555555555555" # its own session: the meta sticks
|
|
gfid = "guest-form_aaaaaa"
|
|
DEPS.askform_store.upsert("lab", _form(gfid, meta={"session": gsid}))
|
|
guest = guest_from_record({"id": "dom", "name": "Dom"})
|
|
with self.assertRaises(HTTPException) as cm:
|
|
service.visible(DEPS, guest, DEPS.askform_store.get(gfid))
|
|
self.assertEqual(cm.exception.status_code, 404)
|
|
self.assertEqual(service.visible(DEPS, OWNER, DEPS.askform_store.get(gfid))["id"], gfid)
|
|
DEPS.meta_store.update(gsid, {"owner": "dom"})
|
|
self.assertEqual(service.visible(DEPS, guest, DEPS.askform_store.get(gfid))["id"], gfid)
|
|
# …and the list route filters the same way (the owner still sees it).
|
|
self.assertEqual(self.c.get("/api/ask-form/forms").json()["count"], 1)
|
|
|
|
def test_outbox_item_from_a_worker(self):
|
|
res = service.ingest_outbox(DEPS, {"id": "afe_0123456789ab", "worker": "mac-1",
|
|
"event": "created", "form": _form(publicUrl=f"https://ask-form.xyz/f/{FID}?token=q")})
|
|
self.assertEqual(res, {"id": "afe_0123456789ab", "ok": True, "form": FID})
|
|
self.assertEqual(DEPS.askform_store.get(FID)["machine"], "mac-1")
|
|
self.assertEqual(len(self._pushes()), 1)
|
|
with self.assertRaises(HTTPException):
|
|
service.ingest_outbox(DEPS, {"id": "afe_0123456789ab", "event": "created"})
|
|
|
|
|
|
class TestSubagentScan(unittest.TestCase):
|
|
def test_links_and_ids(self):
|
|
p = TMP / "agent-askform.jsonl"
|
|
p.write_text('{"c":"{\\"id\\":\\"review-options_ab12cd\\",\\"url\\":\\"http://127.0.0.1:7462/f/review-options_ab12cd?token=tok-1_A\\",'
|
|
'\\"publicUrl\\":\\"https://ask-form.xyz/f/review-options_ab12cd?token=tok-1_A\\"}"}\n')
|
|
ids, links = tree._subagent_forms(p)
|
|
self.assertEqual(ids, ["review-options_ab12cd"])
|
|
self.assertEqual(links["review-options_ab12cd"],
|
|
{"url": "http://127.0.0.1:7462/f/review-options_ab12cd?token=tok-1_A",
|
|
"publicUrl": "https://ask-form.xyz/f/review-options_ab12cd?token=tok-1_A"})
|
|
self.assertEqual(tree._subagent_form_ids(p), ids)
|
|
|
|
def test_parent_page_learns_the_subagents_links(self):
|
|
# The parent's detail page runs _attach_subagents over its children:
|
|
# it must not raise and must file the link under the thread's session.
|
|
fid = "child-form_zz99yy"
|
|
root = TMP / "t" / "proj" / f"{SID}.jsonl"
|
|
sub = root.with_suffix("") / "subagents"
|
|
sub.mkdir(parents=True, exist_ok=True)
|
|
root.write_text("")
|
|
(sub / "agent-a1.meta.json").write_text(json.dumps({"agentType": "clarifier", "toolUseId": "tu1"}))
|
|
(sub / "agent-a1.jsonl").write_text(
|
|
f'{{"c":"{{\\"url\\":\\"http://127.0.0.1:7462/f/{fid}?token=t0k\\"}}"}}\n')
|
|
data = tree._attach_subagents(DEPS, root, {"sessionId": SID, "thread": []})
|
|
self.assertEqual(data["subagents"][0]["forms"], [fid])
|
|
rec = DEPS.askform_store.get(fid)
|
|
self.assertEqual(rec["sessionId"], SID)
|
|
self.assertEqual(rec["url"], f"http://127.0.0.1:7462/f/{fid}?token=t0k")
|
|
|
|
def test_nested_forms_roll_up_with_their_time(self):
|
|
# root → a worker agent → its clarifier: the root's Agent card carries
|
|
# the grandchild's form, stamped with the line it opened on and by whom.
|
|
sid = "22222222-2222-4333-8444-555555555555"
|
|
root = TMP / "t" / "proj" / f"{sid}.jsonl"
|
|
sub = root.with_suffix("") / "subagents"
|
|
sub.mkdir(parents=True, exist_ok=True)
|
|
root.write_text("")
|
|
(sub / "agent-b1.meta.json").write_text(json.dumps(
|
|
{"agentType": "general-purpose", "toolUseId": "tuB"}))
|
|
(sub / "agent-b1.jsonl").write_text(
|
|
'{"timestamp":"2026-10-31T10:00:00.000Z","c":"{\\"publicUrl\\":\\"https://ask-form.xyz/f/outer-form_bb11cc?token=p\\"}"}\n')
|
|
(sub / "agent-b2.meta.json").write_text(json.dumps(
|
|
{"agentType": "clarifier", "toolUseId": "tuC", "parentAgentId": "b1", "spawnDepth": 2}))
|
|
(sub / "agent-b2.jsonl").write_text(
|
|
'{"type":"assistant","timestamp":"2026-10-31T09:00:00.000Z"}\n'
|
|
'{"c":"{\\"publicUrl\\":\\"https://ask-form.xyz/f/deep-form_cc11dd?token=q\\"}",'
|
|
'"timestamp":"2026-10-31T09:30:00.000Z"}\n')
|
|
data = tree._attach_subagents(DEPS, root, {"sessionId": sid, "thread": []})
|
|
card = data["subagents"][0]
|
|
self.assertEqual(card["forms"], ["deep-form_cc11dd", "outer-form_bb11cc"])
|
|
self.assertEqual(card["formRefs"][0]["at"], "2026-10-31T09:30:00.000Z")
|
|
self.assertEqual(card["formRefs"][0]["agentType"], "clarifier")
|
|
self.assertEqual(card["formRefs"][0]["agentId"], tree._conv_id(str(sub / "agent-b2.jsonl")))
|
|
self.assertEqual(card["formRefs"][1]["agentType"], "general-purpose")
|
|
self.assertEqual(DEPS.askform_store.get("deep-form_cc11dd")["sessionId"], sid)
|
|
# The worker agent's own page: its clarifier card carries the form too.
|
|
mid = tree._attach_subagents(DEPS, sub / "agent-b1.jsonl", {"sessionId": sid, "thread": []})
|
|
self.assertEqual(mid["subagents"][0]["forms"], ["deep-form_cc11dd"])
|
|
|
|
|
|
class TestRecoverLinks(unittest.TestCase):
|
|
"""A machine whose serve never posts to the hub (a guest's own computer)
|
|
is mirrored with no link; the conversation's own transcript has it."""
|
|
|
|
def setUp(self):
|
|
_reset()
|
|
links._index = None
|
|
self.sid = "33333333-2222-4333-8444-555555555555"
|
|
self.fid = "jeton-npm_iddwwi"
|
|
self.root = TMP / "t" / "proj-links" / f"{self.sid}.jsonl"
|
|
self.root.parent.mkdir(parents=True, exist_ok=True)
|
|
self.link = f"https://ask-form.xyz/f/{self.fid}?token=mVIL1Mx6hjarar246"
|
|
# The mirror holds the form, link-less (a poll through the sidecar).
|
|
DEPS.askform_store.upsert("g1", _form(self.fid, meta={"session": self.sid}))
|
|
self.pub = []
|
|
self._orig = DEPS.hub.publish
|
|
DEPS.hub.publish = self.pub.append
|
|
|
|
def tearDown(self):
|
|
DEPS.hub.publish = self._orig
|
|
|
|
def _summarise(self):
|
|
DEPS.store.upsert_transcript(str(self.root), 1.0, 1, {}, {"sessionId": self.sid, "messages": 1})
|
|
|
|
def test_main_thread_transcript_gives_the_link(self):
|
|
# The agent kept the link out of the create call's output and showed
|
|
# it later, in its own words (the guest's pet-pet conversation).
|
|
self.root.write_text(
|
|
'{"c":"ok pending, url host ask-form.xyz"}\n'
|
|
f'{{"type":"assistant","c":"Voici le formulaire : {self.link}\\n"}}\n')
|
|
self._summarise()
|
|
self.assertEqual(links.recover(DEPS), 1)
|
|
rec = DEPS.askform_store.get(self.fid)
|
|
self.assertEqual(rec["publicUrl"], self.link)
|
|
self.assertEqual(service.link_of(rec), self.link)
|
|
self.assertEqual([e["type"] for e in self.pub], ["askform"])
|
|
# Nothing left to recover: the next pass is a no-op.
|
|
self.assertEqual(links.recover(DEPS), 0)
|
|
|
|
def test_the_mirror_runs_it_after_a_read(self):
|
|
self.root.write_text(f'{{"c":"{self.link}"}}\n')
|
|
self._summarise()
|
|
FakeSidecar.forms = {self.fid: _form(self.fid, meta={"session": self.sid})}
|
|
m = AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=lambda r: None, publish=lambda e: None,
|
|
recover=lambda: links.recover(DEPS))
|
|
m.tick()
|
|
self.assertEqual(DEPS.askform_store.get(self.fid)["publicUrl"], self.link)
|
|
|
|
def test_a_link_for_another_conversations_form_is_ignored(self):
|
|
other = "44444444-2222-4333-8444-555555555555"
|
|
DEPS.askform_store.upsert("g1", _form("other-form_zz99yy", meta={"session": other}))
|
|
self.root.write_text('{"c":"https://evil.example/f/other-form_zz99yy?token=x"}\n')
|
|
self._summarise()
|
|
self.assertEqual(links.recover(DEPS), 0)
|
|
self.assertEqual(service.link_of(DEPS.askform_store.get("other-form_zz99yy")), "")
|
|
|
|
def test_an_existing_link_is_never_replaced(self):
|
|
DEPS.askform_store.upsert("g1", _form(self.fid, meta={"session": self.sid},
|
|
publicUrl=f"https://ask-form.xyz/f/{self.fid}?token=webhook"))
|
|
self.root.write_text(f'{{"c":"{self.link}"}}\n')
|
|
self._summarise()
|
|
self.assertEqual(links.recover(DEPS), 0)
|
|
self.assertEqual(DEPS.askform_store.get(self.fid)["publicUrl"],
|
|
f"https://ask-form.xyz/f/{self.fid}?token=webhook")
|
|
|
|
def test_a_subagents_transcript_counts_too(self):
|
|
sub = self.root.with_suffix("") / "subagents"
|
|
sub.mkdir(parents=True, exist_ok=True)
|
|
self.root.write_text("")
|
|
agent = sub / "agent-a1.jsonl"
|
|
agent.write_text(f'{{"c":"{self.link}"}}\n')
|
|
DEPS.store.upsert_transcript(str(agent), 1.0, 1, {}, {"sessionId": self.sid, "messages": 1, "isSidechain": True})
|
|
self.assertEqual(links.recover(DEPS), 1)
|
|
|
|
|
|
class TestHostileMachine(unittest.TestCase):
|
|
"""docs/security.md 2026-11-15 (A2, A8): a guest's own computer answers the
|
|
poll with whatever it likes, and a transcript holds whatever the agent
|
|
read. Neither may hand the app a link that isn't a form's page, take over
|
|
another machine's form, or move one into another conversation."""
|
|
GUEST_W = {"id": "g-akira", "owner": "akira", "name": "Framework"}
|
|
GSID = "55555555-2222-4333-8444-555555555555" # runs on the guest's computer
|
|
OSID = "66666666-2222-4333-8444-555555555555" # the owner's, on the lab
|
|
|
|
def setUp(self):
|
|
_reset()
|
|
DEPS.meta_store.update(self.GSID, {"worker": "g-akira", "owner": "akira"})
|
|
DEPS.meta_store.update(self.OSID, {"title": "owner's"})
|
|
from workers import guests
|
|
self.machine = {**MACHINE, "id": "g-akira", "label": "worker Framework",
|
|
"vet": lambda form: guests.session_belongs(
|
|
DEPS, self.GUEST_W, service._form_session(form))}
|
|
self.new = []
|
|
self.m = AskFormMirror(DEPS.askform_store, machines=lambda: [self.machine],
|
|
on_new=self.new.append, publish=lambda e: None,
|
|
origins=lambda: ["https://ai-agent.lab.gabvdl.xyz"])
|
|
|
|
def test_clean_link(self):
|
|
from askform.store import clean_link
|
|
ok = f"https://ask-form.xyz/f/{FID}?token=t0k"
|
|
self.assertEqual(clean_link(ok, FID), ok)
|
|
self.assertEqual(clean_link(f"http://127.0.0.1:7462/f/{FID}?token=t", FID),
|
|
f"http://127.0.0.1:7462/f/{FID}?token=t")
|
|
for bad in ("javascript:fetch('/api/spawn')", "JaVaScRiPt:alert(1)//f/" + FID,
|
|
f"data:text/html,<script>1</script>/f/{FID}",
|
|
f"http://evil.example/f/{FID}?token=t", # plain http off loopback
|
|
f"https://user:pw@ask-form.xyz/f/{FID}", # credentials
|
|
f"https://evil.example\\@ask-form.xyz/f/{FID}", # the browser's host differs
|
|
f"https://ask-form.xyz/f/{FID} onload=x", f"//ask-form.xyz/f/{FID}",
|
|
f"/f/{FID}", "https://ask-form.xyz/f/another-form_aaaaaa?token=t",
|
|
"", None, 7, "https://ask-form.xyz/f/" + FID + "?" + "a" * 3000):
|
|
self.assertIsNone(clean_link(bad, FID), bad)
|
|
|
|
def test_a_machines_script_link_is_dropped(self):
|
|
FakeSidecar.forms = {FID: _form(url="javascript:fetch('/api/spawn')",
|
|
publicUrl="javascript:alert(1)")}
|
|
AskFormMirror(DEPS.askform_store, machines=lambda: [MACHINE],
|
|
on_new=lambda r: None, publish=lambda e: None).sync(MACHINE)
|
|
rec = DEPS.askform_store.get(FID)
|
|
self.assertEqual(service.link_of(rec), "")
|
|
self.assertNotIn("url", rec)
|
|
|
|
def test_a_guest_computer_reports_only_its_own_sessions(self):
|
|
mine = _form("mine_aaaaaa", meta={"session": self.GSID},
|
|
publicUrl="https://ask-form.xyz/f/mine_aaaaaa?token=t")
|
|
FakeSidecar.forms = {
|
|
"mine_aaaaaa": mine,
|
|
"owners_aaaaaa": _form("owners_aaaaaa", meta={"session": self.OSID}),
|
|
"nobody_aaaaaa": {**_form("nobody_aaaaaa"), "meta": {}},
|
|
"unknown_aaaaaa": _form("unknown_aaaaaa", meta={"session": SID})}
|
|
self.assertEqual(self.m.sync(self.machine), 1)
|
|
self.assertEqual([r["id"] for r in DEPS.askform_store.list()], ["mine_aaaaaa"])
|
|
self.assertEqual([r["id"] for r in self.new], ["mine_aaaaaa"])
|
|
|
|
def test_a_guest_computer_cannot_take_over_a_form(self):
|
|
real = f"https://ask-form.xyz/f/{FID}?token=real"
|
|
DEPS.askform_store.upsert("lab", _form(meta={"session": self.OSID}, publicUrl=real))
|
|
# …re-reported as its own, in its own session, with its own link.
|
|
FakeSidecar.forms = {FID: _form(meta={"session": self.GSID}, title="Pwned",
|
|
publicUrl=f"https://evil.example/f/{FID}?token=x")}
|
|
self.assertEqual(self.m.sync(self.machine), 0)
|
|
rec = DEPS.askform_store.get(FID)
|
|
self.assertEqual((rec["machine"], rec["sessionId"], rec["publicUrl"], rec["title"]),
|
|
("lab", self.OSID, real, "Project setup"))
|
|
# Its own form's link, once known, is never swapped either.
|
|
mine = "https://ask-form.xyz/f/mine_aaaaaa?token=t"
|
|
FakeSidecar.forms = {"mine_aaaaaa": _form("mine_aaaaaa", meta={"session": self.GSID},
|
|
publicUrl=mine)}
|
|
self.m.sync(self.machine)
|
|
FakeSidecar.forms["mine_aaaaaa"]["publicUrl"] = "https://evil.example/f/mine_aaaaaa?token=x"
|
|
self.m.sync(self.machine)
|
|
self.assertEqual(DEPS.askform_store.get("mine_aaaaaa")["publicUrl"], mine)
|
|
# A placeholder from the owner's transcript is not its to claim.
|
|
DEPS.askform_store.learn("ph_aaaaaa", session=self.OSID,
|
|
public_url="https://ask-form.xyz/f/ph_aaaaaa?token=t")
|
|
with self.assertRaises(ValueError):
|
|
DEPS.askform_store.upsert("g-akira", _form("ph_aaaaaa", meta={"session": self.GSID}),
|
|
trusted=False)
|
|
# The owner's machines still may (a re-paired worker reports its old forms).
|
|
rec, _, _ = DEPS.askform_store.upsert("mac-1", _form(meta={"session": self.OSID}))
|
|
self.assertEqual(rec["machine"], "mac-1")
|
|
|
|
def test_a_guest_computers_outbox_event_cannot_take_over_either(self):
|
|
DEPS.askform_store.upsert("lab", _form(meta={"session": self.OSID}))
|
|
orig = DEPS.worker_store.get
|
|
DEPS.worker_store.get = lambda wid: self.GUEST_W if wid == "g-akira" else orig(wid)
|
|
try:
|
|
with self.assertRaises(HTTPException) as cm:
|
|
service.ingest_outbox(DEPS, {"id": "afe_0123456789ab", "worker": "g-akira",
|
|
"event": "created",
|
|
"form": _form(meta={"session": self.GSID})})
|
|
finally:
|
|
DEPS.worker_store.get = orig
|
|
self.assertEqual(cm.exception.status_code, 400)
|
|
self.assertEqual(DEPS.askform_store.get(FID)["machine"], "lab")
|
|
|
|
def test_a_guest_computer_says_nothing_about_framing(self):
|
|
FakeSidecar.health = {"installed": True, "ok": True,
|
|
"embedOrigins": ["https://ai-agent.lab.gabvdl.xyz"]}
|
|
self.assertEqual(self.m.check_embed(self.machine), self.m.embed_every)
|
|
self.assertEqual(self.m.embed_origins("g-akira"), [])
|
|
self.assertEqual(FakeSidecar.calls, []) # not even asked
|
|
|
|
def test_refresh_and_revoke_replies_are_vetted_too(self):
|
|
FakeSidecar.forms = {"mine_aaaaaa": _form("mine_aaaaaa", meta={"session": self.GSID})}
|
|
self.m.sync(self.machine)
|
|
FakeSidecar.forms["mine_aaaaaa"]["meta"] = {"session": self.OSID} # moves on a re-read
|
|
machines, service.machines = service.machines, lambda deps: [self.machine]
|
|
DEPS.askform_mirror = self.m
|
|
try:
|
|
with self.assertRaises(HTTPException) as cm:
|
|
service.refresh(DEPS, "mine_aaaaaa", fields=True)
|
|
finally:
|
|
service.machines = machines
|
|
self.assertEqual(cm.exception.status_code, 502)
|
|
self.assertEqual(DEPS.askform_store.get("mine_aaaaaa")["sessionId"], self.GSID)
|
|
|
|
def test_machines_marks_a_guests_computer(self):
|
|
orig_list, orig_online = DEPS.worker_store.list, DEPS.worker_store.online
|
|
DEPS.worker_store.list = lambda: [
|
|
{**self.GUEST_W, "url": "http://x", "token": "t"},
|
|
{"id": "mac-1", "url": "http://y", "token": "t", "name": "Mac"}]
|
|
DEPS.worker_store.online = lambda wid: True
|
|
try:
|
|
ms = {m["id"]: m for m in service.machines(DEPS)}
|
|
finally:
|
|
DEPS.worker_store.list, DEPS.worker_store.online = orig_list, orig_online
|
|
self.assertNotIn("vet", ms["mac-1"])
|
|
self.assertTrue(ms["g-akira"]["vet"](_form(meta={"session": self.GSID})))
|
|
self.assertFalse(ms["g-akira"]["vet"](_form(meta={"session": self.OSID})))
|
|
self.assertFalse(ms["g-akira"]["vet"]({"id": FID}))
|
|
|
|
|
|
class TestLearnOnlyFillsIn(unittest.TestCase):
|
|
"""A transcript also holds what the agent read (a page, a mail): `learn`
|
|
never replaces a link nor moves a form (A8)."""
|
|
OTHER = "77777777-2222-4333-8444-555555555555"
|
|
|
|
def setUp(self):
|
|
_reset()
|
|
self.real = f"https://ask-form.xyz/f/{FID}?token=real"
|
|
DEPS.askform_store.upsert("lab", _form(publicUrl=self.real))
|
|
|
|
def test_a_known_link_and_session_stay(self):
|
|
DEPS.askform_store.learn(FID, public_url=f"https://evil.example/f/{FID}?token=x",
|
|
url=f"https://evil.example/f/{FID}?token=x", session=self.OTHER)
|
|
rec = DEPS.askform_store.get(FID)
|
|
self.assertEqual((rec["publicUrl"], rec["sessionId"]), (self.real, SID))
|
|
self.assertNotIn("url", rec) # another conversation's transcript fills nothing
|
|
|
|
def test_its_own_conversation_fills_what_is_missing(self):
|
|
local = f"http://127.0.0.1:7462/f/{FID}?token=real"
|
|
DEPS.askform_store.learn(FID, url=local, public_url=f"https://evil.example/f/{FID}?token=x",
|
|
session=SID)
|
|
rec = DEPS.askform_store.get(FID)
|
|
self.assertEqual((rec["url"], rec["publicUrl"]), (local, self.real))
|
|
|
|
def test_a_transcript_link_must_be_on_a_known_relay(self):
|
|
# Link-less form, and its own conversation prints a look-alike page.
|
|
DEPS.askform_store.upsert("lab", _form("bare_aaaaaa"))
|
|
DEPS.askform_store.learn("bare_aaaaaa", session=SID,
|
|
public_url="https://ask-form.xyz.evil.example/f/bare_aaaaaa?token=x")
|
|
self.assertIsNone(DEPS.askform_store.adopt_link(
|
|
"bare_aaaaaa", session=SID, public_url="https://evil.example/f/bare_aaaaaa?token=x"))
|
|
self.assertEqual(service.link_of(DEPS.askform_store.get("bare_aaaaaa")), "")
|
|
good = "https://ask-form.xyz/f/bare_aaaaaa?token=x"
|
|
self.assertEqual(DEPS.askform_store.adopt_link("bare_aaaaaa", session=SID,
|
|
public_url=good)["publicUrl"], good)
|
|
|
|
def test_no_placeholder_for_a_link_that_is_no_form_page(self):
|
|
self.assertIsNone(DEPS.askform_store.learn(
|
|
"ghost_aaaaaa", public_url="http://evil.example/f/ghost_aaaaaa?token=x", session=SID))
|
|
self.assertIsNone(DEPS.askform_store.get("ghost_aaaaaa"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|
|
|
|
|
|
class TestMetaStrings(unittest.TestCase):
|
|
"""ask-form keeps meta as map[string]string: a boolean in it is a 400."""
|
|
|
|
def test_values_become_strings_and_false_switches_drop(self):
|
|
self.assertEqual(service.meta_strings({
|
|
"ownerOnly": True, "noPush": False, "session": "s1", "n": 3,
|
|
"gone": None, "tags": ["a", "b"], "o": {"k": 1}}), {
|
|
"ownerOnly": "true", "session": "s1", "n": "3",
|
|
"tags": '["a","b"]', "o": '{"k":1}'})
|
|
self.assertEqual(service.meta_strings(None), {})
|
|
|
|
def test_switches_read_both_spellings(self):
|
|
for v, want in ((True, True), ("true", True), ("1", True), (False, False),
|
|
("false", False), ("", False), (None, False)):
|
|
self.assertEqual(service.is_owner_only({"meta": {"ownerOnly": v}}), want, v)
|