Files
ai-agent/backend/test_notif_state.py
gabrielvidalandClaude Opus 5.5 c9a3754875 feat(notifications): page the feed, load more while scrolling
GET /api/notifications pages by each conversation's newest push (before=
cursor, nextBefore, new=1 for what's still on New); the old call shapes
still work. Home: New is an infinite query — 20 stacks show, 20 more as the
end of the list nears the screen, then the next page; 'Loading more…' while
it fetches; what's shown is pinned by push time so a new push never pushes
the last stack out. The history page scrolls the same way.

The read ledger gains a time baseline: an id it never recorded and pushed
before it counts as dismissed, so older pages can't flood New with history
the old home never showed (live ledger: the old 60-conversation window's
edge, 2026-10-30T13:51Z — the 77 cards on New stay). /unread and the store's
stateOf use the same rule; guests get the equivalent guard locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 00:34:12 +01:00

275 lines
14 KiB
Python

"""The owner's per-notification state (notifications/read_ledger.py) and its
routes: ``GET/POST /api/notifications/state``, the one-time ``/migrate``, the
SSE ``notif-state`` event, the phone's ``/unread`` and the older ``/seen`` /
``/seed`` / ``/dismissed`` on top of it.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import json
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",
"WEBPUSH_PATH": TMP / "webpush.json",
"VAPID_KEY_PATH": TMP / "vapid.pem",
"PROJECTS_DIR": TMP / "projects",
"READONLY_API_KEY": "ro-key",
"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
from notifications import read_ledger # noqa: E402
from notifications.read_ledger import NotifReadStore # noqa: E402
from notifications.service import _create_notify # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
C = "-home-x/abc.jsonl"
def cid(at: str, i: int = 0) -> str:
return f"{C}#{at}#{i}"
class Ledger(unittest.TestCase):
def setUp(self):
self.path = pathlib.Path(tempfile.mkdtemp()) / "nr.json"
def store(self) -> NotifReadStore:
return NotifReadStore(str(self.path))
def test_states_only_move_forward(self):
s = self.store()
self.assertEqual(s.state_of("a"), "unread")
self.assertEqual(s.set_state(["a", "b"], "read", "tab-1"), ["a", "b"])
self.assertEqual(s.set_state(["a"], "dismissed", "tab-1"), ["a"])
# Dismissed stays dismissed; read again is nothing new.
self.assertEqual(s.set_state(["a", "b"], "read", "tab-2"), [])
self.assertEqual((s.state_of("a"), s.state_of("b")), ("dismissed", "read"))
with self.assertRaises(ValueError):
s.set_state(["a"], "unread")
# Persisted, with when and who.
again = self.store()
self.assertEqual(again.snapshot()["states"], {"a": "dismissed", "b": "read"})
raw = json.loads(self.path.read_text())
self.assertEqual(raw["version"], 2)
self.assertEqual(raw["states"]["a"]["by"], "tab-1")
self.assertIsInstance(raw["states"]["a"]["t"], int)
def test_seen_means_read_or_dismissed_for_the_phone(self):
s = self.store()
self.assertEqual(s.unread(["a", "b"]), ["a", "b"]) # not seeded yet
s.set_state(["a"], "read")
s.set_state(["b"], "dismissed")
self.assertTrue(s.is_seen("a") and s.is_seen("b"))
self.assertEqual(s.unread(["a", "b", "c"]), ["c"])
def test_a_v1_seen_list_loads_as_dismissed(self):
self.path.write_text(json.dumps({"seen": ["a", "b"], "seeded": True}))
s = self.store()
self.assertEqual(s.snapshot(), {"seeded": True, "migrated": False, "floor": None,
"baseline": None,
"states": {"a": "dismissed", "b": "dismissed"}})
def test_seed_is_once(self):
s = self.store()
s.seed(["a", "b"])
self.assertEqual(s.unread(["a", "b", "c"]), ["c"])
s.seed(["c"]) # a second client's first sync
self.assertEqual(s.unread(["a", "b", "c"]), ["c"])
def test_the_cap_drops_dismissed_first_and_keeps_them_dismissed(self):
old = read_ledger._MAX_SEEN
read_ledger._MAX_SEEN = 3
self.addCleanup(setattr, read_ledger, "_MAX_SEEN", old)
s = self.store()
# Older than these pushes (a first write would take "now" — see
# test_notif_paging.py for the baseline itself).
s.set_baseline("2026-01-01T00:00:00Z")
s.set_state([cid("2026-10-01T10:00:00Z")], "read")
s.set_state([cid("2026-10-02T10:00:00Z"), cid("2026-10-03T10:00:00Z")], "dismissed")
s.set_state([cid("2026-10-04T10:00:00Z")], "dismissed")
st = s.snapshot()
self.assertEqual(len(st["states"]), 3)
self.assertEqual(st["floor"], "2026-10-02T10:00:00Z")
self.assertIn(cid("2026-10-01T10:00:00Z"), st["states"]) # the read one stays
# The dropped one still reads dismissed; one before the floor that the
# ledger never had too (a log entry by its feed time); later ones unread.
self.assertEqual(s.state_of(cid("2026-10-02T10:00:00Z")), "dismissed")
self.assertEqual(s.unread(["log#x", "log#y"], {"log#x": "2026-09-30T00:00:00Z",
"log#y": "2026-10-05T00:00:00Z"}),
["log#y"])
def test_migrate_imports_the_client_lists_once(self):
self.path.write_text(json.dumps({"seen": ["r", "u", "d", "phone"], "seeded": True}))
s = self.store()
# Swiped through the live API after the deploy, before the import.
s.set_state(["live"], "dismissed", "tab-9")
self.assertTrue(s.migrate(read=["r"], unread=["u", "live", "new"],
dismissed=["d", "k"], by="tab-1"))
st = s.snapshot()
self.assertTrue(st["migrated"])
self.assertEqual(st["states"], {"r": "read", "d": "dismissed",
"phone": "dismissed", "live": "dismissed",
"k": "dismissed"})
# A second tab's import is a no-op.
self.assertFalse(s.migrate(read=[], unread=["r"], dismissed=[]))
self.assertEqual(s.state_of("r"), "read")
def test_migrate_with_nothing_seeds_from_the_feed(self):
s = self.store()
self.assertTrue(s.migrate([], [], [], baseline=lambda: ["a", "b"]))
self.assertEqual(s.unread(["a", "b", "c"]), ["c"])
# An already seeded ledger isn't re-seeded.
s2 = NotifReadStore(str(self.path.with_name("other.json")))
s2.seed(["a"])
s2.migrate([], [], [], baseline=lambda: ["a", "b"])
self.assertEqual(s2.unread(["a", "b"]), ["b"])
class Routes(unittest.TestCase):
def setUp(self):
for u in DEPS.users.all():
DEPS.users.delete(u["id"])
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
self.guest = TestClient(main.app, base_url="https://claude.example.test")
self.guest.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
self.owner = TestClient(main.app)
# A fresh ledger per test.
DEPS.notif_read_store = NotifReadStore(str(TMP / f"nr-{self._testMethodName}.json"))
self.events: list[dict] = []
orig = DEPS.hub.publish
DEPS.hub.publish = lambda ev: self.events.append(ev) or orig(ev)
self.addCleanup(setattr, DEPS.hub, "publish", orig)
import notifications.service as svc
self.phone: list[list[str]] = []
orig_clear = svc.clear_phone
svc.clear_phone = lambda deps, tags: self.phone.append(list(tags))
self.addCleanup(setattr, svc, "clear_phone", orig_clear)
def post(self, path, body, client=None):
r = (client or self.owner).post(path, json=body,
headers=OWNER_H if client is None else {})
self.assertEqual(r.status_code, 200, r.text)
return r.json()
def state(self, client=None):
r = (client or self.owner).get("/api/notifications/state",
headers=OWNER_H if client is None else {})
self.assertEqual(r.status_code, 200, r.text)
return r.json()
def test_state_round_trip_with_live_event(self):
n = _create_notify(DEPS, {"title": "x", "sessionId": ""})
nid = f"log#{n['id']}"
out = self.post("/api/notifications/state",
{"ids": [nid, "c#1#0"], "state": "read", "by": "tab-1"})
self.assertEqual(out, {"ok": True, "ids": [nid, "c#1#0"], "state": "read"})
self.assertIn({"type": "notif-state", "ids": [nid, "c#1#0"], "state": "read",
"by": "tab-1"}, self.events)
self.assertEqual(self.phone, [[n["id"]]]) # off the phone once read
self.assertEqual(self.state()["states"], {nid: "read", "c#1#0": "read"})
# Dismissed; then read again moves nothing and says nothing.
self.post("/api/notifications/state", {"ids": [nid], "state": "dismissed", "by": "tab-2"})
self.events.clear()
out = self.post("/api/notifications/state", {"ids": [nid], "state": "read"})
self.assertEqual(out["ids"], [])
self.assertEqual(self.events, [])
self.assertEqual(self.state()["states"][nid], "dismissed")
# The phone: seen = read or dismissed.
unread = self.owner.get("/api/notifications/unread", headers=OWNER_H).json()
self.assertNotIn(nid, [x["id"] for x in unread["notifications"]])
def test_guest_keeps_their_own_lists(self):
# Not on the guest surface (users/caller.py GUEST_ROUTES): a guest's
# client falls back to its ui-state lists and the older /seen.
for method, path, body in (
("get", "/api/notifications/state", None),
("post", "/api/notifications/state", {"ids": ["c#1#0"], "state": "dismissed"}),
("post", "/api/notifications/state/migrate", {"read": ["c#1#0"]})):
r = getattr(self.guest, method)(path, **({"json": body} if body else {}))
self.assertEqual(r.status_code, 403, path)
self.assertEqual(self.post("/api/notifications/seen", {"ids": ["c#1#0"]},
client=self.guest), {"ok": True, "seen": 0})
self.assertEqual(DEPS.notif_read_store.snapshot()["states"], {})
self.assertFalse(any(e.get("type") == "notif-state" for e in self.events))
def test_read_only_key_can_read_but_not_write(self):
ro = {"X-API-Key": "ro-key"}
self.assertEqual(self.owner.get("/api/notifications/state", headers=ro).status_code, 200)
for path, body in (("/api/notifications/state", {"ids": ["a"], "state": "read"}),
("/api/notifications/state/migrate", {})):
self.assertEqual(self.owner.post(path, headers=ro, json=body).status_code, 403)
def test_migrate_once_and_reload_the_other_tabs(self):
out = self.post("/api/notifications/state/migrate",
{"read": ["r"], "unread": ["u"], "dismissed": ["d"], "by": "tab-1"})
self.assertIsInstance(out.pop("baseline"), str)
self.assertEqual(out, {"enabled": True, "seeded": True, "migrated": True,
"floor": None, "states": {"r": "read", "d": "dismissed"}})
self.assertIn({"type": "notif-state", "reload": True, "by": "tab-1"}, self.events)
self.events.clear()
out = self.post("/api/notifications/state/migrate",
{"read": [], "unread": ["r"], "dismissed": [], "by": "tab-2"})
self.assertEqual(out["states"]["r"], "read")
self.assertEqual(self.events, [])
def test_migrate_with_nothing_seeds_the_whole_feed(self):
n = _create_notify(DEPS, {"title": "old", "sessionId": ""})
out = self.post("/api/notifications/state/migrate", {})
self.assertEqual(out["states"].get(f"log#{n['id']}"), "dismissed")
m = _create_notify(DEPS, {"title": "new", "sessionId": ""})
ids = [x["id"] for x in self.owner.get("/api/notifications/unread",
headers=OWNER_H).json()["notifications"]]
self.assertEqual(ids, [f"log#{m['id']}"])
def test_phone_swipe_dismisses_everywhere(self):
n = _create_notify(DEPS, {"title": "x", "sessionId": ""})
nid = f"log#{n['id']}"
self.post("/api/notifications/state", {"ids": [nid], "state": "read"})
self.events.clear()
self.post("/api/notifications/dismissed", {"tag": n["id"]})
self.assertEqual(DEPS.notif_read_store.state_of(nid), "dismissed")
self.assertIn({"type": "notif-state", "ids": [nid], "state": "dismissed",
"by": "ha"}, self.events)
self.assertIn({"type": "notif-seen", "ids": [nid]}, self.events)
def test_old_build_seen_marks_read_and_seed_is_once(self):
self.post("/api/notifications/seed", {"ids": ["a", "b"]})
self.assertEqual(self.state()["states"], {"a": "dismissed", "b": "dismissed"})
self.post("/api/notifications/seed", {"ids": ["c"]})
self.assertNotIn("c", self.state()["states"])
self.post("/api/notifications/seen", {"ids": ["c", "a"]})
self.assertEqual(self.state()["states"], {"a": "dismissed", "b": "dismissed",
"c": "read"})
self.assertIn({"type": "notif-state", "ids": ["c"], "state": "read",
"by": "legacy"}, self.events)
def test_an_old_build_can_not_mark_everything_read_after_the_import(self):
n = _create_notify(DEPS, {"title": "x", "sessionId": ""})
self.post("/api/notifications/state/migrate", {"dismissed": ["d"]})
# An old build hydrating a blob with no unread list posts `all`.
self.post("/api/notifications/seen", {"all": True})
self.assertEqual(DEPS.notif_read_store.state_of(f"log#{n['id']}"), "unread")
if __name__ == "__main__":
unittest.main()