Files
ai-agent/backend/test_conv_uid_routes.py
gabrielvidalandClaude Opus 5.5 a40bd23b01 feat(plugins): the Related conversations card leaves the core for the graph plugin
The core must not carry features that belong to plugins: the Details
drawer's *Related conversations* card is now the graph plugin's
`conv-related` conversation.details slot.

- New owner-only bridge under graph.read:
  GET /proxy/tools/plugins/{pid}/hub/graph/related?id=<conversation or
  session id> → {id, related, kinds} (plugins/graphdata.related): the same
  conversations/related.py index the core route read, plus each shared
  pill kind's label / icon / colour from its resource plugin, so the frame
  draws the pills without the app's code.
- DETAIL_CARD_RENAMES: related → plugin:graph:conv-related, so a saved
  arrangement keeps its slot.
- Gone from the core: RelatedConversations.tsx (card + hook), the
  `relatedConversations` visibility switch (a plugin card is benched like
  any card), GET /api/conversations/{id}/related with its schemas, authz
  entry, mock route, api.ts call, QK.related and the French strings only
  it used. conversations/related.py stays (past.py reads its index).
- openapi.json re-dumped, src/generated regenerated; docs/plugins.md and
  CLAUDE.md say where it went.
- Tests: test_plugin_graph covers graphdata.related (id resolution,
  ordering, kinds) and the bridge (owner 200, 400 without id, guest 403,
  capability 403) and that the core card and route are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:57:19 +01:00

139 lines
6.9 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)
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()