diff --git a/agent/title_generator.py b/agent/title_generator.py index bf3b7c7037..19e1b5584c 100644 --- a/agent/title_generator.py +++ b/agent/title_generator.py @@ -39,6 +39,29 @@ MAX_DERIVED_TITLE_CHARS = 48 # legitimate wordy titles while excluding full-sentence answers. _MAX_TITLE_WORDS = 12 +# 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 +# sometimes takes the cheapest schema-valid answer and parrots one of these +# back verbatim — most visibly "Fix login button on mobile" naming sessions +# that have nothing to do with a login button. The prompt's example lines are +# rendered from these constants so the guard set and the prompt cannot drift +# apart. Port of QwenLM/qwen-code#9709. +_PROMPT_GOOD_EXAMPLES = ( + "Fix login button on mobile", + "Postgres connection pool exhaustion", + "Friendly greeting", +) +_PROMPT_VAGUE_EXAMPLE = "Code changes" + +# "Friendly greeting" is deliberately NOT in the reject set: the prompt +# instructs the model to produce it for bare greetings, so it is a legitimate +# output, not an echo failure. The too-vague example is rejected too — a model +# repeating the counter-example says nothing about the session, and the +# derived title the guard falls back to is strictly more informative. +_EXAMPLE_ECHO_REJECT = frozenset( + t.lower() for t in _PROMPT_GOOD_EXAMPLES if t != "Friendly greeting" +) | {_PROMPT_VAGUE_EXAMPLE.lower()} + _TITLE_PROMPT_TEMPLATE = ( "You name chat sessions. Given the user's opening message, write a title " "that lets them find this conversation again in a list.\n\n" @@ -51,10 +74,8 @@ _TITLE_PROMPT_TEMPLATE = ( "- Never answer the message. Name it.\n" "- Always produce something, even for a bare greeting.\n" "__LANGUAGE_RULE__\n" - 'Good: {"title": "Fix login button on mobile"}\n' - 'Good: {"title": "Postgres connection pool exhaustion"}\n' - 'Good: {"title": "Friendly greeting"}\n' - 'Too vague: {"title": "Code changes"}\n' + + "".join(f'Good: {{"title": "{t}"}}\n' for t in _PROMPT_GOOD_EXAMPLES) + + f'Too vague: {{"title": "{_PROMPT_VAGUE_EXAMPLE}"}}\n' 'Too long: {"title": "Investigate and fix the issue where the login button ' 'does not respond on mobile devices"}\n\n' 'Reply with JSON only: {"title": "..."}' @@ -229,6 +250,18 @@ def _notify_title(title_callback: Optional[TitleCallback], title: str, source: s _safe_callback(title_callback, (title, source), "%s callback failed", label) +def _is_prompt_example_echo(title: str) -> bool: + """Return True when *title* is one of the prompt's own example titles. + + Comparison is case-insensitive after stripping any leading/trailing run of + non-letter/non-digit characters, so bracket/quote wrappers cannot bypass + the guard — while ``_clean_title`` keeps brackets for real titles like + "(WIP) Fix build". Unicode-aware so full-width wrappers are covered too. + """ + normalized = re.sub(r"^[\W_]+|[\W_]+$", "", title.strip(), flags=re.UNICODE).lower() + return normalized in _EXAMPLE_ECHO_REJECT + + def generate_title( user_message: str, timeout: Optional[float] = None, @@ -285,6 +318,17 @@ def generate_title( # Answer-shaped output: reject (not truncate) so the caller retries next exchange. logger.debug("Rejecting answer-shaped title output (%d words > %d)", len(title.split()), _MAX_TITLE_WORDS) return None + # Example-echo guard: a title that parrots one of the prompt's own + # examples back verbatim says nothing about the session — reject it so + # the instant derived title (a slice of the user's actual words) + # survives instead. Exact match after wrapper-stripping, deliberately + # not fuzzy, so a genuinely topical title that merely resembles an + # example still passes. Wrappers are stripped for the comparison only + # ("(Fix login button on mobile)" is the same canned echo as the bare + # example). Port of QwenLM/qwen-code#9709. + if title is not None and _is_prompt_example_echo(title): + logger.debug("Rejecting prompt-example echo title: %r", title) + return None return title except Exception as e: # WARNING so it shows in agent.log without debug mode; stack at debug. diff --git a/tests/agent/test_title_generator.py b/tests/agent/test_title_generator.py index 20ab253079..ff0d97b633 100644 --- a/tests/agent/test_title_generator.py +++ b/tests/agent/test_title_generator.py @@ -150,6 +150,61 @@ class TestGenerateTitle: with patch("agent.title_generator.call_llm", return_value=mock_response): assert generate_title("question", "answer") == "Investigate the title resolver bug" + @pytest.mark.parametrize("echo", [ + "Fix login button on mobile", + "fix login button on mobile", + '"Fix login button on mobile"', + "(Fix login button on mobile)", + "[Fix login button on mobile]", + "Postgres connection pool exhaustion", + "Code changes", + ]) + def test_rejects_prompt_example_echo(self, echo): + """A model that parrots one of the prompt's own example titles back + must be rejected — a canned example says nothing about the session. + Port of QwenLM/qwen-code#9709 (their #9706 bug class).""" + mock_response = MagicMock() + mock_response.choices = [MagicMock()] + mock_response.choices[0].message.content = echo + + with patch("agent.title_generator.call_llm", return_value=mock_response): + assert generate_title("help me with something unrelated") is None + + def test_friendly_greeting_example_is_allowed(self): + """'Friendly greeting' is prescribed output for bare greetings, not an + echo failure — it must pass the guard.""" + mock_response = MagicMock() + mock_response.choices = [MagicMock()] + mock_response.choices[0].message.content = "Friendly greeting" + + with patch("agent.title_generator.call_llm", return_value=mock_response): + assert generate_title("hey there!") == "Friendly greeting" + + def test_prompt_examples_render_from_guard_constants(self): + """The prompt's example lines are rendered from the same constants the + guard checks, so the two cannot drift apart.""" + from agent.title_generator import ( + _PROMPT_GOOD_EXAMPLES, + _PROMPT_VAGUE_EXAMPLE, + _TITLE_PROMPT_TEMPLATE, + ) + + for example in _PROMPT_GOOD_EXAMPLES: + assert f'Good: {{"title": "{example}"}}' in _TITLE_PROMPT_TEMPLATE + assert f'Too vague: {{"title": "{_PROMPT_VAGUE_EXAMPLE}"}}' in _TITLE_PROMPT_TEMPLATE + + def test_topical_title_resembling_example_passes(self): + """The guard is exact-match only: a genuinely topical title that merely + resembles an example must not be rejected.""" + mock_response = MagicMock() + mock_response.choices = [MagicMock()] + mock_response.choices[0].message.content = "Fix login button on desktop" + + with patch("agent.title_generator.call_llm", return_value=mock_response): + assert generate_title("the login button is broken on desktop") == ( + "Fix login button on desktop" + ) + def test_invokes_failure_callback_on_exception(self):