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>
158 lines
6.8 KiB
Python
158 lines
6.8 KiB
Python
"""A block too long to ship whole (records._clip, ParserState._set_clipped,
|
|
/api/conversation-full-text): the part shown is cut on a clean markdown
|
|
boundary with no marker in it, the item says it was cut (`clipped`,
|
|
`clipId`), and *Show more* gets the whole text back.
|
|
|
|
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",
|
|
"SCHEDULED_PATH": TMP / "scheduled.json",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import conversations # noqa: E402
|
|
import main # noqa: E402
|
|
from conversations.parse.records import MAX_BLOCK, _clip # noqa: E402
|
|
|
|
SID = "11111111-2222-4333-8444-aaaaaaaaaaaa"
|
|
REL = f"-home-x/{SID}.jsonl"
|
|
|
|
TABLE = "| file | what |\n|---|---|\n" + "".join(
|
|
f"| src/mod{i}.py | {'changes the thing ' * 3}|\n" for i in range(160))
|
|
ANSWER = "Here is the summary.\n\n" + "Some context. " * 300 + "\n\n" + TABLE + "\nThat's all."
|
|
PROMPT = "short prompt"
|
|
LOG = "".join(f"line {i}: {'x' * 50}\n" for i in range(400))
|
|
|
|
|
|
def _rec(kind, uuid, content, t):
|
|
return {"type": kind, "uuid": uuid, "sessionId": SID, "timestamp": f"2026-11-25T10:00:0{t}Z",
|
|
"message": {"role": kind, "content": content,
|
|
**({"model": "claude-opus-5-5"} if kind == "assistant" else {})}}
|
|
|
|
|
|
def write_transcript() -> pathlib.Path:
|
|
p = TMP / "arch" / REL
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
recs = [
|
|
_rec("user", "u1", PROMPT, 0),
|
|
_rec("assistant", "a1", [{"type": "tool_use", "id": "toolu_1", "name": "Bash",
|
|
"input": {"command": "cat build.log"}}], 1),
|
|
_rec("user", "u2", [{"type": "tool_result", "tool_use_id": "toolu_1", "content": LOG}], 2),
|
|
_rec("assistant", "a2", [{"type": "text", "text": ANSWER}], 3),
|
|
]
|
|
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
|
|
return p
|
|
|
|
|
|
class Clip(unittest.TestCase):
|
|
def test_short_text_is_untouched(self):
|
|
self.assertEqual(_clip("hello"), "hello")
|
|
self.assertIsNone(_clip(None))
|
|
|
|
def test_no_marker_and_never_mid_table_row(self):
|
|
out = _clip(ANSWER)
|
|
self.assertLessEqual(len(out), MAX_BLOCK)
|
|
self.assertNotIn("truncated", out)
|
|
self.assertTrue(ANSWER.startswith(out))
|
|
last = out.splitlines()[-1]
|
|
# Between two whole rows: the last line kept is a complete table row.
|
|
self.assertTrue(last.startswith("| src/mod") and last.endswith("|"), last)
|
|
|
|
def test_never_between_header_and_rule(self):
|
|
# The cap falls right after a table's header row.
|
|
text = "p " * 3990 + "\n| h1 | h2 |\n|---|---|\n| a | b |\n" + "z" * 9000
|
|
out = _clip(text)
|
|
self.assertFalse(out.rstrip().endswith("| h1 | h2 |"), out[-40:])
|
|
|
|
def test_a_code_block_cut_inside_is_closed(self):
|
|
text = "intro\n\n```py\n" + "".join(f"v{i} = {'y' * 30}\n" for i in range(400)) + "```\nend"
|
|
out = _clip(text)
|
|
self.assertLessEqual(len(out), MAX_BLOCK + 4)
|
|
self.assertTrue(out.endswith("\n```"), out[-20:])
|
|
self.assertEqual(out.count("```") % 2, 0)
|
|
|
|
def test_a_paragraph_break_near_the_cap_wins(self):
|
|
text = "a\n" * 3200 + "\n" + "b " * 700 + "\n\n" + "c " * 5000
|
|
out = _clip(text)
|
|
self.assertTrue(out.endswith("b"), out[-10:])
|
|
|
|
def test_plain_output_is_cut_at_a_line_end(self):
|
|
out = _clip(LOG, markdown=False)
|
|
self.assertTrue(LOG.startswith(out + "\n"))
|
|
self.assertLessEqual(len(out), MAX_BLOCK)
|
|
|
|
def test_one_huge_line_is_cut_at_the_cap(self):
|
|
self.assertEqual(len(_clip("a" * 20000)), MAX_BLOCK)
|
|
|
|
|
|
class Parser(unittest.TestCase):
|
|
def test_items_carry_clipped_and_the_state_keeps_the_rest(self):
|
|
p = write_transcript()
|
|
st = conversations.ParserState(p, full=True)
|
|
conversations.feed_lines(st, p, 0)
|
|
thread = st.summary()["thread"]
|
|
user = next(it for it in thread if it["role"] == "user" and it["kind"] == "text")
|
|
self.assertNotIn("clipped", user)
|
|
self.assertNotIn("clipId", user)
|
|
tool = next(it for it in thread if it["kind"] == "tool_use")
|
|
msg = next(it for it in thread if it["role"] == "assistant" and it["kind"] == "text")
|
|
self.assertEqual(tool["clipped"], {"result": len(LOG)})
|
|
self.assertEqual(msg["clipped"], {"text": len(ANSWER)})
|
|
# Ids in transcript order, the same on a fresh parse.
|
|
self.assertEqual((tool["clipId"], msg["clipId"]), (0, 1))
|
|
self.assertEqual(st.clip_fields(1), {"text": ANSWER})
|
|
self.assertEqual(st.clip_fields(0), {"result": LOG})
|
|
self.assertIsNone(st.clip_fields(2))
|
|
self.assertEqual(st.full_field(msg, "text"), ANSWER)
|
|
self.assertEqual(st.last_answer(), ANSWER.strip()) # a run's answer, whole
|
|
again = conversations.parse_conversation(p, full=True)["thread"]
|
|
self.assertEqual([it.get("clipId") for it in again], [it.get("clipId") for it in thread])
|
|
|
|
def test_the_cheap_parse_clips_nothing(self):
|
|
p = write_transcript()
|
|
st = conversations.ParserState(p, full=False)
|
|
conversations.feed_lines(st, p, 0)
|
|
self.assertEqual(st.clip_fields(0), None)
|
|
|
|
|
|
class Route(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
write_transcript()
|
|
cls.c = TestClient(main.app, headers={"X-Internal-Auth": "tok"})
|
|
|
|
def test_full_text(self):
|
|
d = self.c.get("/api/conversation", params={"id": REL}).json()
|
|
msg = next(it for it in d["thread"] if it.get("clipped", {}).get("text"))
|
|
r = self.c.get("/api/conversation-full-text", params={"id": REL, "clip": msg["clipId"]})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), {"clipId": msg["clipId"], "fields": {"text": ANSWER}})
|
|
|
|
def test_unknown_clip_is_404(self):
|
|
r = self.c.get("/api/conversation-full-text", params={"id": REL, "clip": 99})
|
|
self.assertEqual(r.status_code, 404)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|