Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): make pane titles clear at a glance
Ruben Lütke820959b7d8a2
diff --git a/jarvis/agentic_ide/recap.py b/jarvis/agentic_ide/recap.pyindex 6e588d4680..103e57e6df 100644--- a/jarvis/agentic_ide/recap.py+++ b/jarvis/agentic_ide/recap.py@@ -52,10 +52,13 @@ if TYPE_CHECKING: # pragma: no cover - typing only# status bar and a blank frame row, small enough that the scan is free.TAIL_LINES = 14-# The header label is truncated by CSS anyway; this is the transport cap, so a-# pane that printed a 3,000-character JSON blob cannot push that through the-# state payload of every poll.-HEADLINE_CHARS = 120+# The header has room for roughly one short navigation label once the pane's+# call-sign and controls have taken their share. The old 120-character cap+# delegated the real limit to CSS, which routinely hid the words that finally+# identified the user's goal. Forty-eight characters keeps the WHOLE label in+# a normal pane and forces both the model and the deterministic floor to put the+# differentiating subject first.+HEADLINE_CHARS = 48# The long form is read in a card that wraps and scrolls, not in a one-line# tooltip — so the cap is here to bound the payload, not to make the text fit.# It used to be 280, which cut the second sentence off mid-word in exactly the@@ -64,10 +67,10 @@ DETAIL_CHARS = 480# How much of the instruction is quoted in the long form. A prompt is often a# whole brief; this is the part of it that identifies the task.TASK_CHARS = 200-# The same job in the header, where it shares a few centimetres with the pane's-# call-sign and its buttons. Shorter on purpose: past this the CSS clip lands-# before the character cap does, and two ellipses is one more than anyone needs.-HEADLINE_TASK_CHARS = 96+# The same job in the header. It shares the exact cap: a fallback must not be+# allowed to overflow merely because its source was an instruction rather than+# a transcript row.+HEADLINE_TASK_CHARS = HEADLINE_CHARS# Glyphs an agent TUI draws in front of its input line. A row starting with one# is the prompt box, not something the agent did.@@ -114,6 +117,7 @@ def _chrome_fragments() -> tuple[str, ...]:extra = ()return (*_CHROME_FRAGMENTS, *extra)+# Leading decoration a TUI puts in front of a real line: bullets, tree glyphs,# check marks, spinner frames. Stripped so the recap starts on a word. The# allowed openers are kept out of the class deliberately — a path, a quote or an@@ -128,6 +132,13 @@ _MARKUP_RE = re.compile(r"^\s{0,3}(?:#{1,6}\s+|[-*+]\s+|\d{1,2}[.)]\s+|>\s+)")# no markdown at all._EMPHASIS_RE = re.compile(r"[*_`]{1,3}")+# A raw path list is a frequent last readable row after a search command. It+# contains plenty of letters, so the older "three alphabetic characters" rule+# accepted it as work and headers ended up reading `jarvis/core/bus.py",+# "jarvis/memory`. A path can be useful after a verb ("Wrote src/app.py"), but+# paths on their own name implementation debris, not the user's task.+_PATH_PART_RE = re.compile(r"[\\/]")+# Section labels a brief is structured with. On their own they name the FORM of# the document, not the work, so the job is on the line after them — and where# one prefixes the sentence ("Task: fix the login test") the sentence is the@@ -203,13 +214,26 @@ def condense(text: str, limit: int) -> str:cleaned = " ".join(str(text or "").split())if len(cleaned) <= limit:return cleaned- cut = cleaned[:limit]+ # The ellipsis belongs INSIDE the advertised budget. Returning `limit + 1`+ # made every caller's cap slightly dishonest, and this cap now corresponds+ # to actual pixels in the pane header rather than only a transport guard.+ cut = cleaned[: max(1, limit - 1)]spaced = cut.rsplit(" ", 1)[0]# A single very long token (a path, a hash) has no space to cut at — take# the hard cut rather than returning nothing.return f"{spaced or cut}…"+def _bare_path_list(text: str) -> bool:+ """Whether ``text`` is only one or more filesystem-looking tokens."""+ tokens = [+ token.strip("\"'()[]{}<>,:;")+ for token in re.split(r"\s+", text.strip())+ if token.strip("\"'()[]{}<>,:;")+ ]+ return bool(tokens) and all(_PATH_PART_RE.search(token) for token in tokens)++def _informative(line: str) -> bool:"""True for a transcript row that says something about the work."""text = line.strip()@@ -218,6 +242,8 @@ def _informative(line: str) -> bool:lowered = text.lower()if any(fragment in lowered for fragment in _chrome_fragments()):return False+ if _bare_path_list(text):+ return False# A row of numbers, punctuation or box residue is not a sentence.return sum(1 for ch in text if ch.isalpha()) >= 3@@ -323,7 +349,7 @@ def summarize(term: Any, *, tail: Sequence[str] | None = None) -> Recap:problem = condense(getattr(term, "error", ""), HEADLINE_CHARS)problem = problem or "it could not be started"return Recap(- headline=f"Not running — {problem}",+ headline=condense(f"Not running — {problem}", HEADLINE_CHARS),detail=_sentences(f"This pane is not running: {problem}.",asked,@@ -332,7 +358,7 @@ def summarize(term: Any, *, tail: Sequence[str] | None = None) -> Recap:if status == "pending":return Recap(- headline="Not started yet — connect to it to start its agent.",+ headline="Not started — waiting for terminal connection",detail=_sentences("This pane has no agent running yet; it starts as soon as the terminal connects.",asked if task else "",@@ -370,10 +396,12 @@ def summarize(term: Any, *, tail: Sequence[str] | None = None) -> Recap:elif activity:headline = activityelse:- headline = "Running — nothing printed yet."+ headline = "Running — no work visible yet"- now = f"Working now, last output {idle}: {activity}." if idle and activity else (- f"Working now: {activity}." if activity else "Running, with nothing printed yet."+ now = (+ f"Working now, last output {idle}: {activity}."+ if idle and activity+ else (f"Working now: {activity}." if activity else "Running, with nothing printed yet."))return Recap(headline=condense(headline, HEADLINE_CHARS),diff --git a/jarvis/agentic_ide/recap_engine.py b/jarvis/agentic_ide/recap_engine.pyindex dae40d0918..baab1c2960 100644--- a/jarvis/agentic_ide/recap_engine.py+++ b/jarvis/agentic_ide/recap_engine.py@@ -53,7 +53,7 @@ from __future__ import annotationsimport asyncioimport reimport time-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom typing import TYPE_CHECKING, Anyfrom loguru import logger@@ -84,11 +84,18 @@ MIN_LINES_TO_SUMMARIZE = 8#: simply wait for the next poll, five seconds later.MAX_CONCURRENT = 2-#: How much of the pane is handed to the model, newest rows last. Enough to-#: cover the arc of a task (what was asked, what was tried, where it ended) and-#: far short of the whole 600-row scrollback.-INPUT_LINES = 180+#: How much of the pane is handed to the model. The original version kept only+#: the newest rows. That preserves implementation activity but drops the+#: user's request at the top of a directly driven CLI session — exactly how an+#: outcome such as "make the workspace setup feel simple" became the process+#: report "consolidating the workspace launcher". Keep both bookends within+#: the same total budget: the beginning identifies WHY; the end says WHERE IT+#: STANDS. The noisy middle is the least valuable part of a glance label.+INPUT_HEAD_LINES = 48+INPUT_TAIL_LINES = 132INPUT_CHARS = 9_000+INPUT_HEAD_CHARS = 2_400+INPUT_TAIL_CHARS = INPUT_CHARS - INPUT_HEAD_CHARS#: How long one summary may take before the pane keeps its previous recap. A#: recap nobody is waiting for does not deserve a long leash.@@ -101,12 +108,28 @@ CALL_TIMEOUT_S = 30.0FAILURES_BEFORE_QUIET = 3QUIET_S = 600.0-#: Transport caps. The header is clipped by the pane's width anyway; the long-#: form is read in a card that wraps and scrolls, so its cap only has to bound-#: the payload. It used to be 420 and cut the last sentence off mid-word.-HEADLINE_CHARS = 120+#: This is a DISPLAY budget, not merely a transport cap. In a normal grid the+#: call-sign and pane actions leave room for about 48 characters; a 90-character+#: model instruction merely guaranteed that CSS would hide the distinguishing+#: half. Keep this in parity with the deterministic floor in :mod:`.recap`.+HEADLINE_CHARS = recap.HEADLINE_CHARSDETAIL_CHARS = 640+#: A provider whose output budget was consumed by internal reasoning has been+#: observed returning ``DETAIL: The``. Showing that fragment in the expanded+#: card is worse than repeating the useful headline, so a detail needs enough+#: substance to stand on its own.+MIN_DETAIL_CHARS = 24+MIN_DETAIL_WORDS = 5++#: Thinking-mandatory models consume their private reasoning from the same+#: output budget. Most live panes still produced a complete title inside 400+#: tokens; the two that did not were obvious invalid fragments. Start there,+#: then spend 800 only on an invalid answer. This preserves title quality+#: without doubling every background recap's cost.+MODEL_OUTPUT_TOKENS = 400+MODEL_RETRY_OUTPUT_TOKENS = 800+#: What the user may type into a recap of their own. The same two lengths, with#: room to spare — a hand-written recap is checked here rather than silently#: shortened, so nobody writes three sentences and gets one and a half back.@@ -141,6 +164,9 @@ NO_PROVIDER_NOTE = "No model is reachable to summarize this pane."#: providers put the API key in the request URL, and this string is rendered in#: the recap card — where a screenshot would carry it straight out of the app._SECRET_RE = re.compile(r"(?i)(key|token|secret|password|authorization)=[^\s&\"']+")+_TITLE_WORD_RE = re.compile(r"\b[^\W\d_][\w'-]*\b", flags=re.UNICODE)+_SHELL_FRAGMENT_RE = re.compile(r"(?:^|\s)--?[a-zA-Z]\w*|[*?][./\\\w]")+_DETAIL_SENTENCE_END_RE = re.compile(r"[.!?](?=\s|$)")# Which language the sentence is written in. Interface languages, so this table# carries every locale [ui].language accepts and falls back to English for a@@ -154,9 +180,9 @@ _LANGUAGE_NAMES = {"en": "English", "de": "German", "es": "Spanish"}# screen is mostly its own interface, and a summary that quotes the status bar# is the failure this module was built to replace._SYSTEM = """\-You write the status line for one terminal pane in a multi-agent coding \-workspace. The user is glancing across a grid of panes and needs to know, \-without reading any of them, what THIS pane has been doing and where it stands.+You write a navigation label and recap for one terminal pane in a multi-agent \+coding workspace. The user is glancing across a grid and must recognize the \+ORIGINAL USER GOAL of this pane immediately, without reading its terminal.You are given the instruction the pane was last sent and a readable replay of \its terminal screen. That screen belongs to a coding CLI, so it also contains \@@ -164,30 +190,48 @@ the CLI's own interface — banners, menus, spinners, key hints, a token \counter, and the text on its input line, which is what the USER typed. Read \past all of that to the work itself.-Answer with exactly two lines and nothing else:+Answer with exactly two physical lines and nothing else:-HEADLINE: <at most 90 characters, and a COMPLETE thought inside that budget — \-this line is clipped by the pane's width, so front-load the part that \-identifies the work and never let it run past 90 into an ellipsis. What this \-pane is doing or has achieved, as a plain statement. No pane name, no agent \-name, no quotation marks, no trailing period.>-DETAIL: <three or four full sentences, and the place where the actual answer \-lives: what the goal was, what has been done so far, where the work stands \-now, and what is outstanding or what the next step is. Finish every sentence \-you start.>+HEADLINE: <3-7 words, HARD MAXIMUM 48 characters. A self-contained navigation \+label for the user's problem or desired outcome, normally "subject — result". \+Put the unique subject first and a concrete result, blocker, or completion \+state second. No pane name, agent name, quotation marks, or trailing period.>+DETAIL: <exactly two complete sentences on this same physical line. State the \+original goal first, then what has been achieved, what is blocked, or the next \+step. Finish both sentences.>Rules:-- Be concrete. "Working on the code" is worthless. Name the files, commands, \-errors, findings and decisions that are actually on the screen.+- The headline answers "Which user problem or outcome is this pane for?", not \+"Which generic engineering activity is happening?" Use the user's vocabulary \+when the original request is visible; otherwise infer the outcome cautiously \+from the work.+- Do not start the headline with process narration such as "Investigating", \+"Implementing", "Working on", "Fixing", "Analyzing", "Reviewing", or an \+equivalent phrase in the requested language. Those verbs spend the visible \+space before identifying the task.+- Keep file paths, class names, commands and implementation mechanisms OUT of \+the headline. Put useful technical evidence in DETAIL instead.+- Be concrete in DETAIL. "Working on the code" is worthless. Name supported \+errors, findings, decisions and results there.- If the pane is waiting for the user — a permission prompt, a question, a \-choice between options — say that first in both lines. It is the one thing \-the user has to act on.+choice between options — lead with "Needs input" (translated) in both lines. \+It is the one thing the user has to act on.- Never quote the CLI's status bar, key hints, token or context counter, \spinner text, or the contents of its input line.- Say only what the screen supports. If it shows no real work yet, say that \plainly instead of inventing some.- Report, do not address the user, and do not offer help. No preamble, no \-markdown, no bullet points, no code fences.\+markdown, no bullet points, no code fences.++Headline examples (poor -> useful):+- "Consolidating the workspace launcher into a single screen" -> \+"Workspace setup — one clear screen"+- "Fixing three bugs in the terminal notification system" -> \+"Terminal alerts — 3 reliability fixes"+- "Implementing terminal tab renaming based on workspace renaming" -> \+"Terminal tabs — rename without restart"+- "Investigating terminal pane geometry and whitespace" -> \+"Terminal panes — reclaim wasted space"\"""@@ -446,8 +490,7 @@ async def _run(term: Any, key: str, rows: list[str], folder: str) -> None:if entry.failures >= FAILURES_BEFORE_QUIET:entry.quiet_until = time.time() + QUIET_Slogger.info(- "Agentic IDE recap: {} failed {}x ({}) — deterministic recaps for "- "the next {:.0f}s",+ "Agentic IDE recap: {} failed {}x ({}) — deterministic recaps for the next {:.0f}s",key,entry.failures,type(exc).__name__,@@ -516,30 +559,85 @@ def _resolve_brain(): # noqa: ANN202 - Brain | None, avoids an import cyclereturn None-def build_prompt(term: Any, rows: Sequence[str], *, folder: str = "") -> str:- """What the summarizer is shown: the brief, the pane, and its screen.+def _bounded_rows(+ rows: Sequence[str], *, max_lines: int, max_chars: int, newest: bool = False+) -> list[str]:+ """One end of a transcript, bounded without dropping its nearest row.- Public because it is the part worth asserting on — the tests pin that the- instruction and the newest rows survive the budget, and that the oldest rows- are what gets dropped when they do not.+ ``newest`` walks backwards so the very latest row survives when that end is+ wider than its character allowance, then restores chronological order for+ the model. A single pathological JSON row is clipped rather than allowed+ to make the whole section empty."""- tail: list[str] = []+ source = list(rows)+ picked: list[str] = []used = 0- for line in reversed(list(rows)[-INPUT_LINES:]):- used += len(line) + 1- if used > INPUT_CHARS:+ iterable = reversed(source[-max_lines:]) if newest else iter(source[:max_lines])+ for raw in iterable:+ line = str(raw)+ remaining = max_chars - used+ if remaining <= 1:break- tail.append(line)- tail.reverse()+ cost = len(line) + 1+ if cost > remaining:+ if not picked:+ picked.append(f"{line[: max(1, remaining - 1)]}…")+ break+ picked.append(line)+ used += cost+ if newest:+ picked.reverse()+ return picked+++def _screen_sections(rows: Sequence[str]) -> list[str]:+ """The transcript bookends that carry user intent and current state."""+ source = list(rows)+ total_chars = sum(len(str(line)) + 1 for line in source)+ total_lines = INPUT_HEAD_LINES + INPUT_TAIL_LINES+ if len(source) <= total_lines and total_chars <= INPUT_CHARS:+ return ["Its terminal transcript, oldest row first:\n<<<\n" + "\n".join(source) + "\n>>>"]++ head = _bounded_rows(+ source,+ max_lines=INPUT_HEAD_LINES,+ max_chars=INPUT_HEAD_CHARS,+ )+ # Never repeat rows from a short but extremely wide transcript in both+ # sections. The line boundary is enough: character clipping happens only+ # inside the chosen edge row.+ tail_source = source[min(INPUT_HEAD_LINES, len(source)) :]+ tail = _bounded_rows(+ tail_source,+ max_lines=INPUT_TAIL_LINES,+ max_chars=INPUT_TAIL_CHARS,+ newest=True,+ )+ sections = [+ "The beginning of its terminal transcript, where the original user "+ "request often appears:\n<<<\n" + "\n".join(head) + "\n>>>"+ ]+ if tail:+ sections.append(+ "The newest part of its terminal transcript, after less useful "+ "middle rows were omitted:\n<<<\n" + "\n".join(tail) + "\n>>>"+ )+ return sections+++def build_prompt(term: Any, rows: Sequence[str], *, folder: str = "") -> str:+ """What the summarizer is shown: the brief, the pane, and its screen.+ Public because it is the part worth asserting on — the tests pin that the+ instruction and both transcript bookends survive the budget, and that the+ less useful middle is what gets dropped when they do not.+ """instruction = str(getattr(term, "last_prompt", "") or "").strip()if len(instruction) > 1_500:instruction = f"{instruction[:1_500]}…"status = str(getattr(term, "status", "") or "pending")- header = [- f"Coding CLI: {getattr(term, 'display_name', '') or getattr(term, 'agent', '') or 'unknown'}",- f"Pane status: {status}",- ]+ cli = getattr(term, "display_name", "") or getattr(term, "agent", "") or "unknown"+ header = [f"Coding CLI: {cli}", f"Pane status: {status}"]if folder:header.append(f"Working folder: {folder}")idle = recap.idle_phrase(term)@@ -554,13 +652,27 @@ def build_prompt(term: Any, rows: Sequence[str], *, folder: str = "") -> str:"This pane has not been sent an instruction from Jarvis; whatever it ""is doing was typed into it directly.")- parts.append("Its terminal screen, oldest row first:\n<<<\n" + "\n".join(tail) + "\n>>>")+ parts.extend(_screen_sections(rows))language = _LANGUAGE_NAMES.get(_ui_language(), _LANGUAGE_NAMES["en"])parts.append(f"Write both lines in {language}.")return "\n\n".join(parts)+def _valid_model_headline(headline: str) -> bool:+ """Whether a model line is a navigation label rather than CLI debris."""+ if len(headline.split()) < 2 or len(_TITLE_WORD_RE.findall(headline)) < 2:+ return False+ if '"' in headline or "`" in headline or _SHELL_FRAGMENT_RE.search(headline):+ return False+ if headline.lstrip().startswith(("...", "./", "../", "/", "\\")):+ return False+ return all(+ headline.count(opening) == headline.count(closing)+ for opening, closing in (("(", ")"), ("[", "]"), ("{", "}"))+ )++def parse_answer(text: str, *, writer: str = "") -> SmartRecap | None:"""Pull the two lines out of the model's answer, or None if neither is there.@@ -596,8 +708,20 @@ def parse_answer(text: str, *, writer: str = "") -> SmartRecap | None:headline = recap.condense(headline.strip().strip('"').rstrip(".").strip(), HEADLINE_CHARS)detail = recap.condense(" ".join(detail_parts).strip().strip('"'), DETAIL_CHARS)- if not headline:+ if not _valid_model_headline(headline):return None+ detail_words = re.findall(r"\b[\w'-]+\b", detail, flags=re.UNICODE)+ sentence_ends = list(_DETAIL_SENTENCE_END_RE.finditer(detail))+ if len(detail) < MIN_DETAIL_CHARS or len(detail_words) < MIN_DETAIL_WORDS:+ detail = headline+ elif sentence_ends:+ # Keep every complete sentence and drop only the provider's guillotined+ # tail (`...where it stands. A`). One complete sentence is more useful+ # than repeating the headline merely because the requested second one+ # ran out of budget.+ detail = detail[: sentence_ends[-1].end()].strip()+ else:+ detail = headlinereturn SmartRecap(headline=headline,detail=detail or headline,@@ -627,19 +751,41 @@ async def summarize_with_model(# A recap is a reading of the screen, not an opinion about it: the same# pane should not be described differently on two consecutive polls.temperature=0.1,- max_tokens=400,+ max_tokens=MODEL_OUTPUT_TOKENS,stream=True,+ # This is a small deterministic extraction task. Thinking-by-default+ # Gemini models count internal reasoning against `max_tokens`; live, the+ # 400-token budget was consumed before the visible answer reached more+ # than `DETAIL: The`. Every provider that has a reasoning control reads+ # this shared hint, and providers without one ignore it.+ reasoning_effort="none",)- chunks: list[str] = []- async for delta in brain.complete(request):- if delta.content:- chunks.append(delta.content)# Which model actually answered, for the card's footer. Read off whatever# the resolved brain exposes rather than from config: the chain may have# crossed to a different provider than the configured one (AP-22), and the# honest answer is the one that wrote the sentence.writer = str(getattr(brain, "model", "") or getattr(brain, "name", "") or "")- return parse_answer("".join(chunks), writer=writer)+ answer = parse_answer(await _complete_text(brain, request), writer=writer)+ if answer is not None:+ return answer++ # A thinking-mandatory model can spend the small first budget before it has+ # emitted a usable title. Retry only that measurable failure shape; valid+ # headlines never pay twice merely because their detail was truncated.+ retry = replace(request, max_tokens=MODEL_RETRY_OUTPUT_TOKENS)+ answer = parse_answer(await _complete_text(brain, retry), writer=writer)+ if answer is None:+ raise ValueError("The recap model returned no usable headline.")+ return answer+++async def _complete_text(brain: Any, request: Any) -> str:+ """Aggregate one bounded recap request without exposing provider details."""+ chunks: list[str] = []+ async for delta in brain.complete(request):+ if delta.content:+ chunks.append(delta.content)+ return "".join(chunks)def pin(key: str, headline: str, detail: str = "") -> SmartRecap:diff --git a/tests/unit/agentic_ide/test_recap.py b/tests/unit/agentic_ide/test_recap.pyindex 1ecece7c17..c0ea167b15 100644--- a/tests/unit/agentic_ide/test_recap.py+++ b/tests/unit/agentic_ide/test_recap.py@@ -6,6 +6,7 @@ it has nothing to report, and which rows of a coding CLI's TUI must never end upin the header. Without the last one every busy pane in a grid reads "? forshortcuts", which is the shape of a label that answers nothing."""+from __future__ import annotationsimport time@@ -58,6 +59,15 @@ def test_the_headline_reports_the_last_printed_row_when_nothing_was_asked() -> Nassert summarize(term).headline == "Running pytest tests/unit/test_login.py"+def test_a_bare_path_list_never_becomes_the_headline() -> None:+ """Search output names implementation debris, not the pane's user goal."""+ term = _pane(status="live")+ term.transcript.feed("Mapped the event bus to the speech pipeline\r\n")+ term.transcript.feed('"/core/bus.py", "jarvis/memory"\r\n')++ assert summarize(term).headline == "Mapped the event bus to the speech pipeline"++def test_a_live_pane_that_printed_nothing_falls_back_to_its_instruction() -> None:term = _pane(status="live", last_prompt="Refactor the config writer", prompts_sent=1)@@ -132,7 +142,7 @@ def test_the_headline_is_capped_for_transport() -> None:headline = summarize(term).headline- assert len(headline) <= HEADLINE_CHARS + 1 # the ellipsis+ assert len(headline) <= HEADLINE_CHARSassert headline.endswith("…")diff --git a/tests/unit/agentic_ide/test_recap_engine.py b/tests/unit/agentic_ide/test_recap_engine.pyindex 73181a1ffe..befd9d085f 100644--- a/tests/unit/agentic_ide/test_recap_engine.py+++ b/tests/unit/agentic_ide/test_recap_engine.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport asyncioimport time+from types import SimpleNamespaceimport pytest@@ -181,17 +182,31 @@ def test_scheduling_never_raises(monkeypatch) -> None:# ----------------------------------------------------------------- the prompt-def test_the_prompt_carries_the_instruction_and_the_newest_rows() -> None:+def test_the_prompt_carries_the_instruction_and_both_transcript_bookends() -> None:+ """The original request says WHY; the newest rows say where it stands."""term = _pane(last_prompt="Analyse swapping terminal tiles by dragging them")prompt = recap_engine.build_prompt(term, _rows(400), folder="C:/repo")assert "Analyse swapping terminal tiles" in prompt- assert "Step 399" in prompt # the newest row survives the budget...- assert "Step 0" not in prompt # ...and the oldest is what gets dropped+ assert "Step 0" in prompt # the original request is usually at this end...+ assert "Step 399" in prompt # ...and the current state is at this one.+ assert "Step 200" not in prompt # noisy implementation history is omittedassert "C:/repo" in prompt+def test_the_headline_prompt_is_an_outcome_label_that_fits_the_real_header() -> None:+ """Pin the product distinction the screenshot exposed: goal, not process."""+ system = recap_engine._SYSTEM # noqa: SLF001 - the contract under test++ assert "navigation label" in system+ assert "HARD MAXIMUM 48 characters" in system+ assert "original user goal" in system.lower()+ assert '"Investigating"' in system+ assert "Keep file paths" in system+ assert "Workspace setup — one clear screen" in system++def test_a_pane_nobody_briefed_says_so_in_the_prompt() -> None:prompt = recap_engine.build_prompt(_pane(), _rows(10))@@ -258,7 +273,29 @@ def test_the_headline_is_capped_for_transport() -> None:answer = recap_engine.parse_answer("HEADLINE: " + "word " * 200)assert answer is not None- assert len(answer.headline) <= recap_engine.HEADLINE_CHARS + 1+ assert len(answer.headline) <= recap_engine.HEADLINE_CHARS+++def test_a_truncated_detail_does_not_replace_a_useful_headline_with_debris() -> None:+ """Live Gemini output once ended at `DETAIL: The` after thinking used the cap."""+ answer = recap_engine.parse_answer(+ "HEADLINE: Terminal alerts — 3 reliability fixes\nDETAIL: The"+ )++ assert answer is not None+ assert answer.detail == answer.headline+++ "answer",+ [+ "HEADLINE: Glockenfunktion)\nDETAIL: Three notification bugs are being fixed.",+ '... tests -g "*.py',+ "adr/0014-memory-trigger-contract",+ ],+)+def test_cli_debris_is_rejected_as_a_model_headline(answer: str) -> None:+ assert recap_engine.parse_answer(answer) is None# ------------------------------------------------------------ the summary itself@@ -271,6 +308,70 @@ def test_an_install_with_no_provider_keeps_the_deterministic_recap(monkeypatch)assert asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20))) is None+def test_the_recap_request_disables_internal_reasoning(monkeypatch) -> None:+ """A tiny extraction must leave its output budget for the visible answer."""++ class Brain:+ model = "test-model"++ def __init__(self) -> None:+ self.requests: list[object] = []++ async def complete(self, request): # noqa: ANN001, ANN202 - protocol fake+ self.requests.append(request)+ yield SimpleNamespace(+ content=(+ "HEADLINE: Terminal titles — clear at a glance\n"+ "DETAIL: The goal is recognizable terminal titles. "+ "The new labels lead with the user's outcome."+ )+ )++ brain = Brain()+ monkeypatch.setattr(recap_engine, "_resolve_brain", lambda: brain)++ answer = asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20)))++ assert answer is not None+ assert len(brain.requests) == 1+ assert brain.requests[0].max_tokens == recap_engine.MODEL_OUTPUT_TOKENS # type: ignore[attr-defined]+ assert brain.requests[0].reasoning_effort == "none" # type: ignore[attr-defined]+++def test_an_invalid_small_answer_retries_with_the_measured_larger_budget(monkeypatch) -> None:+ """Only malformed headlines pay for a thinking-mandatory provider retry."""++ class Brain:+ model = "test-model"++ def __init__(self) -> None:+ self.requests: list[object] = []++ async def complete(self, request): # noqa: ANN001, ANN202 - protocol fake+ self.requests.append(request)+ content = (+ "adr/0014-memory-trigger-contract"+ if len(self.requests) == 1+ else (+ "HEADLINE: Terminal titles — clear at a glance\n"+ "DETAIL: The goal is recognizable terminal titles. "+ "The new labels lead with the user's outcome."+ )+ )+ yield SimpleNamespace(content=content)++ brain = Brain()+ monkeypatch.setattr(recap_engine, "_resolve_brain", lambda: brain)++ answer = asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20)))++ assert answer is not None+ assert [request.max_tokens for request in brain.requests] == [ # type: ignore[attr-defined]+ recap_engine.MODEL_OUTPUT_TOKENS,+ recap_engine.MODEL_RETRY_OUTPUT_TOKENS,+ ]++def test_a_failing_provider_leaves_the_previous_sentence_in_place() -> None:"""A provider that raises costs the refresh, never the recap on screen."""@@ -290,9 +391,7 @@ def test_a_failing_provider_leaves_the_previous_sentence_in_place() -> None:finally:recap_engine.summarize_with_model = original # type: ignore[assignment]- assert recap_engine.recap_for(term, lines=[]).headline == (- "The sentence already on screen"- )+ assert recap_engine.recap_for(term, lines=[]).headline == ("The sentence already on screen")assert state.failures == 1assert not state.inflight