Files
gabrielvidalandClaude Opus 5.5 86882300a1 feat(conversations): clip long blocks on a clean markdown boundary and serve the rest
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>
2026-11-25 17:29:57 +01:00

205 lines
7.5 KiB
Python

"""Reading a transcript: its JSONL records (a whole file, or the bytes
appended since an offset), the timestamp helpers every pass uses, and the
thread-item basics (clipped text blocks, ``_item``)."""
import datetime
import json
import pathlib
import re
from typing import TYPE_CHECKING
if TYPE_CHECKING: # feed_lines' annotation only
from .state import ParserState
def _ms(iso: str | None) -> float | None:
"""Epoch milliseconds for a transcript ISO timestamp, or None."""
if not iso:
return None
try:
return datetime.datetime.fromisoformat(
iso.replace("Z", "+00:00")).timestamp() * 1000
except ValueError:
return None
#: Width of one activity bin, in minutes (the activity dashboard's histogram
#: resolution). Bins are absolute — indexed from the Unix epoch in UTC — so a
#: bin index is timezone-free and only the *reader* maps it to a local slot.
BIN_MINUTES = 5
_BIN_MS = BIN_MINUTES * 60 * 1000
def _bin5(iso: str | None) -> int | None:
"""The 5-minute bin index (epoch-based, UTC) a transcript timestamp lands in."""
ms = _ms(iso)
return None if ms is None else int(ms // _BIN_MS)
def _elapsed_ms(start: str | None, end: str | None) -> int | None:
"""Wall-clock milliseconds between two transcript timestamps."""
a, b = _ms(start), _ms(end)
if a is None or b is None or b < a:
return None
return int(b - a)
MAX_BLOCK = 8000 # cap a single text/result block so payloads stay bounded
def _block_text(content) -> str:
"""Flatten a tool_result / message content into text."""
if content is None:
return ""
if isinstance(content, str):
return content
parts = []
if isinstance(content, list):
for b in content:
if isinstance(b, dict):
if b.get("type") == "text":
parts.append(b.get("text", ""))
elif b.get("type") == "image":
parts.append("[image]")
elif b.get("type") == "tool_reference":
# ToolSearch results are tool_reference blocks; keep one
# parseable line per match for the ToolSearch widget.
parts.append(f"tool_reference: {b.get('tool_name', '')}")
elif "text" in b:
parts.append(str(b["text"]))
else:
parts.append(str(b))
return "\n".join(parts)
# An opening / closing code fence: up to 3 spaces, then ``` or ~~~ (3 or more).
_FENCE_RE = re.compile(r" {0,3}(`{3,}|~{3,})")
# A table's delimiter row (`|---|:--:|`): the line above it is the header,
# which on its own renders as a plain paragraph — never cut between the two.
_TABLE_RULE_RE = re.compile(r" {0,3}\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$")
def _clip(s: str, markdown: bool = True, limit: int = MAX_BLOCK) -> str:
"""At most ``limit`` chars of ``s`` — the first part of a block too big to
ship whole. The item says it was cut (``clipped``) and the viewer's *Show
more* fetches the rest (``ParserState.clip_fields``), so no marker goes
into the text.
The cut lands on a clean boundary, so the part shown still renders: a
blank line outside any code fence in the last quarter (a table or a list
kept whole), else a line end outside a fence (between two table rows at
worst, never between a table's header and its rule), else a line end
inside the fence — closed again for the markdown renderer — and only a
single line longer than half the cap is cut mid-line. Plain text
(``markdown=False``: tool output) is cut at the last line end."""
if not s or len(s) <= limit:
return s
floor = limit // 2
if not markdown:
nl = s.rfind("\n", 0, limit)
return s[:nl] if nl >= floor else s[:limit]
para = line = inside = 0
before = 0 # the line cut before the last line
fence: str | None = None # the open fence's marker (``` / ~~~~)
inside_fence: str | None = None # …as it was at the `inside` cut
pos = 0
while True:
nl = s.find("\n", pos, limit)
if nl == -1:
break
ln = s[pos:nl]
m = _FENCE_RE.match(ln)
prev = line
if fence is None:
if m:
fence = m.group(1)
elif not ln.strip():
para = nl
elif _TABLE_RULE_RE.match(ln) and "-" in ln:
prev = line = before # not after the header row either
elif m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) \
and not ln[m.end():].strip():
fence = None
para = nl # right after a closing fence
if fence is None:
before, line = prev, nl
else:
inside, inside_fence = nl, fence
pos = nl + 1
if fence is None and line == pos - 1:
# The line the cap fell in may be the rule under the last line kept.
end = s.find("\n", pos)
nxt = s[pos:end if end != -1 else len(s)]
if _TABLE_RULE_RE.match(nxt) and "-" in nxt:
line = before
for cut, at_least in ((para, limit * 3 // 4), (line, floor), (para, floor)):
if cut >= at_least:
return s[:cut].rstrip()
if inside >= floor and inside_fence:
return s[:inside].rstrip() + "\n" + inside_fence
out = s[:limit]
return out + "\n" + fence if fence else out
# Per-message cap for the full-text search index. Search + snippet only need the
# meat of a message, and this text ships to the client (Fuse.js indexes it), so
# we bound each message to keep the search payload reasonable.
SEARCH_CLIP = 1000
def _search_clip(s: str) -> str:
s = " ".join((s or "").split()) # collapse whitespace/newlines for snippets
return s[:SEARCH_CLIP] if len(s) > SEARCH_CLIP else s
def _iter_records(path: pathlib.Path):
try:
with path.open(encoding="utf-8", errors="ignore") as fh:
for line in fh:
line = line.strip()
if not line or line[0] != "{":
continue
try:
yield json.loads(line)
except ValueError:
continue
except OSError:
return
def feed_lines(state: "ParserState", path: pathlib.Path, offset: int) -> int | None:
"""Feed the complete JSONL lines from ``offset`` to EOF into ``state``.
Returns the offset of the next unread byte — a trailing partial line (a
record still being written) is left for the next pass. ``None`` on read
errors. Mirrors ``_iter_records`` semantics, so a state fed this way from
offset 0 equals ``parse_conversation``. Shared by the indexer (summaries)
and the detail route (full threads): a live transcript only ever grows by
append, so neither re-reads the file on every tick."""
try:
with path.open("rb") as fh:
fh.seek(offset)
buf = fh.read()
except OSError:
return None
end = buf.rfind(b"\n")
if end == -1:
return offset # no complete new line yet
for raw in buf[:end].split(b"\n"):
line = raw.decode("utf-8", "ignore").strip()
if not line or line[0] != "{":
continue
try:
state.feed(json.loads(line))
except ValueError:
continue
return offset + end + 1
def _item(role, kind, first, out_tokens, **rest) -> dict:
it = {"role": role, "kind": kind,
**{k: v for k, v in rest.items() if v is not None}}
if first and out_tokens:
it["out"] = out_tokens # output tokens for this assistant API call
return it