Archiving is being done with a conversation: every push of it on the
owner's feed moves to dismissed in his read ledger — off home's New list,
seen on the phone's /unread, cleared off his web push devices and the
phone's shade — and every open PWA hears it as SSE notif-state
(by: "archive"), so the stack slides out right and the list closes the
gap, on this device and any other with home on screen.
- notifications/routes.dismiss_archived + service.conversation_feed_ids
(every transcript's <conv>#<at>#<i>, the session's hub-only log# entries;
an ask still pending is left out). Never backwards: unarchiving brings
nothing back.
- Called by the owner's POST /api/conversation-meta {archived: true} (the
drawer menu, `ai-agent archive`, MCP archive_conversation) and
archive-old; the auto-archive sweep only for test runs, ledger only —
a cron run's push is the job's report and stays on New. A guest
archiving their own conversation leaves the owner's ledger alone.
- _clear_read clears the phone in one webhook call, and can be held to
the archived sessions (entries_for_feed_ids matched any push of the
same second).
- Frontend: the archiving tab drops the stack at once
(dropConversationNotifs), without waiting for the event.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
247 lines
12 KiB
Python
247 lines
12 KiB
Python
"""Archiving a conversation dismisses its pushes in the owner's read ledger
|
|
(``notifications.routes.dismiss_archived``): off the home's New list and the
|
|
phone's unread, every open PWA told (``notif-state``, ``by: archive``), the
|
|
pushes taken off his devices — from ``POST /api/conversation-meta`` (the app,
|
|
the ``ai-agent`` CLI, MCP ``archive_conversation``), the drawer's
|
|
``archive-old`` and the auto-archive sweep (test runs only, ledger only).
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
import uuid
|
|
|
|
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",
|
|
"SECURITY_STATE_PATH": TMP / "sec.json",
|
|
"SECURITY_LOG_PATH": TMP / "sec.jsonl",
|
|
"READONLY_API_KEY": "ro-key",
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
|
|
"GUEST_PUBLIC_URL": "https://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 notifications.service as svc # noqa: E402
|
|
from conversations import autoarchive # noqa: E402
|
|
from conversations.tree import _conv_id # noqa: E402
|
|
from notifications.read_ledger import NotifReadStore # noqa: E402
|
|
from notifications.service import _create_ask, _create_notify # noqa: E402
|
|
from users.caller import OWNER_ID # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
T = TMP / "t"
|
|
|
|
|
|
class ArchiveDismisses(unittest.TestCase):
|
|
"""A fake history: ``self.convs`` maps a conversation name to its endedAt."""
|
|
|
|
def setUp(self):
|
|
self.c = TestClient(main.app)
|
|
store = NotifReadStore(str(TMP / f"nr-{self._testMethodName}.json"))
|
|
store.set_baseline("2026-01-01T00:00:00Z") # every push below is newer
|
|
store.seed([])
|
|
DEPS.notif_read_store = store
|
|
self.convs: dict[str, 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)
|
|
self.events: list[dict] = []
|
|
pub = DEPS.hub.publish
|
|
DEPS.hub.publish = lambda ev: self.events.append(ev) or pub(ev)
|
|
self.addCleanup(setattr, DEPS.hub, "publish", pub)
|
|
self.phone: list[list[str]] = []
|
|
clear = svc.clear_phone
|
|
svc.clear_phone = lambda deps, tags: self.phone.append(list(tags))
|
|
self.addCleanup(setattr, svc, "clear_phone", clear)
|
|
|
|
def sid(self, name: str) -> str:
|
|
return f"{self._testMethodName}-{name}"
|
|
|
|
def conv(self, name: str, ended: str = "2099-01-01T00:00:00Z", meta: dict | None = None):
|
|
self.convs[name] = ended
|
|
if meta:
|
|
DEPS.meta_store.update(self.sid(name), dict(meta))
|
|
|
|
def push(self, name: str, title: str) -> tuple[str, str]:
|
|
"""A push from conversation ``name``: (its feed id, its hub log id)."""
|
|
if name not in self.convs:
|
|
self.conv(name)
|
|
n = _create_notify(DEPS, {"title": title, "message": "", "sessionId": self.sid(name)})
|
|
notes = DEPS.meta_store.peek(self.sid(name))["notifications"]
|
|
i = len(notes) - 1
|
|
return f"{_conv_id(str(T / f'{name}.jsonl'))}#{notes[i]['at']}#{i}", n["id"]
|
|
|
|
def post(self, path, body, headers=None):
|
|
r = self.c.post(path, json=body, headers=headers or OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
return r.json()
|
|
|
|
def archive(self, name: str, on: bool = True, headers=None):
|
|
return self.post("/api/conversation-meta", {"id": self.sid(name), "archived": on},
|
|
headers)
|
|
|
|
def state(self, fid: str) -> str:
|
|
return DEPS.notif_read_store.state_of(fid)
|
|
|
|
def notif_states(self) -> list[dict]:
|
|
return [e for e in self.events if e.get("type") == "notif-state"]
|
|
|
|
def new_list(self) -> list[str]:
|
|
r = self.c.get("/api/notifications", params={"new": 1}, headers=OWNER_H)
|
|
return [c["id"] for c in r.json()["conversations"]]
|
|
|
|
def unread(self) -> list[str]:
|
|
r = self.c.get("/api/notifications/unread", headers=OWNER_H)
|
|
return [n["id"] for n in r.json()["notifications"]]
|
|
|
|
# ── the meta route: the app, the CLI, MCP ────────────────────────────────
|
|
def test_archiving_dismisses_the_conversations_pushes_everywhere(self):
|
|
a1, a1_log = self.push("a", "a first")
|
|
a2, a2_log = self.push("a", "a second")
|
|
b1, _ = self.push("b", "b only")
|
|
# One of them opened on some tab: read, still on New.
|
|
self.post("/api/notifications/state", {"ids": [a1], "state": "read", "by": "tab-1"})
|
|
self.events.clear()
|
|
self.phone.clear()
|
|
|
|
self.archive("a")
|
|
self.assertEqual((self.state(a1), self.state(a2), self.state(b1)),
|
|
("dismissed", "dismissed", "unread"))
|
|
# Every open PWA hears it — the archiving tab too (`by` is no tab's).
|
|
self.assertEqual(self.notif_states(), [{"type": "notif-state", "ids": [a1, a2],
|
|
"state": "dismissed", "by": "archive"}])
|
|
# …before the meta event that refetches the lists.
|
|
kinds = [e["type"] for e in self.events]
|
|
self.assertLess(kinds.index("notif-state"), kinds.index("meta"))
|
|
# Off the phone's shade in one call — only this conversation's pushes.
|
|
self.assertEqual(len(self.phone), 1)
|
|
self.assertEqual(sorted(self.phone[0]), sorted([a1_log, a2_log]))
|
|
# Off New and off the phone's unread.
|
|
b = _conv_id(str(T / "b.jsonl"))
|
|
self.assertEqual(self.new_list(), [b])
|
|
unread = self.unread() # (other tests' hub-only pushes are in it too)
|
|
self.assertIn(b1, unread)
|
|
for gone in (a1, a2, f"log#{a1_log}", f"log#{a2_log}"):
|
|
self.assertNotIn(gone, unread)
|
|
|
|
def test_never_backwards_and_unarchiving_brings_nothing_back(self):
|
|
a1, _ = self.push("a", "a first")
|
|
self.archive("a")
|
|
self.events.clear()
|
|
self.archive("a", on=False)
|
|
self.assertEqual(self.state(a1), "dismissed")
|
|
self.assertEqual(self.notif_states(), [])
|
|
# A push after that is new; archiving again moves only it.
|
|
a2, _ = self.push("a", "a again")
|
|
self.assertEqual(self.state(a2), "unread")
|
|
self.events.clear()
|
|
self.archive("a")
|
|
self.assertEqual(self.notif_states(), [{"type": "notif-state", "ids": [a2],
|
|
"state": "dismissed", "by": "archive"}])
|
|
# Archiving what is archived already says nothing.
|
|
self.events.clear()
|
|
self.archive("a")
|
|
self.assertEqual(self.notif_states(), [])
|
|
|
|
def test_a_question_still_open_is_not_seen_by_archiving(self):
|
|
self.conv("a")
|
|
pending = _create_ask(DEPS, {"question": "Ship it?", "options": ["Yes", "No"],
|
|
"sessionId": self.sid("a")})["id"]
|
|
answered = _create_ask(DEPS, {"question": "Which one?", "options": ["A", "B"],
|
|
"sessionId": self.sid("a")})["id"]
|
|
DEPS.notify_store.answer_ask(answered, 0, "A")
|
|
other = _create_notify(DEPS, {"title": "unrelated", "message": "",
|
|
"sessionId": ""})["id"]
|
|
self.archive("a")
|
|
self.assertEqual(self.state(f"log#{answered}"), "dismissed")
|
|
self.assertEqual(self.state(f"log#{pending}"), "unread")
|
|
self.assertEqual(self.state(f"log#{other}"), "unread")
|
|
self.assertIn(f"log#{pending}", self.unread())
|
|
|
|
def test_a_conversation_without_pushes_moves_nothing(self):
|
|
self.conv("quiet")
|
|
self.archive("quiet")
|
|
self.assertEqual(self.notif_states(), [])
|
|
self.assertEqual(DEPS.notif_read_store.snapshot()["states"], {})
|
|
|
|
# ── a guest's conversation ───────────────────────────────────────────────
|
|
def test_a_guest_conversation_only_moves_for_the_owners_own_archive(self):
|
|
for u in DEPS.users.all():
|
|
DEPS.users.delete(u["id"])
|
|
dom = DEPS.users.create("dom@example.com", "Dom", cli=True, projects={"film": "chat"})
|
|
DEPS.security_state.set_locked(False)
|
|
run = str(uuid.uuid4()) # dom's live run, the CLI call's session
|
|
DEPS.meta_store.update(run, {"owner": dom["id"], "runAs": dom["id"],
|
|
"projects": ["film"], "state": "running"})
|
|
# Dom's conversation, which the owner follows (so it is in his feed).
|
|
self.conv("g", meta={"owner": dom["id"], "projects": ["film"],
|
|
"follow": {OWNER_ID: True}})
|
|
g1, _ = self.push("g", "dom's push")
|
|
# Dom archives it from their CLI: his ledger is his, untouched.
|
|
self.archive("g", headers={**OWNER_H, "X-AIA-As-Session": run})
|
|
self.assertTrue(DEPS.meta_store.peek(self.sid("g")).get("archived"))
|
|
self.assertEqual(self.state(g1), "unread")
|
|
self.assertEqual(self.notif_states(), [])
|
|
# The owner archives it: dismissed for him.
|
|
self.archive("g", on=False)
|
|
self.archive("g")
|
|
self.assertEqual(self.state(g1), "dismissed")
|
|
|
|
def test_a_guest_conversation_the_owner_does_not_hear_is_not_his_feed(self):
|
|
self.conv("g", meta={"owner": "someone"})
|
|
DEPS.meta_store.update(self.sid("g"), {"notification": {
|
|
"title": "theirs", "body": "", "at": "2026-11-06T10:00:00Z"}})
|
|
self.archive("g")
|
|
self.assertEqual(DEPS.notif_read_store.snapshot()["states"], {})
|
|
|
|
# ── the drawer's archive-old ─────────────────────────────────────────────
|
|
def test_archive_old_dismisses_what_it_archives(self):
|
|
old1, _ = self.push("old", "from last week")
|
|
new1, _ = self.push("fresh", "from today")
|
|
self.convs["old"] = "2026-01-02T00:00:00Z"
|
|
out = self.post("/api/conversations/archive-old", {})
|
|
self.assertEqual(out["archived"], 1)
|
|
self.assertEqual((self.state(old1), self.state(new1)), ("dismissed", "unread"))
|
|
self.assertIn({"type": "notif-state", "ids": [old1], "state": "dismissed",
|
|
"by": "archive"}, self.events)
|
|
|
|
# ── the auto-archive sweep ───────────────────────────────────────────────
|
|
def test_the_sweep_dismisses_a_test_runs_pushes_not_a_cron_runs(self):
|
|
t1, _ = self.push("test", "a throwaway run's push")
|
|
c1, _ = self.push("cron", "radar: today's digest")
|
|
self.events.clear()
|
|
self.phone.clear()
|
|
autoarchive.archive(DEPS, [{"sessionId": self.sid("test"), "kind": "test"},
|
|
{"sessionId": self.sid("cron"), "kind": "cron"}])
|
|
self.assertEqual(self.state(t1), "dismissed")
|
|
self.assertEqual(self.state(c1), "unread") # the job's report stays on New
|
|
self.assertEqual(self.notif_states(), [{"type": "notif-state", "ids": [t1],
|
|
"state": "dismissed", "by": "auto-archive"}])
|
|
self.assertEqual(self.phone, []) # nobody acted: the phone keeps it
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|