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>
141 lines
7.0 KiB
Python
141 lines
7.0 KiB
Python
"""Conversation ids over HTTP: every response names a conversation by its
|
|
UUIDv7 (conversations/ids.py), and whatever an old link or a script names it
|
|
by — the legacy transcript path, a bare session id — still opens it. The path
|
|
behind the uid goes to the owner only; a guest neither gets it nor can reach a
|
|
conversation that isn't theirs through any spelling.
|
|
|
|
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",
|
|
"NEW_PROJECTS_PATH": TMP / "np.json", "PROJECTS_DIR": TMP / "projects",
|
|
"UPLOADS_HOST_DIR": "/srv/ai-agent/data/uploads",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
|
|
"GUEST_HOSTS": "claude.example.test", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from conversations import ids # noqa: E402
|
|
from conversations.card import transcript_event # noqa: E402
|
|
from core.routes import _guest_filter # noqa: E402
|
|
from users.caller import SESSION_COOKIE, Caller # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
SID = "11111111-2222-4333-8444-555555555555"
|
|
DOMS = "22222222-2222-4333-8444-555555555555"
|
|
ROOT = f"-home-gabrielvidal-projects-secret/{SID}.jsonl"
|
|
SUB = f"-home-gabrielvidal-projects-secret/{SID}/subagents/agent-a1.jsonl"
|
|
DOM_ROOT = f"-home-gabrielvidal-projects-film/{DOMS}.jsonl"
|
|
|
|
|
|
def write(rel: str, sid: str, sidechain: bool = False) -> None:
|
|
p = TMP / "arch" / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
extra = {"isSidechain": True, "agentId": "a1"} if sidechain else {}
|
|
p.write_text("\n".join(json.dumps(o) for o in [
|
|
{"type": "ai-title", "aiTitle": "Secret project"},
|
|
{"type": "user", "uuid": "u1", "sessionId": sid, "timestamp": "2026-10-13T20:00:00.250Z",
|
|
"message": {"role": "user", "content": "hi"}, **extra},
|
|
{"type": "assistant", "uuid": "a1", "sessionId": sid, "timestamp": "2026-10-13T20:00:01Z",
|
|
"message": {"role": "assistant", "model": "claude-opus-5-5",
|
|
"content": [{"type": "text", "text": "hello"}]}, **extra},
|
|
]) + "\n")
|
|
|
|
|
|
class ConvUidRoutes(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
write(ROOT, SID)
|
|
write(SUB, SID, sidechain=True)
|
|
write(DOM_ROOT, DOMS)
|
|
DEPS.indexer.scan_transcripts()
|
|
|
|
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"})
|
|
DEPS.meta_store.update(DOMS, {"owner": self.dom["id"], "projects": ["film"]})
|
|
self.owner = TestClient(main.app, headers={"x-internal-auth": "tok"})
|
|
self.guest = TestClient(main.app, base_url="https://claude.example.test")
|
|
self.guest.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
|
|
|
|
def detail(self, client, id):
|
|
return client.get("/api/conversation", params={"id": id})
|
|
|
|
def test_the_list_carries_uids_sorted_like_their_start(self):
|
|
cards = self.owner.get("/api/conversations").json()["conversations"]
|
|
got = {c["sessionId"]: c["id"] for c in cards}
|
|
self.assertTrue(ids.is_uid(got[SID]) and ids.is_uid(got[DOMS]))
|
|
self.assertEqual(ids.uid_time(got[SID]), 1791921600.25) # its first message
|
|
self.assertTrue(all(ids.is_uid(c["id"]) for c in cards))
|
|
|
|
def test_every_spelling_opens_the_conversation_as_its_uid(self):
|
|
uid = ids.uid_for_rel(ROOT)
|
|
for spelling in (uid, ROOT, SID):
|
|
r = self.detail(self.owner, spelling)
|
|
self.assertEqual(r.status_code, 200, (spelling, r.text))
|
|
self.assertEqual(r.json()["id"], uid)
|
|
self.assertIsNone(r.json()["continuedIn"])
|
|
|
|
def test_a_subagent_has_its_own_uid(self):
|
|
subs = self.owner.get("/api/subagents").json()["subagents"]
|
|
[sub] = [s for s in subs if s["rootId"] == ids.uid_for_rel(ROOT)]
|
|
self.assertEqual(sub["id"], ids.uid_for_rel(SUB))
|
|
self.assertEqual(sub["parentId"], ids.uid_for_rel(ROOT))
|
|
page = self.detail(self.owner, sub["id"]).json()
|
|
self.assertEqual(page["id"], sub["id"])
|
|
self.assertEqual(page["parentConversation"]["id"], ids.uid_for_rel(ROOT))
|
|
self.assertEqual(self.detail(self.owner, SUB).json()["id"], sub["id"])
|
|
|
|
def test_the_transcript_path_is_the_owners_alone(self):
|
|
own = self.detail(self.owner, ids.uid_for_rel(DOM_ROOT)).json()
|
|
self.assertEqual(own["transcript"], f"/srv/ai-agent/data/transcripts/{DOM_ROOT}")
|
|
theirs = self.detail(self.guest, ids.uid_for_rel(DOM_ROOT))
|
|
self.assertEqual(theirs.status_code, 200, theirs.text)
|
|
self.assertIsNone(theirs.json()["transcript"])
|
|
self.assertEqual(theirs.json()["id"], ids.uid_for_rel(DOM_ROOT))
|
|
|
|
def test_a_guest_reaches_no_other_conversation_by_any_spelling(self):
|
|
for spelling in (ids.uid_for_rel(ROOT), ROOT, SID, ids.uid_for_rel(SUB), SUB):
|
|
self.assertEqual(self.detail(self.guest, spelling).status_code, 404, spelling)
|
|
self.assertEqual(self.guest.get("/api/conversation-summary",
|
|
params={"id": ids.uid_for_rel(ROOT)}).status_code, 404)
|
|
uid = ids.uid_for_rel(DOM_ROOT)
|
|
self.assertEqual(self.guest.get(f"/api/conversations/{uid}/related").status_code, 200)
|
|
|
|
def test_unknown_ids(self):
|
|
self.assertEqual(self.detail(self.owner, "019a0000-0000-7000-8000-000000000000").status_code, 404)
|
|
self.assertEqual(self.detail(self.owner, "../../etc/passwd.jsonl").status_code, 400)
|
|
self.assertEqual(self.detail(self.owner, "nope").status_code, 400)
|
|
|
|
def test_the_transcript_event_names_uids_and_each_subagents_root(self):
|
|
ev = transcript_event([SUB, ROOT])
|
|
self.assertEqual(ev["ids"], [ids.uid_for_rel(SUB), ids.uid_for_rel(ROOT)])
|
|
self.assertEqual(ev["roots"], {ids.uid_for_rel(SUB): ids.uid_for_rel(ROOT)})
|
|
# A guest's stream keeps only what they can see — the roots map too.
|
|
dom = Caller(id=self.dom["id"], role="guest", name="Dom")
|
|
both = transcript_event([SUB, DOM_ROOT])
|
|
self.assertEqual(_guest_filter(DEPS, dom)(both),
|
|
{"type": "transcript", "ids": [ids.uid_for_rel(DOM_ROOT)], "roots": {}})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|