A conversation (and every subagent) was addressed by its transcript's path under the archive, which put the owner's home dir, project and branch names in every URL a guest saw. Now each archived transcript has a UUIDv7: - timestamp = the transcript's first timestamped record (ids sort by start, past conversations included); the other 74 bits = sha256(rel path), so a lost registry re-derives the same ids - registry: conv_uids table in ai-agent.db (conversations/ids.py), bound at startup; tree._conv_id is the one door responses go through - legacy path ids and bare session ids still resolve (_public_id) — old links, deploy.sh, the mail trigger, worker terminals - access.session_of / catalog._meta_key resolve a uid before deriving the sid; TRANSCRIPTS_DIR / <id> joins replaced by ids.path_of - SSE transcript events carry uids + a roots map (subagent → root); the guest filter trims it - thread detail: owner-only `transcript` (the archived copy's host path) - id_migration: at every start, mint missing uids and swap every known path id in /data/*.json for its uid (raw text, .bak-uids-<stamp> copies), re-key short titles + their side-call refs; cross-process safe for blue-green Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
297 lines
14 KiB
Python
297 lines
14 KiB
Python
"""The paged notification feed (``GET /api/notifications?limit=&before=&new=``)
|
|
and the read ledger's ``baseline`` — the push time before which an id the
|
|
ledger doesn't list reads dismissed, so paging back through the history never
|
|
floods the home's New list (notifications/read_ledger.py, routes.py).
|
|
|
|
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 conversations import ids # noqa: E402
|
|
from conversations.tree import _conv_id # noqa: E402
|
|
from notifications import service # noqa: E402
|
|
from notifications.read_ledger import NotifReadStore # noqa: E402
|
|
from users.caller import SESSION_COOKIE # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
T = TMP / "t"
|
|
|
|
|
|
def cid(conv: str) -> str:
|
|
"""A fake conversation's public id (its uid)."""
|
|
return _conv_id(str(T / f"{conv}.jsonl"))
|
|
|
|
|
|
def name_of(uid: str) -> str:
|
|
"""…and back to the name the test gave it."""
|
|
return pathlib.PurePosixPath(ids.REGISTRY.rel(uid) or uid).name.removesuffix(".jsonl")
|
|
|
|
|
|
def nid(conv: str, at: str, i: int = 0) -> str:
|
|
return f"{cid(conv)}#{at}#{i}"
|
|
|
|
|
|
class Feed(unittest.TestCase):
|
|
"""A fake history: ``convs`` maps a conversation name to (endedAt, its
|
|
push times, oldest first)."""
|
|
|
|
def setUp(self):
|
|
self.owner = TestClient(main.app)
|
|
DEPS.notif_read_store = NotifReadStore(str(TMP / f"nr-{self._testMethodName}.json"))
|
|
self.convs: dict[str, tuple[str, list[str]]] = {}
|
|
orig = DEPS.store.all_summaries
|
|
DEPS.store.all_summaries = lambda: [
|
|
(str(T / f"{name}.jsonl"), {"sessionId": self.sid(name), "messages": 1,
|
|
"endedAt": ended})
|
|
for name, (ended, _) in self.convs.items()]
|
|
self.addCleanup(setattr, DEPS.store, "all_summaries", orig)
|
|
|
|
def sid(self, name: str) -> str:
|
|
return f"{self._testMethodName}-{name}"
|
|
|
|
def conv(self, name: str, ended: str, *ats: str, meta: dict | None = None):
|
|
self.convs[name] = (ended, list(ats))
|
|
if meta:
|
|
DEPS.meta_store.update(self.sid(name), dict(meta))
|
|
for i, at in enumerate(ats):
|
|
DEPS.meta_store.update(self.sid(name), {"notification": {
|
|
"title": f"{name} {i}", "body": "", "at": at}})
|
|
|
|
def get(self, client=None, **params):
|
|
r = (client or self.owner).get("/api/notifications", params=params,
|
|
headers=OWNER_H if client is None else {})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
return r.json()
|
|
|
|
@staticmethod
|
|
def ids(page) -> list[str]:
|
|
return [name_of(c["id"]) for c in page["conversations"]]
|
|
|
|
|
|
class Paging(Feed):
|
|
def setUp(self):
|
|
super().setUp()
|
|
# endedAt deliberately out of step with the pushes: the order is the
|
|
# newest push, not the end time.
|
|
self.conv("a", "2026-10-31T00:00:00Z", "2026-10-01T10:00:00Z", "2026-10-05T10:00:00Z")
|
|
self.conv("b", "2026-10-02T00:00:00Z", "2026-10-02T10:00:00Z")
|
|
self.conv("c", "2026-10-20T00:00:00Z", "2026-10-04T10:00:00Z")
|
|
self.conv("d", "2026-10-03T00:00:00Z", "2026-10-03T10:00:00Z")
|
|
self.conv("e", "2026-10-06T00:00:00Z", "2026-10-06T10:00:00Z")
|
|
|
|
def test_the_unpaged_call_keeps_its_shape(self):
|
|
out = self.get()
|
|
self.assertEqual(self.ids(out), ["e", "a", "c", "d", "b"])
|
|
self.assertEqual((out["count"], out["total"], out["nextBefore"]), (5, 5, None))
|
|
self.assertEqual([n["at"] for n in out["conversations"][1]["notifications"]],
|
|
["2026-10-01T10:00:00Z", "2026-10-05T10:00:00Z"])
|
|
# A bare limit is the first page, as before.
|
|
self.assertEqual(self.ids(self.get(limit=2)), ["e", "a"])
|
|
|
|
def test_pages_walk_the_feed_newest_push_first(self):
|
|
seen, before, pages = [], None, 0
|
|
while True:
|
|
page = self.get(limit=2, **({"before": before} if before else {}))
|
|
pages += 1
|
|
self.assertEqual(page["total"], 5)
|
|
self.assertEqual(page["count"], len(page["conversations"]))
|
|
seen += self.ids(page)
|
|
before = page["nextBefore"]
|
|
if not before:
|
|
break
|
|
self.assertEqual(before, f"{page['conversations'][-1]['notifications'][-1]['at']}"
|
|
f"|{page['conversations'][-1]['id']}")
|
|
self.assertEqual(seen, ["e", "a", "c", "d", "b"])
|
|
self.assertEqual(pages, 3)
|
|
|
|
def test_a_page_boundary_inside_a_tie_loses_nothing(self):
|
|
self.conv("f", "2026-10-06T00:00:00Z", "2026-10-06T10:00:00Z") # same push as e
|
|
first = self.get(limit=1)
|
|
self.assertEqual(self.ids(first), ["f"])
|
|
second = self.get(limit=1, before=first["nextBefore"])
|
|
self.assertEqual(self.ids(second), ["e"])
|
|
|
|
def test_a_bare_timestamp_is_a_cursor_too(self):
|
|
self.assertEqual(self.ids(self.get(before="2026-10-05T10:00:00Z")), ["c", "d", "b"])
|
|
|
|
|
|
class New(Feed):
|
|
def test_new_keeps_the_conversations_still_on_new(self):
|
|
self.conv("gone", "2026-10-30T00:00:00Z", "2026-10-30T10:00:00Z", "2026-10-30T11:00:00Z")
|
|
self.conv("read", "2026-10-29T00:00:00Z", "2026-10-29T10:00:00Z", "2026-10-29T11:00:00Z")
|
|
self.conv("fresh", "2026-10-28T00:00:00Z", "2026-10-28T10:00:00Z")
|
|
self.conv("old", "2026-10-27T00:00:00Z", "2026-06-01T10:00:00Z")
|
|
store = DEPS.notif_read_store
|
|
store.set_baseline("2026-10-01T00:00:00Z")
|
|
store.set_state([nid("gone", "2026-10-30T10:00:00Z", 0),
|
|
nid("gone", "2026-10-30T11:00:00Z", 1),
|
|
nid("read", "2026-10-29T11:00:00Z", 1)], "dismissed")
|
|
store.set_state([nid("read", "2026-10-29T10:00:00Z", 0)], "read")
|
|
out = self.get(new=1)
|
|
# "old" predates the baseline and isn't listed: dismissed.
|
|
self.assertEqual(self.ids(out), ["read", "fresh"])
|
|
self.assertEqual(out["total"], 2)
|
|
# The conversation comes whole: the client filters its cards.
|
|
self.assertEqual(len(out["conversations"][0]["notifications"]), 2)
|
|
self.assertEqual(self.ids(self.get(new=1, limit=1)), ["read"])
|
|
self.assertEqual(self.ids(self.get()), ["gone", "read", "fresh", "old"])
|
|
|
|
def test_a_guest_gets_their_feed_unfiltered(self):
|
|
for u in DEPS.users.all():
|
|
DEPS.users.delete(u["id"])
|
|
dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
|
|
guest = TestClient(main.app, base_url="https://claude.example.test")
|
|
guest.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(dom["id"]))
|
|
self.conv("doms", "2026-10-30T00:00:00Z", "2026-06-01T10:00:00Z",
|
|
meta={"owner": dom["id"], "projects": ["film"]})
|
|
DEPS.notif_read_store.set_baseline("2026-10-01T00:00:00Z")
|
|
self.assertEqual(self.ids(self.get(client=guest, new=1)), ["doms"])
|
|
|
|
|
|
class Baseline(unittest.TestCase):
|
|
def setUp(self):
|
|
self.path = pathlib.Path(tempfile.mkdtemp()) / "nr.json"
|
|
|
|
def store(self) -> NotifReadStore:
|
|
return NotifReadStore(str(self.path))
|
|
|
|
def test_a_seed_dismisses_what_came_before_it(self):
|
|
s = self.store()
|
|
s.seed([nid("a", "2026-10-01T10:00:00Z")])
|
|
base = s.baseline()
|
|
self.assertIsNotNone(base)
|
|
older = nid("b", "2020-01-01T00:00:00Z") # paged in later, never listed
|
|
later = nid("c", "2999-01-01T00:00:00Z") # arrives after the seed
|
|
self.assertEqual((s.state_of(older), s.state_of(later)), ("dismissed", "unread"))
|
|
self.assertEqual(s.unread([older, later, "log#x", "log#y"],
|
|
{"log#x": "2020-01-01T00:00:00Z",
|
|
"log#y": "2999-01-01T00:00:00Z"}),
|
|
[later, "log#y"])
|
|
# Kept on disk, and handed to the PWAs.
|
|
self.assertEqual(self.store().snapshot()["baseline"], base)
|
|
self.assertEqual(json.loads(self.path.read_text())["baseline"], base)
|
|
# Nothing to move: a dismissed id can't be read again.
|
|
self.assertEqual(s.set_state([older], "read"), [])
|
|
|
|
def test_the_import_keeps_what_the_home_could_show(self):
|
|
s = self.store()
|
|
shown_unread = nid("a", "2026-10-31T10:00:00Z")
|
|
hidden_unread = nid("b", "2026-06-01T10:00:00Z") # an old list's "new"
|
|
read_long_ago = nid("c", "2026-05-01T10:00:00Z")
|
|
self.assertTrue(s.migrate(read=[read_long_ago], unread=[shown_unread, hidden_unread],
|
|
dismissed=[], by="tab-1",
|
|
baseline_at=lambda: "2026-10-30T00:00:00Z"))
|
|
self.assertEqual(s.baseline(), "2026-10-30T00:00:00Z")
|
|
self.assertEqual([s.state_of(i) for i in (shown_unread, hidden_unread, read_long_ago)],
|
|
["unread", "dismissed", "read"])
|
|
self.assertEqual(s.on_new([shown_unread, hidden_unread, read_long_ago]),
|
|
{shown_unread, read_long_ago})
|
|
# The push at the edge itself is still on the home.
|
|
self.assertEqual(s.state_of(nid("d", "2026-10-30T00:00:00Z")), "unread")
|
|
# With no edge to give, the import's own second.
|
|
s2 = NotifReadStore(str(self.path.with_name("other.json")))
|
|
s2.migrate([], [], [], baseline_at=lambda: None)
|
|
self.assertIsNotNone(s2.baseline())
|
|
|
|
def test_a_seeded_ledger_waits_for_the_import(self):
|
|
# A v1 / seeded ledger from before the import: a live write doesn't
|
|
# set a baseline (what came since the seed is genuinely unread).
|
|
self.path.write_text(json.dumps({"seen": ["a"], "seeded": True}))
|
|
s = self.store()
|
|
s.set_state(["b"], "read", "ha")
|
|
self.assertIsNone(s.baseline())
|
|
self.assertFalse(s.needs_baseline())
|
|
# A fresh one's first write is its seed.
|
|
s2 = NotifReadStore(str(self.path.with_name("fresh.json")))
|
|
s2.set_state(["b"], "read")
|
|
self.assertIsNotNone(s2.baseline())
|
|
|
|
def test_an_import_from_before_the_baseline_knows_when_it_ran(self):
|
|
# The shape of the ledger the first import wrote (2026-11-01).
|
|
self.path.write_text(json.dumps({
|
|
"version": 2, "seeded": True, "migrated": True, "floor": None,
|
|
"states": {"v1-id": {"s": "dismissed", "t": None, "by": "v1"},
|
|
"legacy": {"s": "read", "t": 1700000000, "by": "legacy"},
|
|
"x": {"s": "read", "t": 1793573360, "by": "tab-1"},
|
|
"y": {"s": "dismissed", "t": 1793573627, "by": "tab-1"}}}))
|
|
s = self.store()
|
|
self.assertTrue(s.needs_baseline())
|
|
self.assertEqual(s.imported_at(), "2026-11-01T22:49:20Z")
|
|
self.assertTrue(s.set_baseline("2026-10-30T13:51:32Z"))
|
|
self.assertFalse(s.set_baseline("2026-11-01T00:00:00Z")) # once
|
|
self.assertFalse(self.store().needs_baseline())
|
|
self.assertEqual(self.store().baseline(), "2026-10-30T13:51:32Z")
|
|
|
|
|
|
class Upgrade(Feed):
|
|
"""A ledger imported before the baseline existed (the live one) gets the
|
|
edge of what the home could show at the import, on first use."""
|
|
|
|
def setUp(self):
|
|
super().setUp()
|
|
self.window = service.OLD_HOME_WINDOW
|
|
service.OLD_HOME_WINDOW = 2
|
|
self.addCleanup(setattr, service, "OLD_HOME_WINDOW", self.window)
|
|
path = TMP / f"nr-up-{self._testMethodName}.json"
|
|
path.write_text(json.dumps({
|
|
"version": 2, "seeded": True, "migrated": True, "floor": None,
|
|
# imported at 2026-11-01T22:49:20Z: one card read, the rest of
|
|
# what was new left out (= unread).
|
|
"states": {nid("shown", "2026-10-31T09:00:00Z", 0):
|
|
{"s": "read", "t": 1793573360, "by": "tab-1"}}}))
|
|
DEPS.notif_read_store = NotifReadStore(str(path))
|
|
self.path = path
|
|
# The two conversations that ended last before the import were the
|
|
# home's window; its oldest push is the edge.
|
|
self.conv("shown", "2026-11-01T20:00:00Z", "2026-10-31T09:00:00Z", "2026-10-31T10:00:00Z")
|
|
self.conv("also", "2026-11-01T10:00:00Z", "2026-10-30T13:51:32Z")
|
|
self.conv("deep", "2026-10-29T00:00:00Z", "2026-10-29T10:00:00Z")
|
|
self.conv("after", "2026-11-02T00:00:00Z", "2026-11-01T23:00:00Z")
|
|
|
|
def test_the_state_gets_the_homes_edge(self):
|
|
st = self.owner.get("/api/notifications/state", headers=OWNER_H).json()
|
|
self.assertEqual(st["baseline"], "2026-10-30T13:51:32Z")
|
|
self.assertEqual(json.loads(self.path.read_text())["baseline"], "2026-10-30T13:51:32Z")
|
|
# On New: the window's cards and what came after the import, not the
|
|
# deep history nobody was shown.
|
|
self.assertEqual(self.ids(self.get(new=1)), ["after", "shown", "also"])
|
|
|
|
def test_the_phone_reads_the_same(self):
|
|
unread = self.owner.get("/api/notifications/unread", headers=OWNER_H).json()
|
|
convs = {name_of(n["convId"]) for n in unread["notifications"]}
|
|
self.assertEqual(convs, {"after", "shown", "also"})
|
|
self.assertNotIn(nid("shown", "2026-10-31T09:00:00Z", 0),
|
|
[n["id"] for n in unread["notifications"]])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|