Files
ai-agent/backend/notifications/read_ledger.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

344 lines
15 KiB
Python

"""Server-side notification state — the owner's per-notification ledger.
Every notification id in the owner's feed is in one of three states:
* ``unread`` — implicit: not in the ledger. A fresh arrival.
* ``read`` — opened (its card expanded) — it keeps its place on the
home **New** list.
* ``dismissed`` — swiped away (in the app or on the phone) — off New.
A state never goes backwards (dismissed stays dismissed) — except through the
client's one-time import of its old lists (``migrate``), which is authoritative
over what the server could only guess before it.
This is what every open PWA hydrates from and patches live (SSE
``notif-state``), and what the desk **phone** reads: *seen* = read or
dismissed, unread = the rest. Two rules the phone flow depends on:
* A read-only caller (the phone, presenting the read-only API key) fetching
the unread list must **not** mutate this — *listening on the phone doesn't
count as reading*. Only the PWA's explicit POSTs move a state.
* A first sync mustn't flood everything as unread: ``seed`` adopts the whole
current feed as the dismissed baseline, once.
* Neither may an *old* notification the ledger never heard of: the feed is
paged (``GET /api/notifications?before=``), so a PWA scrolling back syncs
ids no screen ever showed. ``baseline`` is a push time: one from before it
that isn't in the ledger reads ``dismissed``. A seed (or a first write)
takes its own second — the seed lists the whole feed anyway. The one-time
import takes the oldest push the home could show then
(``service.old_home_edge``: the newest 60 conversations' pushes — the home
fetched no more), not the import's second: the import records an
*unread* id by leaving it out, so the cards waiting on the home then have
no entry, while older ones were only "new" in a list nobody saw.
Store: one JSON file (``/data/notif-read.json``), atomic rewrite, same pattern
as ``meta.py``/``notify.py``. Shape (version 2)::
{"version": 2, "seeded": bool, "migrated": bool, "floor": "<iso>"|null,
"baseline": "<iso>"|null,
"states": {"<id>": {"s": "read"|"dismissed", "t": <epoch s>, "by": "<src>"}}}
Version 1 was ``{"seen": [ids], "seeded": bool}``; its seen ids load as
``dismissed`` (source ``v1``). The ledger is capped (oldest dropped first,
dismissed before read); ``floor`` remembers the newest ``at`` the cap dropped,
so an evicted id still reads as dismissed instead of coming back unread.
A ledger imported before ``baseline`` existed has none (``needs_baseline``):
the routes give it the home's edge as of its import — ``imported_at``, the
earliest change it recorded (every entry the import wrote carries that
second).
"""
import calendar
import json
import os
import pathlib
import threading
import time
from typing import Callable
UNREAD, READ, DISMISSED = "unread", "read", "dismissed"
STATES = (READ, DISMISSED)
_RANK = {UNREAD: 0, READ: 1, DISMISSED: 2}
_MAX_SEEN = 5000
# Sources the client's one-time import may override: what the server only had
# from before it held per-id state. Anything set through the live API since (a
# tab's swipe, the phone's) is newer than the lists being imported.
_GUESSED = {"v1", "seed", "legacy"}
def _at_of(nid: str) -> str | None:
"""The push time a conversation feed id carries (``<conv>#<at>#<i>``);
a hub-only ``log#<id>`` carries none."""
if nid.startswith("log#") or nid.count("#") < 2:
return None
return nid.rsplit("#", 2)[1] or None
def _iso(epoch: float) -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch))
# What a pre-import change says nothing about: an old build's read mark
# (``legacy``) or a v1 seen id (no time) — neither is when the ledger began
# knowing everything.
_NOT_A_START = {"legacy", "v1"}
def _epoch(at: str | None) -> float | None:
if not at:
return None
try:
return float(calendar.timegm(time.strptime(at[:19], "%Y-%m-%dT%H:%M:%S")))
except ValueError:
return None
class NotifReadStore:
def __init__(self, path: str):
self.path = pathlib.Path(path)
self._lock = threading.Lock()
# Insertion-ordered: the oldest entries are the first the cap drops.
self._states: dict[str, dict] = {}
self._seeded = False
self._migrated = False
self._floor: str | None = None
# Pushes from before it that the ledger never recorded are dismissed.
self._baseline: str | None = None
self._load()
# ── persistence ──────────────────────────────────────────────────────────
def _load(self) -> None:
try:
data = json.loads(self.path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return
if not isinstance(data, dict):
return
self._seeded = bool(data.get("seeded"))
self._migrated = bool(data.get("migrated"))
self._floor = data.get("floor") or None
self._baseline = data.get("baseline") or None
states = data.get("states")
if isinstance(states, dict):
for nid, e in states.items():
if isinstance(e, dict) and e.get("s") in STATES:
self._states[str(nid)] = {"s": e["s"], "t": e.get("t"),
"by": e.get("by") or ""}
else:
# Version 1: a plain seen list, which couldn't tell an opened card
# from a swiped one — dismissed, until the client's import says.
for nid in data.get("seen") or []:
self._states[str(nid)] = {"s": DISMISSED, "t": None, "by": "v1"}
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".json.tmp")
tmp.write_text(json.dumps({
"version": 2, "seeded": self._seeded, "migrated": self._migrated,
"floor": self._floor, "baseline": self._baseline, "states": self._states,
}, separators=(",", ":")), encoding="utf-8")
os.replace(tmp, self.path)
# ── reads ────────────────────────────────────────────────────────────────
def _state_of(self, nid: str, at: str | None = None) -> str:
e = self._states.get(nid)
if e:
return e["s"]
if self._floor or self._baseline:
t = _epoch(at or _at_of(nid))
floor, base = _epoch(self._floor), _epoch(self._baseline)
if t is not None and ((floor is not None and t <= floor)
or (base is not None and t < base)):
return DISMISSED
return UNREAD
def state_of(self, nid: str, at: str | None = None) -> str:
with self._lock:
return self._state_of(nid, at)
def is_seen(self, nid: str) -> bool:
"""Read or dismissed — what the phone counts as dealt with."""
return self.state_of(nid) != UNREAD
def seeded(self) -> bool:
with self._lock:
return self._seeded
def migrated(self) -> bool:
"""Whether a PWA's lists were imported (``migrate``) — from then on the
ledger, not any ui-state blob, is the owner's New / unread."""
with self._lock:
return self._migrated
def baseline(self) -> str | None:
"""The push time before which an id it doesn't list is dismissed."""
with self._lock:
return self._baseline
def needs_baseline(self) -> bool:
"""Imported before the baseline was kept — see ``set_baseline``."""
with self._lock:
return self._migrated and self._baseline is None
def imported_at(self) -> str | None:
"""When the one-time import ran, for a ledger that didn't keep it: its
earliest recorded change (an old build's read mark or a v1 id doesn't
count — they predate the import)."""
with self._lock:
ts = [e["t"] for e in self._states.values()
if isinstance(e.get("t"), (int, float)) and e.get("by") not in _NOT_A_START]
return _iso(min(ts)) if ts else None
def count(self) -> int:
"""How many ids the ledger holds (read or dismissed)."""
with self._lock:
return len(self._states)
def snapshot(self) -> dict:
"""Every recorded state, for a PWA to hydrate from."""
with self._lock:
return {"seeded": self._seeded, "migrated": self._migrated,
"floor": self._floor, "baseline": self._baseline,
"states": {nid: e["s"] for nid, e in self._states.items()}}
def unread(self, ids: list[str], at_of: dict[str, str | None] | None = None) -> list[str]:
"""Which of ``ids`` are unread. Pure read — never mutates the ledger.
Before the first ``seed``, nothing is considered read (so a fresh install
surfaces recent notifications rather than reporting zero); after seeding,
only ids neither read nor dismissed are unread. ``at_of`` gives the
push time of ids that don't carry one (``log#…``), for the cap floor.
"""
at_of = at_of or {}
with self._lock:
if not self._seeded:
return list(ids)
return [i for i in ids if self._state_of(i, at_of.get(i)) == UNREAD]
def on_new(self, ids: list[str]) -> set[str]:
"""Which of ``ids`` are still on the home **New** list (unread or read,
not dismissed) — what ``GET /api/notifications?new=1`` keeps."""
with self._lock:
return {i for i in ids if self._state_of(i) != DISMISSED}
# ── writes ───────────────────────────────────────────────────────────────
def _start(self) -> None:
"""Seeded from now on. A fresh ledger takes this second as its
baseline (a seed adopts the whole feed; a first write on an unseeded
ledger is the sane-baseline case). An older seeded one waits for the
import to set it."""
if not self._seeded and self._baseline is None:
self._baseline = _iso(time.time())
self._seeded = True
def set_baseline(self, at: str | None) -> bool:
"""Give a ledger that has none its baseline (``at``: a push time, ISO).
Returns whether it was set."""
with self._lock:
if self._baseline is not None or not at:
return False
self._baseline = at
self._save()
return True
def _put(self, nid: str, state: str, by: str) -> None:
self._states.pop(nid, None) # re-inserted: it's fresh again for the cap
self._states[nid] = {"s": state, "t": int(time.time()), "by": by}
def _trim(self) -> None:
over = len(self._states) - _MAX_SEEN
if over <= 0:
return
# Dismissed entries go first (oldest first); a read card is still on
# New, so it only goes when nothing else is left to drop.
order = ([n for n, e in self._states.items() if e["s"] == DISMISSED]
+ [n for n, e in self._states.items() if e["s"] != DISMISSED])
floor = _epoch(self._floor)
for nid in order[:over]:
del self._states[nid]
t = _epoch(_at_of(nid))
if t is not None and (floor is None or t > floor):
floor, self._floor = t, _at_of(nid)
def set_state(self, ids: list[str], state: str, by: str = "") -> list[str]:
"""Move ``ids`` forward to ``state`` (``read`` / ``dismissed``); an id
already there or further along is left alone. Returns the ids that
changed. Marks the ledger seeded: a client that never seeded still gets
a sane baseline."""
if state not in STATES:
raise ValueError(f"unknown state: {state}")
changed: list[str] = []
with self._lock:
for nid in dict.fromkeys(ids):
if nid and _RANK[self._state_of(nid)] < _RANK[state]:
self._put(nid, state, by)
changed.append(nid)
if changed or not self._seeded:
self._start()
self._trim()
self._save()
return changed
def mark_seen(self, ids: list[str], by: str = "legacy") -> int:
"""The pre-state API (``POST /api/notifications/seen``): ``ids`` read.
Returns how many ids the ledger holds."""
self.set_state(ids, READ, by)
return self.count()
def seed(self, ids: list[str], by: str = "seed") -> int:
"""Adopt ``ids`` as the dismissed baseline — once: a seeded ledger is
left alone (a second client's first sync mustn't swallow what arrived
since). Returns how many ids the ledger holds."""
with self._lock:
if not self._seeded:
for nid in dict.fromkeys(ids):
if nid and nid not in self._states:
self._put(nid, DISMISSED, by)
self._start()
self._trim()
self._save()
return len(self._states)
def migrate(self, read: list[str], unread: list[str], dismissed: list[str],
by: str = "", baseline: Callable[[], list[str]] | None = None,
baseline_at: Callable[[], str | None] | None = None) -> bool:
"""The client's one-time import of the lists it kept before the server
held per-id state — authoritative over what the ledger only guessed
(``_GUESSED`` sources): ``unread`` ids leave the ledger, ``read`` and
``dismissed`` are set as given. A state set through the live API since
only ever moves forward. With nothing to import and an unseeded ledger,
``baseline()`` (the whole current feed) is adopted as dismissed.
``baseline_at()``: the oldest push the client's lists can speak for
(the home's edge, ``service.old_home_edge``) — what's older and isn't
listed is dismissed from then on; default: now.
Returns False when the import already happened (a no-op)."""
with self._lock:
if self._migrated:
return False
for ids, state in ((unread, UNREAD), (read, READ), (dismissed, DISMISSED)):
for nid in dict.fromkeys(ids):
if not nid:
continue
e = self._states.get(nid)
if e and e["by"] not in _GUESSED:
if _RANK[e["s"]] >= _RANK[state]:
continue
if state == UNREAD:
self._states.pop(nid, None)
else:
self._states[nid] = {"s": state, "t": int(time.time()),
"by": by or "migrate"}
if not (read or unread or dismissed) and not self._seeded and baseline:
for nid in dict.fromkeys(baseline()):
if nid and nid not in self._states:
self._put(nid, DISMISSED, "seed")
self._migrated = True
self._seeded = True
# From here the ledger is the whole story, down to the edge of
# what the client's lists covered.
self._baseline = (baseline_at() if baseline_at else None) or _iso(time.time())
self._trim()
self._save()
return True