A text block past 8,000 chars was cut mid-line with an inline
'… [N more chars truncated]' marker — mid-table, it broke the markdown.
records._clip now cuts on a block boundary (a blank line outside a code
fence, else between two lines, never between a table's header and its
rule; a fence cut inside is closed again) and adds no marker. The item
carries clipped ({field: full length}) + clipId, the parser keeps the
full text (clip_fields / full_field / last_answer), and
GET /api/conversation-full-text serves it (conversations.read).
Answers read server-side are whole too: a child's report back and guest
deliveries (cron/guests.final_answer), and the plugin hub route.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
177 lines
7.3 KiB
Python
177 lines
7.3 KiB
Python
"""The ``conversations.read`` bridge a plugin reads (Left to do, 2026-11-25):
|
|
each row carries the id the app's links take and what a plugin needs to pick
|
|
conversations (user turns, turn ended, the run-kind flags); one conversation
|
|
answers its newest transcript's final answer. And the core's old
|
|
``/data/leftovers.json`` is carried into the plugin's data once."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import json
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
import main
|
|
from plugins import carryover
|
|
from plugins.proxyroutes import final_answer
|
|
from plugins.store import OWNER_UID, PluginStore
|
|
from toolproxy import access
|
|
|
|
NOW = dt.datetime.now(dt.timezone.utc)
|
|
|
|
|
|
def _iso(hours_ago: float) -> str:
|
|
return (NOW - dt.timedelta(hours=hours_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
MANIFEST = {"schema": 1, "id": "cr", "name": "Reader", "capabilities": ["conversations.read"]}
|
|
|
|
|
|
class FakeSummaries:
|
|
def __init__(self, rows):
|
|
self.rows = rows
|
|
|
|
def all_summaries(self):
|
|
return list(self.rows)
|
|
|
|
|
|
class FakeMeta:
|
|
def __init__(self, m):
|
|
self.m = m
|
|
|
|
def peek(self, sid):
|
|
return self.m.get(sid) or {}
|
|
|
|
|
|
class TestBridge(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tc = TestClient(main.app)
|
|
|
|
def _env(self, td, caps=("conversations.read",)):
|
|
root = pathlib.Path(td)
|
|
src = root / "src"
|
|
src.mkdir()
|
|
(src / "plugin.json").write_text(json.dumps({**MANIFEST, "capabilities": list(caps)}))
|
|
store = PluginStore(root / "data")
|
|
store.install(OWNER_UID, str(src), is_owner=True, approve=True)
|
|
rows = [
|
|
("/a/old.jsonl", {"sessionId": "s1", "title": "One", "endedAt": _iso(30), "startedAt": _iso(31),
|
|
"userTurns": 2, "turnEnded": True}),
|
|
("/a/new.jsonl", {"sessionId": "s1", "title": "One", "endedAt": _iso(2), "startedAt": _iso(3),
|
|
"userTurns": 3, "turnEnded": True}),
|
|
("/a/cron.jsonl", {"sessionId": "s2", "endedAt": _iso(5), "userTurns": 1, "turnEnded": True}),
|
|
("/a/guest.jsonl", {"sessionId": "s3", "endedAt": _iso(5), "userTurns": 1}),
|
|
]
|
|
meta = {"s2": {"cron": {"job": "x"}, "test": True, "spawnedBy": {"sessionId": "p"}},
|
|
"s3": {"owner": "cel"}}
|
|
deps = main.app.state.ai
|
|
return [patch.object(deps, "plugin_store", store),
|
|
patch.object(deps, "store", FakeSummaries(rows)),
|
|
patch.object(deps, "meta_store", FakeMeta(meta))]
|
|
|
|
def test_rows_carry_the_flags_and_leave_guests_out(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
ps = self._env(td)
|
|
for p in ps:
|
|
p.start()
|
|
try:
|
|
tok = access.mint_handler(OWNER_UID, "cr", ttl=600)
|
|
r = self.tc.get("/proxy/tools/plugins/cr/hub/conversations?days=30&limit=1000",
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
rows = r.json()["conversations"]
|
|
self.assertNotIn("s3", {c["sessionId"] for c in rows})
|
|
cron = next(c for c in rows if c["sessionId"] == "s2")
|
|
self.assertTrue(cron["cron"] and cron["test"] and cron["spawnedBy"])
|
|
self.assertFalse(cron["agentRun"])
|
|
one = [c for c in rows if c["sessionId"] == "s1"]
|
|
self.assertEqual({c["userTurns"] for c in one}, {2, 3})
|
|
self.assertTrue(all(c["turnEnded"] and c["id"] for c in one))
|
|
finally:
|
|
for p in ps:
|
|
p.stop()
|
|
|
|
def test_one_conversation_reads_its_newest_transcript(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
ps = self._env(td)
|
|
for p in ps:
|
|
p.start()
|
|
seen = []
|
|
|
|
def answer(path):
|
|
seen.append(str(path))
|
|
return "Done. Left: deploy."
|
|
try:
|
|
tok = access.mint_handler(OWNER_UID, "cr", ttl=600)
|
|
with patch("plugins.proxyroutes._last_answer", answer):
|
|
r = self.tc.get("/proxy/tools/plugins/cr/hub/conversations/s1",
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(seen, ["/a/new.jsonl"])
|
|
self.assertEqual(r.json()["finalAnswer"], "Done. Left: deploy.")
|
|
self.assertEqual(r.json()["userTurns"], 3)
|
|
finally:
|
|
for p in ps:
|
|
p.stop()
|
|
|
|
def test_without_the_capability_it_is_refused(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
ps = self._env(td, caps=())
|
|
for p in ps:
|
|
p.start()
|
|
try:
|
|
tok = access.mint_handler(OWNER_UID, "cr", ttl=600)
|
|
r = self.tc.get("/proxy/tools/plugins/cr/hub/conversations",
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 403)
|
|
finally:
|
|
for p in ps:
|
|
p.stop()
|
|
|
|
def test_final_answer_skips_user_and_tool_items(self):
|
|
self.assertEqual(final_answer([
|
|
{"role": "assistant", "kind": "text", "text": "first"},
|
|
{"role": "user", "kind": "text", "text": "thanks"},
|
|
{"role": "assistant", "kind": "text", "text": " "},
|
|
]), "first")
|
|
self.assertEqual(final_answer([]), "")
|
|
|
|
|
|
class TestCarryOver(unittest.TestCase):
|
|
def test_leftovers_move_once(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = pathlib.Path(td)
|
|
legacy = root / "leftovers.json"
|
|
data = {"results": {"s1": {"score": 0.8, "lines": [{"i": 0, "text": "deploy", "p": 0.8}]}},
|
|
"scan": {"lastRunAt": "2026-11-25T05:30:00Z"}}
|
|
legacy.write_text(json.dumps(data))
|
|
store = PluginStore(root / "plugins")
|
|
self.assertTrue(carryover.leftovers(store, str(legacy)))
|
|
dst = store.user_data_dir(OWNER_UID, "left-to-do") / "results.json"
|
|
self.assertEqual(json.loads(dst.read_text()), data)
|
|
self.assertFalse(legacy.exists())
|
|
self.assertTrue((root / "leftovers.json.migrated").exists())
|
|
# a second start: nothing to do, the plugin's data untouched
|
|
dst.write_text(json.dumps({"results": {}, "scan": {}}))
|
|
self.assertFalse(carryover.leftovers(store, str(legacy)))
|
|
self.assertEqual(json.loads(dst.read_text())["results"], {})
|
|
|
|
def test_existing_plugin_data_wins(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = pathlib.Path(td)
|
|
legacy = root / "leftovers.json"
|
|
legacy.write_text(json.dumps({"results": {"old": {}}, "scan": {}}))
|
|
store = PluginStore(root / "plugins")
|
|
dst = store.user_data_dir(OWNER_UID, "left-to-do") / "results.json"
|
|
dst.write_text(json.dumps({"results": {"new": {}}, "scan": {}}))
|
|
self.assertTrue(carryover.leftovers(store, str(legacy)))
|
|
self.assertIn("new", json.loads(dst.read_text())["results"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|