Skip to content

The agent that grows with you

fix: auto-titles no longer drop reasoning-model JSON or store truncated fragments

teknium10b52e403473b
diff --git a/agent/title_generator.py b/agent/title_generator.py
index f03bf721caa..a8b728766c7 100644
--- a/agent/title_generator.py
+++ b/agent/title_generator.py
@@ -54,6 +54,9 @@ MAX_DERIVED_TITLE_CHARS = 48
# answer-shaped output guard in generate_title; port of can1357/oh-my-pi#7306). 12 leaves headroom for
# legitimate wordy titles while excluding full-sentence answers.
_MAX_TITLE_WORDS = 12
+# Output budget for the title call: room for a fenced/prefixed JSON reply and for a reasoning model that
+# thinks despite the thinking-disabled request, without letting a runaway reply burn minutes.
+TITLE_MAX_TOKENS = 512
# The example titles shown to the model in the prompt, and the echo-guard
# set: when the opening message carries little topical signal, a small model
@@ -223,14 +226,8 @@ def _first_line(text: str) -> str:
return next((ln.strip() for ln in text.splitlines() if ln.strip()), "")
-def _extract_title_text(content: str) -> str:
- """Strict JSON, then a loose JSON scan, then first-line prose (a provider ignoring ``response_format`` still titles)."""
- if not content:
- return ""
- raw = content.strip()
- fenced = re.match(r"^```(?:json)?\s*(.*?)\s*```$", raw, re.DOTALL)
- if fenced:
- raw = fenced.group(1).strip()
+def _extract_json_title(raw: str) -> Optional[str]:
+ """Title from a ``{"title": ...}`` payload — strict parse, then a loose ``"title": "..."`` scan; None when absent."""
try:
parsed = json.loads(raw)
if isinstance(parsed, dict) and isinstance(parsed.get("title"), str):
@@ -242,6 +239,33 @@ def _extract_title_text(content: str) -> str:
with suppress(ValueError):
return json.loads(f'"{match.group(1)}"').strip()
return match.group(1).strip()
+ return None
+
+
+def _is_truncated_structured_output(raw: str) -> bool:
+ """Structured output the token cap cut before its closing quote/brace/fence (``{"title``, a bare fence opener).
+
+ Checked only after the JSON paths failed, and on structure alone (a leading brace/bracket, an
+ unclosed fence) so quoted or *emphasized* prose titles are untouched (#83903)."""
+ return raw.count("```") % 2 == 1 or raw.startswith(("{", "["))
+
+
+def _extract_title_text(content: str) -> str:
+ """Strict JSON, then a loose JSON scan, then first-line prose (a provider ignoring ``response_format`` still titles).
+
+ A truncated structured payload is dropped rather than handed to the prose fallback: the fragment
+ would otherwise be persisted as the session title."""
+ if not content:
+ return ""
+ raw = content.strip()
+ fenced = re.match(r"^```(?:json)?\s*(.*?)\s*```$", raw, re.DOTALL)
+ if fenced:
+ raw = fenced.group(1).strip()
+ title = _extract_json_title(raw)
+ if title is not None:
+ return title
+ if _is_truncated_structured_output(raw):
+ return ""
# Prose fallback: scrub <think> blocks so reasoning can't leak into a title.
try:
from agent.agent_runtime_helpers import strip_think_blocks
@@ -251,6 +275,19 @@ def _extract_title_text(content: str) -> str:
return _strip_title_prefix(_first_line(raw)).strip("\"'").strip()
+def _title_from_reasoning(message: Any) -> str:
+ """The ``{"title": ...}`` payload when a reasoning model put it in ``reasoning_content`` / ``reasoning``
+ and left ``content`` empty (glm-5 / minimax under ``json_schema``, #82291). Structured extraction only:
+ chain-of-thought prose is never a title, so there is no prose fallback here."""
+ for field in ("reasoning_content", "reasoning"):
+ text = getattr(message, field, None)
+ if isinstance(text, str) and text.strip():
+ title = _extract_json_title(text.strip())
+ if title:
+ return title
+ return ""
+
+
def _clean_title(text: str) -> Optional[str]:
"""Normalize a model-produced title, or None when nothing usable remains."""
title = _strip_title_prefix(" ".join((text or "").split()).strip("\"'").strip()).rstrip(".!,;:")
@@ -328,8 +365,12 @@ def generate_title(
response = call_llm(
task="title_generation",
messages=[{"role": "system", "content": prompt}, {"role": "user", "content": user_snippet}],
- # A title is a handful of tokens; a larger ceiling let chatty models burn seconds.
- max_tokens=64, temperature=None, timeout=timeout, main_runtime=main_runtime,
+ # A title is a handful of tokens, but 64 was cut mid-JSON by fenced/prefixed replies and by
+ # reasoning models whose thinking survives the disable below (#83903, #82291). A model that
+ # honours the JSON contract stops after ~15 tokens regardless, so the ceiling only costs on
+ # replies that would have been garbage anyway. temperature=None: omitted from the wire so
+ # default-only reasoning models accept the first request (#72351).
+ max_tokens=TITLE_MAX_TOKENS, temperature=None, timeout=timeout, main_runtime=main_runtime,
extra_body={"response_format": _TITLE_RESPONSE_FORMAT},
# The module contract above promises thinking-disabled operation,
# but nothing enforced it: with the aux default reasoning_effort
@@ -339,7 +380,8 @@ def generate_title(
# ("```json") as the session title (#91927).
reasoning_config={"enabled": False},
)
- title = _clean_title(_extract_title_text(response.choices[0].message.content or ""))
+ message = response.choices[0].message
+ title = _clean_title(_extract_title_text(message.content or "") or _title_from_reasoning(message))
# Answer-shaped output guard: titling is a 3-7 word task, so a title with many words is a model that
# ignored the task and answered the user's message instead ("I don't have context on X — that's not
# something I recognize..."). Truncating would store half an assistant blob as the session title,
diff --git a/tests/agent/test_title_generator.py b/tests/agent/test_title_generator.py
index 8d94b3041df..5bcb6e68743 100644
--- a/tests/agent/test_title_generator.py
+++ b/tests/agent/test_title_generator.py
@@ -69,7 +69,48 @@ class TestGenerateTitle:
assert captured_kwargs.get("reasoning_config") == {"enabled": False}
+ @pytest.mark.parametrize(
+ ("content", "expected"),
+ [
+ # #83903: a token cap cutting the JSON mid-value or right after the fence opener must not
+ # persist the fragment; the derived title survives instead.
+ ('{"title":"Investigate and fix the login butt', None),
+ ("```json", None),
+ ('{"title"', None),
+ # Legit titles the structural check must keep: emphasized/quoted prose, non-Latin, numeric.
+ ("*Fix the login flow*", "*Fix the login flow*"),
+ ("修复登录按钮", "修复登录按钮"),
+ ("42", "42"),
+ ('```json\n{"title": "Fix login button"', "Fix login button"),
+ ],
+ )
+ def test_truncated_structured_output_never_becomes_the_title(self, content, expected):
+ mock_response = MagicMock()
+ mock_response.choices = [MagicMock()]
+ mock_response.choices[0].message.content = content
+ with patch("agent.title_generator.call_llm", return_value=mock_response):
+ assert generate_title("login is broken") == expected
+
+ def test_json_in_reasoning_content_is_used_but_reasoning_prose_is_not(self):
+ """#82291: glm-5/minimax under json_schema return content='' with the JSON in reasoning_content /
+ reasoning. That payload titles the session; chain-of-thought prose never does."""
+ def response(content, **reasoning):
+ resp = MagicMock(spec=["choices"])
+ resp.choices = [MagicMock(spec=["message"])]
+ resp.choices[0].message = MagicMock(spec=["content", *reasoning])
+ resp.choices[0].message.content = content
+ for k, v in reasoning.items():
+ setattr(resp.choices[0].message, k, v)
+ return resp
+ cases = [
+ (response("", reasoning_content='{"title": "Check FFmpeg on this machine"}'), "Check FFmpeg on this machine"),
+ (response(None, reasoning='{"title": "Check FFmpeg on this machine"}'), "Check FFmpeg on this machine"),
+ (response("", reasoning_content="The user wants ffmpeg checked. A short title would be"), None),
+ ]
+ for resp, expected in cases:
+ with patch("agent.title_generator.call_llm", return_value=resp):
+ assert generate_title("check ffmpeg") == expected
def test_strips_think_blocks(self):
"""Reasoning-model output wrapped in <think>...</think> must not