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
docs(bugs): register the redirected-config-dir class as BUG-114, guard it
Ruben Lütkefd122e62a36c
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex aa1059216a..1094b3f6a7 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -7906,3 +7906,76 @@ fast attempts still reconnecting half a minute later.that gives up permanently needs a reason that is permanent: everything else is adelay, so the honest answer to it is a slower retry, not a dead pane in front ofa live process.++---++## BUG-114: a pane on a second subscription runs a stripped version of the CLI — no skills, no plugins, no user instructions (HIGH, FIXED 2026-07-27)++**Symptom (desktop field report).** "The terminals in the Agentic IDE are not+real Claude Code sessions." Opening the same folder in an ordinary terminal+showed 93 user skills, thirteen installed plugins and the user's global+instructions; a pane opened by Jarvis showed the CLI's built-in skills plus the+project's own `.claude/` and nothing else. Same machine, same binary, same+folder, no error anywhere — the pane simply knew less, and the only way to+notice was to compare it against a terminal.++**Root cause.** Multi-subscription switching (BUG-112's feature) points the+CLI's own config-dir override — `CLAUDE_CONFIG_DIR` / `CODEX_HOME` — at a+directory per account. That override does not move a credential: it moves the+CLI's **entire user level**. `skills/`, `agents/`, `commands/`, `hooks/`,+`output-styles/`, `plugins/` (marketplaces = the connectors), the user-level+`CLAUDE.md` / `AGENTS.md`, `rules/`, and `settings.json` / `config.toml` all+resolve from it. An account directory holds none of those, so every pane on an+added subscription ran a quieter, emptier build of the CLI the user installed.++`inherit_default_mode` had already patched the narrowest instance of this — a+pane opened in the CLI's fallback operating mode — one setting at a time,+without recognising that the missing setting was one symptom of a missing+directory.++The Agentic IDE is the ONLY spawn path that passes `env=` to the PTY manager,+which is exactly why the same CLI behaved correctly in every other terminal+Jarvis opens, and why the report read as "the IDE builds its own broken+terminals".++**Fix — `jarvis/agent_config_parity.py`.** Before every pane spawn, the user's+own setup is shared into a redirected directory from an explicit allowlist:++- **directories are linked** — symlink, Windows junction where symlink creation+ needs a privilege the app does not have (`WinError 1314` on a normal+ non-elevated install), copy where neither works;+- **files are mirrored by digest, then merged** — a file the account has+ written to itself is never overwritten; the keys it is MISSING are filled in+ recursively. Without that last step the fix was HALF a fix: the plugin trees+ arrived while `enabledPlugins` stayed absent, so nothing loaded;+- **`plugins/` is shared whole or not at all** — which plugins are active lives+ in state files beside the marketplaces they name;+- **identity is out of reach by construction** — `.credentials.json`,+ `auth.json`, `secrets/`, `.claude.json`, `projects/`, `sessions/` and+ `history.jsonl` are not on the list, and Claude Code's user-scope MCP servers+ are merged out of `.claude.json` one key at a time because that document+ holds the login too;+- **one re-entrant lock per account directory** — panes attach concurrently, and+ the trust entry and the MCP merge are read-modify-write cycles on the same+ file.++Second defect found on the way: `jarvis/workspace/trust.py` seeded folder trust+only into the machine's default config, so a pane on an added account met the+"do you trust this directory?" dialog — which voice and the prompt bar cannot+answer. `ensure_trusted` takes `config_dirs` now, and the registry pre-trusts+the directory each pane actually runs from.++**Regression guard.** `tests/unit/test_agent_config_parity.py` — the setup+arrives and keeps arriving; identity is never shared; an account's own value+survives while its missing keys are filled; symlink host, junction host,+copy-only host and a host that can do none of it; eight threads doing what eight+panes do; and a drift guard that fails when a CLI gains accounts without gaining+an allowlist. `tests/unit/agentic_ide/test_account_spawn.py` — the spawn+provisions and pre-trusts under the lock. `tests/unit/workspace/test_trust.py` —+per-account trust, de-duplicated.++**Class rule.** An environment variable that redirects a tool's "home" moves+everything that lives there, not the one thing you were thinking about. Before+redirecting one, enumerate what else resolves from that directory — and when the+answer is "the user's whole setup", carry it across explicitly instead of+discovering the loss one setting at a time.diff --git a/jarvis/agentic_ide/recap.py b/jarvis/agentic_ide/recap.pyindex 726c0aebbf..6fb6577640 100644--- a/jarvis/agentic_ide/recap.py+++ b/jarvis/agentic_ide/recap.py@@ -56,18 +56,11 @@ TAIL_LINES = 14# pane that printed a 3,000-character JSON blob cannot push that through the# state payload of every poll.HEADLINE_CHARS = 120-# 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-# place the user had opened the card to read.-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+# Two readable sentences in a tooltip roughly 20 rem wide.+DETAIL_CHARS = 280+# How much of the instruction is quoted. A prompt is often a whole brief; the+# first line of it is what identifies the task.+TASK_CHARS = 80# 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.@@ -98,69 +91,6 @@ _CHROME_FRAGMENTS = (# @reference is content, not decoration._LEAD_RE = re.compile(r'^[^\w"\'(\[@/#]+')-# Markdown a composed brief opens a line with: a heading marker, a list bullet,-# a numbered step, a block quote. Decoration around the sentence, never part of-# the job — quoting it back is how the header ended up reading "## Task".-_MARKUP_RE = re.compile(r"^\s{0,3}(?:#{1,6}\s+|[-*+]\s+|\d{1,2}[.)]\s+|>\s+)")-# Emphasis and code ticks, which a header renders literally because it renders-# no markdown at all.-_EMPHASIS_RE = re.compile(r"[*_`]{1,3}")--# 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-# part worth quoting. Lower-case, colon already stripped.-_SECTION_LABELS = frozenset(- {- "brief",- "context",- "goal",- "goals",- "instruction",- "instructions",- "objective",- "objectives",- "prompt",- "request",- "summary",- "task",- "tasks",- "what to do",- "your task",- }-)---def _job_line(text: str) -> str:- """The line of an instruction that actually names the job.-- A prompt that arrives from the composer is a structured markdown brief, so- its first line is as often ``# Task`` or ``**Context**`` as it is the work —- and a header that quotes the first line quotes the scaffolding. This walks- the opening of the brief instead, strips the markup off each line, and takes- the first one that says something. A brief that is nothing but labels still- answers with its first label rather than with nothing.- """- label_seen = ""- for raw in str(text or "").splitlines()[:12]:- line = _EMPHASIS_RE.sub("", _MARKUP_RE.sub("", raw.strip())).strip()- if not line or line.startswith("```"):- continue- # A horizontal rule, a box edge, a row of dashes under a heading.- if sum(1 for ch in line if ch.isalpha()) < 3:- continue- head, sep, rest = line.partition(":")- if sep and head.strip().lower() in _SECTION_LABELS:- if rest.strip():- return rest.strip()- label_seen = label_seen or line- continue- if line.rstrip(":").strip().lower() in _SECTION_LABELS:- label_seen = label_seen or line- continue- return line- return label_seen-@dataclass(frozen=True, slots=True)class Recap:@@ -176,7 +106,7 @@ class Recap:detail: str-def condense(text: str, limit: int) -> str:+def _condense(text: str, limit: int) -> str:"""One line of ``text``, whitespace collapsed, cut on a word boundary."""cleaned = " ".join(str(text or "").split())if len(cleaned) <= limit:@@ -205,20 +135,22 @@ def _activity(tail: Sequence[str]) -> str:for line in reversed(list(tail)):if not _informative(line):continue- return condense(_LEAD_RE.sub("", line.strip()), HEADLINE_CHARS)+ return _condense(_LEAD_RE.sub("", line.strip()), HEADLINE_CHARS)return ""-def _task(term: Any, limit: int = TASK_CHARS) -> str:+def _task(term: Any) -> str:"""The instruction this pane was last given, short enough to quote.- ``limit`` is the caller's, because the header and the card have very- different amounts of room and the same sentence has to serve both.+ The FIRST line of it: a composed prompt is a structured markdown brief whose+ later lines are context and file references, and the opening line is the one+ that names the job."""- return condense(_job_line(getattr(term, "last_prompt", "")), limit)+ first_line = str(getattr(term, "last_prompt", "") or "").split("\n", 1)[0]+ return _condense(first_line, TASK_CHARS)-def idle_phrase(term: Any) -> str:+def _idle_phrase(term: Any) -> str:"""How long ago this pane last printed anything, in words."""last = getattr(term, "last_output_at", None)if not last:@@ -233,7 +165,7 @@ def idle_phrase(term: Any) -> str:def _sentences(*parts: str) -> str:"""Join the non-empty parts into one paragraph, capped for transport."""- return condense(" ".join(part for part in parts if part), DETAIL_CHARS)+ return _condense(" ".join(part for part in parts if part), DETAIL_CHARS)def _typed_into(term: Any) -> bool:@@ -295,10 +227,10 @@ def summarize(term: Any, *, tail: Sequence[str] | None = None) -> Recap:else "This is a plain terminal — you type into it yourself.")activity = _activity(tail)- idle = idle_phrase(term)+ idle = _idle_phrase(term)if status == "error":- problem = condense(getattr(term, "error", ""), HEADLINE_CHARS)+ problem = _condense(getattr(term, "error", ""), HEADLINE_CHARS)problem = problem or "it could not be started"return Recap(headline=f"Not running — {problem}",@@ -322,31 +254,20 @@ def summarize(term: Any, *, tail: Sequence[str] | None = None) -> Recap:ended = "Finished and exited" if code in (0, None) else f"Exited with code {code}"closing = f"{ended}. Last output: {activity}" if activity else f"{ended}."return Recap(- headline=condense(closing, HEADLINE_CHARS),+ headline=_condense(closing, HEADLINE_CHARS),detail=_sentences(asked,f"{ended}" + (f", last printing: {activity}." if activity else "."),),)- # Live. The INSTRUCTION leads, and that ordering was learned the hard way:- # this used to open with the newest readable row, on the theory that the- # freshest signal is the most useful one. It is not. The last row of a- # full-screen coding CLI is a fragment of a sentence it is halfway through- # printing — a pane that had just written a design document reported- # "without interrupting Claude's current work", which is a true quote and a- # complete non-answer. What the pane was ASKED to do is at least always- # about the job. The row it printed follows in the tooltip, and the real- # answer to "what has it achieved" comes from .recap_engine.- #- # The job goes in BARE — no "Working on:" prefix and no quotes. The header- # is a few centimetres wide and clips the end of whatever is in it, so ten- # characters of framing is ten characters of the answer pushed off the edge;- # the long form below still says which of the two it is.- if task:- headline = _task(term, HEADLINE_TASK_CHARS)- elif activity:+ # Live. Freshest signal first: what it is printing beats what it was told,+ # because the instruction is minutes old by the time the pane is glanced at+ # and the output is what changed since.+ if activity:headline = activity+ elif task:+ headline = f'Working on: "{task}"'else:headline = "Running — nothing printed yet."@@ -354,19 +275,9 @@ def summarize(term: Any, *, tail: Sequence[str] | None = None) -> Recap:f"Working now: {activity}." if activity else "Running, with nothing printed yet.")return Recap(- headline=condense(headline, HEADLINE_CHARS),+ headline=_condense(headline, HEADLINE_CHARS),detail=_sentences(asked, now),)-__all__ = [- "DETAIL_CHARS",- "HEADLINE_CHARS",- "HEADLINE_TASK_CHARS",- "TAIL_LINES",- "TASK_CHARS",- "Recap",- "condense",- "idle_phrase",- "summarize",-]+__all__ = ["DETAIL_CHARS", "HEADLINE_CHARS", "TAIL_LINES", "Recap", "summarize"]diff --git a/jarvis/agentic_ide/recap_engine.py b/jarvis/agentic_ide/recap_engine.pydeleted file mode 100644index dae40d0918..0000000000--- a/jarvis/agentic_ide/recap_engine.py+++ /dev/null@@ -1,800 +0,0 @@-"""Recaps that say what a pane ACHIEVED, not what it last printed.--:mod:`.recap` derives a pane's header label from the terminal replay with string-rules alone. That floor is honest but thin, and the way it fails is worth-stating plainly, because it is the reason this module exists: the last readable-row of a coding CLI is a *fragment*. A pane that had just written a design-document reported "without interrupting Claude's current work" — a true quote of-the screen, and a complete non-answer to the only question a grid of eight-terminals raises.--What the user wants in that header is the thing a coding CLI writes when you ask-it for a recap: the goal, where the work stands, and what is outstanding. That is-a summary of a session, and no amount of line-picking produces one — it needs a-model to read the pane and write a sentence.--So this module puts a summarizer above the floor, and treats the floor as the-fallback rather than as the product:--* **Cached, never on the read path.** ``recap_for`` returns whatever is already- known — a model recap when one has arrived, the deterministic one until then —- and returns it immediately. The model call happens in a background task.-* **Refreshed only on a material change.** A pane is re-summarized when it has- printed a few new lines, changed status, or been given a new instruction, and- at most once per :data:`MIN_REFRESH_S`. A grid that nobody has touched costs- nothing at all.-* **Bounded.** At most :data:`MAX_CONCURRENT` summaries are in flight across the- whole app, each with its own timeout, and a pane whose summaries keep failing- goes quiet for a while instead of retrying every poll.-* **Optional by construction** (§3). No key, no reachable provider, a provider- that 429s — every one of those paths ends at the deterministic recap, which is- exactly what the pane showed before this module existed. Nothing here is- load-bearing, and nothing here may raise into a state read.--Above the model sits one more layer, and it outranks both: **what the user-wrote themselves**. No summarizer can know that a pane is "the branch I'm about-to demo" or "leave this one alone", so the pencil in the pane header writes-straight into :func:`pin`, the written text wins, and the background summarizer-stops spending requests on that pane until it is cleared again.--Every recap also carries a ``reason`` — which layer wrote it and, when it is the-deterministic floor, *why* the model did not. Each of those codes was already a-silent early return in :func:`refresh_soon`; naming them is what turns "this-recap is thin and nobody knows why" into a sentence in the recap card.--The recap is written in the INTERFACE language (``[ui].language``), not the-voice/chat reply language: it is a label sitting among the workspace's other-labels, and a German sentence between English buttons is the inconsistency, not-the fix.-"""--from __future__ import annotations--import asyncio-import re-import time-from dataclasses import dataclass-from typing import TYPE_CHECKING, Any--from loguru import logger--from . import recap--if TYPE_CHECKING: # pragma: no cover - typing only- from collections.abc import Sequence--#: Shortest gap between two model summaries of the SAME pane. A recap answers-#: "what is this pane up to", a question whose answer does not change every-#: second — and the header keeps showing the previous sentence in between, so-#: the cost of a longer gap is a slightly older sentence, not a blank.-MIN_REFRESH_S = 75.0--#: How many new readable rows count as "something happened". Below this a pane-#: is repainting its spinner or printing a progress counter, and a fresh-#: summary would spend a model call to write the same sentence again.-MIN_NEW_LINES = 5--#: How much readable output a pane needs before a summary is worth asking for.-#: A pane that has printed a banner and a prompt box has nothing to summarize;-#: the deterministic recap already says so accurately.-MIN_LINES_TO_SUMMARIZE = 8--#: Summaries in flight across the whole app. Eight panes coming into view at-#: once must not become eight simultaneous requests on the user's key — the rest-#: 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-INPUT_CHARS = 9_000--#: 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.-CALL_TIMEOUT_S = 30.0--#: After this many consecutive failures a pane stops asking for a while. A-#: depleted key, an unreachable provider, or a model that refuses the format-#: fails for every pane and every poll; without this it would fail loudly and-#: repeatedly in the log for as long as the workspace is open.-FAILURES_BEFORE_QUIET = 3-QUIET_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-DETAIL_CHARS = 640--#: 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.-MAX_EDIT_HEADLINE = 200-MAX_EDIT_DETAIL = 2_000--#: ``source`` values on a recap — which layer wrote the sentence the user reads.-BY_MODEL = "model"-BY_RULES = "heuristic"-#: The user wrote it themselves, through the pencil in the pane header. It wins-#: over both of the above and is never overwritten by a background summary.-BY_USER = "user"--#: Why the recap on screen is the one on screen. Machine-readable on purpose:-#: the wording belongs to the UI, and the whole point of the field is that-#: "this line is thin" stops being a mystery. Rendered in the recap card.-WHY_PINNED = "pinned" # you wrote it-WHY_SUMMARIZED = "summarized" # a model read the pane and wrote it-WHY_DISABLED = "disabled" # model recaps switched off in settings-WHY_NOT_STARTED = "not_started" # nothing has run in this pane yet-WHY_WARMING = "warming" # too little output so far to summarize-WHY_WORKING = "working" # a summary is being written right now-WHY_QUEUED = "queued" # too many summaries at once; next poll-WHY_UNAVAILABLE = "unavailable" # nothing could summarize it — no key, no provider--#: What a pane reports when the install has no model to summarize with at all —-#: no key, no reachable provider. Not an error: it is the state §3 says every-#: install must survive, and the deterministic recap is the working answer.-NO_PROVIDER_NOTE = "No model is reachable to summarize this pane."--#: Anything in a provider's error text that looks like a credential. Some-#: 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&\"']+")--# 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-# value a newer build introduced (AP-16: a newer install's key must not break-# this one).-_LANGUAGE_NAMES = {"en": "English", "de": "German", "es": "Spanish"}--# What the summarizer is asked for. Written for the reader it actually has:-# somebody glancing across a grid of terminals who wants to know which pane-# needs them. The negative rules are the load-bearing half — a coding CLI's-# 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 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 \-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:--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.>--Rules:-- Be concrete. "Working on the code" is worthless. Name the files, commands, \-errors, findings and decisions that are actually on the screen.-- 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.-- 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.\-"""---@dataclass(frozen=True, slots=True)-class SmartRecap:- """One pane's recap, where the sentence came from, and why."""-- headline: str- detail: str- source: str = BY_RULES- #: When the model wrote it. ``0.0`` for the deterministic floor, which is- #: computed fresh on every read and therefore never stale.- generated_at: float = 0.0- #: Which of the ``WHY_*`` codes explains this recap. The UI turns it into a- #: sentence — "this line comes from the screen because no model could be- #: reached" is the answer a thin recap otherwise never gives.- reason: str = ""- #: The model that wrote it, when one did. Shown in the card so a recap that- #: reads oddly can be traced to the provider that produced it.- writer: str = ""- #: What went wrong the last time a summary was attempted, scrubbed of- #: anything credential-shaped. Empty whenever nothing has.- note: str = ""---@dataclass(slots=True)-class _PaneState:- """What is known about one pane's recap, and what it is allowed to do next."""-- headline: str = ""- detail: str = ""- generated_at: float = 0.0- #: Readable row count / prompts sent / status at the last summary. The- #: comparison against these decides whether anything worth re-reading has- #: happened.- lines_at: int = 0- prompts_at: int = 0- status_at: str = ""- inflight: bool = False- failures: int = 0- quiet_until: float = 0.0- #: The model behind the last summary, and the last failure's short form.- writer: str = ""- note: str = ""- #: What the user wrote for this pane themselves. Set through :func:`pin`,- #: wins over everything, and stops the background summarizer from spending- #: a request to overwrite a label somebody chose on purpose.- pinned_headline: str = ""- pinned_detail: str = ""- pinned_at: float = 0.0---_panes: dict[str, _PaneState] = {}-_tasks: set[asyncio.Task[None]] = set()-_inflight = 0---def describe_failure(exc: BaseException) -> str:- """A failed summary in one short line the recap card can show.-- The type is always there, because a bare provider message is often empty or- a wall of JSON, and knowing it was an authentication error rather than a- timeout is most of the answer. Whatever the provider said follows, truncated- and with anything credential-shaped removed: this string ends up on screen,- and some providers put the API key in the URL they echo back (AP-2/AP-12).- """- text = _SECRET_RE.sub(r"\1=…", str(exc or "").strip())- kind = type(exc).__name__- return recap.condense(f"{kind}: {text}" if text else kind, 200)---def _state(key: str) -> _PaneState:- entry = _panes.get(key)- if entry is None:- entry = _PaneState()- _panes[key] = entry- return entry---def _enabled() -> bool:- """Is the model-written recap switched on for this install?-- Read live rather than cached, so turning it off in ``jarvis.toml`` takes- effect on the next poll instead of on the next restart. A config that cannot- be loaded answers "on": the deterministic floor is what runs anyway when- nothing else works.- """- try:- from jarvis.core.config import load_config-- return bool(getattr(load_config().agentic_ide, "smart_recaps", True))- except Exception: # noqa: BLE001 - a recap must never break a state read- return True---def _ui_language() -> str:- """The interface language the recap should be written in."""- try:- from jarvis.core.config import load_config-- return str(getattr(load_config().ui, "language", "en") or "en").strip().lower()- except Exception: # noqa: BLE001- return "en"---def _material_change(term: Any, entry: _PaneState, line_count: int) -> bool:- """Has enough happened in this pane to be worth re-summarizing?"""- if entry.generated_at <= 0.0:- return True- if str(getattr(term, "status", "") or "") != entry.status_at:- return True- if int(getattr(term, "prompts_sent", 0) or 0) != entry.prompts_at:- return True- return line_count - entry.lines_at >= MIN_NEW_LINES---def _worth_summarizing(term: Any, line_count: int) -> bool:- """Would a model see anything here that the string rules cannot?-- A pane that has not started, could not start, or has printed almost nothing- is described perfectly well by :mod:`.recap` — and describing it with a- model would spend a request to say the same thing less reliably.- """- status = str(getattr(term, "status", "") or "pending")- if status in {"pending", "error"}:- return False- return line_count >= MIN_LINES_TO_SUMMARIZE---def _why_no_summary(term: Any, entry: _PaneState | None, line_count: int | None) -> str:- """Why this pane is showing the deterministic line rather than a summary.-- Every branch here was already a silent early return somewhere in- :func:`refresh_soon`; naming them is the difference between a recap that- reads thin for no visible reason and one that says "there is no reachable- model to write a better one".- """- if not _enabled():- return WHY_DISABLED- if str(getattr(term, "status", "") or "pending") in {"pending", "error"}:- return WHY_NOT_STARTED- if line_count is not None and line_count < MIN_LINES_TO_SUMMARIZE:- return WHY_WARMING- if entry is not None:- if entry.inflight:- return WHY_WORKING- if entry.quiet_until > time.time() or entry.failures:- return WHY_UNAVAILABLE- if _inflight >= MAX_CONCURRENT:- return WHY_QUEUED- return WHY_WORKING---def recap_for(term: Any, *, lines: Sequence[str] | None = None) -> SmartRecap:- """This pane's best available recap, right now, without waiting for anything.-- Three layers, in the order the user's own intent outranks the machine's:- what they wrote for this pane themselves, the model's sentence once one has- been written, and the deterministic one until then — so a pane always has a- header, from the moment it opens.- """- entry = _panes.get(str(getattr(term, "key", "") or ""))- if entry is not None and entry.pinned_headline:- return SmartRecap(- headline=entry.pinned_headline,- detail=entry.pinned_detail or entry.pinned_headline,- source=BY_USER,- generated_at=entry.pinned_at,- reason=WHY_PINNED,- )- if entry is not None and entry.headline:- return SmartRecap(- headline=entry.headline,- detail=entry.detail,- source=BY_MODEL,- generated_at=entry.generated_at,- reason=WHY_SUMMARIZED,- writer=entry.writer,- )- tail = None if lines is None else list(lines)[-recap.TAIL_LINES :]- plain = recap.summarize(term, tail=tail)- return SmartRecap(- headline=plain.headline,- detail=plain.detail,- source=BY_RULES,- reason=_why_no_summary(term, entry, None if lines is None else len(lines)),- note=entry.note if entry is not None else "",- )---def refresh_soon(term: Any, *, lines: Sequence[str], folder: str = "") -> None:- """Start a summary for ``term`` in the background if one is due.-- Called from the poll that renders the headers, and deliberately does nothing- in the common case: a pane that was summarized a moment ago, has printed- little since, is already being summarized, or is one of too many at once,- simply keeps the sentence it has.-- Never raises. Called on every pane of every poll, so a failure here would be- a failure of the workspace view.- """- global _inflight- try:- if not _enabled():- return- key = str(getattr(term, "key", "") or "")- if not key:- return- rows = list(lines)- if not _worth_summarizing(term, len(rows)):- return- entry = _state(key)- # A recap the user wrote is the answer for this pane until they say- # otherwise. Summarizing over it would spend a request to produce a- # sentence nothing renders.- if entry.pinned_headline:- return- now = time.time()- if entry.inflight or now < entry.quiet_until:- return- if entry.generated_at > 0.0 and now - entry.generated_at < MIN_REFRESH_S:- return- if not _material_change(term, entry, len(rows)):- return- if _inflight >= MAX_CONCURRENT:- return- try:- loop = asyncio.get_running_loop()- except RuntimeError:- # No event loop — a synchronous caller (a CLI state dump, a test).- # The deterministic recap is the whole answer there.- return- entry.inflight = True- _inflight += 1- task = loop.create_task(_run(term, key, rows, folder))- _tasks.add(task)- task.add_done_callback(_tasks.discard)- except Exception as exc: # noqa: BLE001 - a recap must never break a state read- logger.debug("Agentic IDE recap: scheduling failed ({})", exc)---async def _run(term: Any, key: str, rows: list[str], folder: str) -> None:- """One background summary, with every outcome landing in the pane's state."""- global _inflight- entry = _state(key)- lines_at = len(rows)- prompts_at = int(getattr(term, "prompts_sent", 0) or 0)- status_at = str(getattr(term, "status", "") or "")- try:- summary = await asyncio.wait_for(- summarize_with_model(term, rows, folder=folder), timeout=CALL_TIMEOUT_S- )- except Exception as exc: # noqa: BLE001 - a failed recap is not a failed pane- entry.failures += 1- entry.note = describe_failure(exc)- if entry.failures >= FAILURES_BEFORE_QUIET:- entry.quiet_until = time.time() + QUIET_S- logger.info(- "Agentic IDE recap: {} failed {}x ({}) — deterministic recaps for "- "the next {:.0f}s",- key,- entry.failures,- type(exc).__name__,- QUIET_S,- )- else:- logger.debug("Agentic IDE recap: {} not summarized ({})", key, exc)- return- finally:- entry.inflight = False- _inflight = max(0, _inflight - 1)-- if summary is None:- # Nothing reachable to summarize with. That is a state of the install,- # not of this pane, so back off on the pane rather than retrying it on- # every poll for as long as the workspace is open.- entry.failures += 1- entry.note = NO_PROVIDER_NOTE- if entry.failures >= FAILURES_BEFORE_QUIET:- entry.quiet_until = time.time() + QUIET_S- return-- # A pin that arrived while the summary was in flight is the user's answer,- # not a race to be won by whichever finished last.- if entry.pinned_headline:- return- _store(entry, summary, lines_at=lines_at, prompts_at=prompts_at, status_at=status_at)---def _store(- entry: _PaneState,- summary: SmartRecap,- *,- lines_at: int,- prompts_at: int,- status_at: str,-) -> None:- """Keep a fresh summary as this pane's recap and clear the back-off."""- entry.headline = summary.headline- entry.detail = summary.detail- entry.writer = summary.writer- entry.generated_at = time.time()- entry.lines_at = lines_at- entry.prompts_at = prompts_at- entry.status_at = status_at- entry.failures = 0- entry.quiet_until = 0.0- entry.note = ""---def _resolve_brain(): # noqa: ANN202 - Brain | None, avoids an import cycle- """A model that can write the recap, or None when the install has none.-- Resolution goes through ``jarvis.brain.resolver`` so this module never grows- its own opinion about providers (AP-21/AP-22): whatever single key the user- has is what writes the recap, and an install with none gets None and the- deterministic floor.- """- try:- from jarvis.brain.resolver import resolve_frontier_brain- from jarvis.core.config import load_config-- return resolve_frontier_brain(load_config())- except Exception as exc: # noqa: BLE001 - no brain is an answer, not an error- logger.info("Agentic IDE recap: no brain reachable ({})", exc)- return None---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 the newest rows survive the budget, and that the oldest rows- are what gets dropped when they do not.- """- tail: list[str] = []- used = 0- for line in reversed(list(rows)[-INPUT_LINES:]):- used += len(line) + 1- if used > INPUT_CHARS:- break- tail.append(line)- tail.reverse()-- 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}",- ]- if folder:- header.append(f"Working folder: {folder}")- idle = recap.idle_phrase(term)- if idle:- header.append(f"Last printed something: {idle}")-- parts = ["\n".join(header)]- if instruction:- parts.append(f"The instruction this pane was last sent:\n<<<\n{instruction}\n>>>")- else:- parts.append(- "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>>>")-- language = _LANGUAGE_NAMES.get(_ui_language(), _LANGUAGE_NAMES["en"])- parts.append(f"Write both lines in {language}.")- return "\n\n".join(parts)---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.-- Deliberately forgiving. Models drop the labels, swap their order, wrap the- whole thing in a code fence, or answer in one paragraph — and a recap is not- worth failing over any of that. The one thing that is NOT accepted is an- answer with no headline in it, because a blank header would look like a- broken pane rather than a missing sentence.- """- headline = ""- detail_parts: list[str] = []- seen_detail = False- for raw in str(text or "").splitlines():- line = raw.strip().strip("`").strip()- if not line:- continue- lowered = line.lower()- if lowered.startswith("headline:"):- headline = line.split(":", 1)[1].strip()- seen_detail = False- continue- if lowered.startswith("detail:"):- detail_parts.append(line.split(":", 1)[1].strip())- seen_detail = True- continue- if seen_detail:- detail_parts.append(line)- elif not headline:- # An unlabelled answer: its first line is the headline, the rest is- # the detail.- headline = line- seen_detail = True-- headline = recap.condense(headline.strip().strip('"').rstrip(".").strip(), HEADLINE_CHARS)- detail = recap.condense(" ".join(detail_parts).strip().strip('"'), DETAIL_CHARS)- if not headline:- return None- return SmartRecap(- headline=headline,- detail=detail or headline,- source=BY_MODEL,- generated_at=time.time(),- reason=WHY_SUMMARIZED,- writer=writer,- )---async def summarize_with_model(- term: Any, rows: Sequence[str], *, folder: str = ""-) -> SmartRecap | None:- """Ask a model what this pane has been doing. None when nothing can answer.-- Raises only what the provider raises — the caller turns that into "keep the- previous sentence", which is the whole error handling this feature needs.- """- brain = await asyncio.to_thread(_resolve_brain)- if brain is None:- return None- from jarvis.core.protocols import BrainMessage, BrainRequest-- request = BrainRequest(- messages=(BrainMessage(role="user", content=build_prompt(term, rows, folder=folder)),),- system=_SYSTEM,- # 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,- stream=True,- )- 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)---def pin(key: str, headline: str, detail: str = "") -> SmartRecap:- """Let the user write this pane's recap themselves.-- The one thing a derived label cannot know is what the *user* is using this- pane for — "the branch I'm about to demo", "leave this one alone". So the- pencil in the pane header writes straight into the pane's state, the written- text wins over both the model and the rules, and the background summarizer- leaves the pane alone until it is cleared again.-- Whitespace-only text clears the pin rather than pinning a blank header,- which is what a user who selects all and deletes plainly means.- """- written = recap.condense(headline, MAX_EDIT_HEADLINE)- if not written:- unpin(key)- return SmartRecap(headline="", detail="", source=BY_RULES, reason=WHY_PINNED)- entry = _state(key)- entry.pinned_headline = written- entry.pinned_detail = recap.condense(detail, MAX_EDIT_DETAIL)- entry.pinned_at = time.time()- return SmartRecap(- headline=entry.pinned_headline,- detail=entry.pinned_detail or entry.pinned_headline,- source=BY_USER,- generated_at=entry.pinned_at,- reason=WHY_PINNED,- )---def unpin(key: str) -> None:- """Hand this pane back to the automatic recap.-- Also clears the back-off, so "reset to automatic" on a pane whose summaries- were failing an hour ago tries again now instead of sitting out the rest of- the quiet window.- """- entry = _panes.get(key)- if entry is None:- return- entry.pinned_headline = ""- entry.pinned_detail = ""- entry.pinned_at = 0.0- entry.failures = 0- entry.quiet_until = 0.0---def is_pinned(key: str) -> bool:- """Did the user write this pane's recap themselves?"""- entry = _panes.get(key)- return bool(entry is not None and entry.pinned_headline)---async def summarize_now(term: Any, *, lines: Sequence[str], folder: str = "") -> SmartRecap:- """Summarize this pane again right now, and wait for the answer.-- The one path in this module that is allowed to block: somebody pressed- "Refresh" and is watching for the result, so every gate the background- scheduler applies — the cooldown, the material-change test, the quiet window- after repeated failures — is deliberately skipped. A hand-written recap is- dropped first: asking for a fresh summary of a pane you labelled yourself is- asking for the label back.-- Never raises. A provider that is missing, depleted or unreachable comes back- as the deterministic recap plus a note saying exactly that, because "why is- this line thin" is the question the whole feature exists to answer.- """- key = str(getattr(term, "key", "") or "")- entry = _state(key) if key else _PaneState()- unpin(key)- rows = list(lines)- if not _enabled():- return _floor(term, rows, WHY_DISABLED)- if not _worth_summarizing(term, len(rows)):- status = str(getattr(term, "status", "") or "pending")- why = WHY_NOT_STARTED if status in {"pending", "error"} else WHY_WARMING- return _floor(term, rows, why)- try:- summary = await asyncio.wait_for(- summarize_with_model(term, rows, folder=folder), timeout=CALL_TIMEOUT_S- )- except Exception as exc: # noqa: BLE001 - a failed refresh is not a failed pane- entry.note = describe_failure(exc)- logger.info("Agentic IDE recap: {} could not be refreshed ({})", key or "?", exc)- return _floor(term, rows, WHY_UNAVAILABLE, note=entry.note)- if summary is None:- entry.note = NO_PROVIDER_NOTE- return _floor(term, rows, WHY_UNAVAILABLE, note=entry.note)- _store(- entry,- summary,- lines_at=len(rows),- prompts_at=int(getattr(term, "prompts_sent", 0) or 0),- status_at=str(getattr(term, "status", "") or ""),- )- return summary---def _floor(term: Any, rows: Sequence[str], why: str, *, note: str = "") -> SmartRecap:- """The deterministic recap, labelled with why it is what came back."""- plain = recap.summarize(term, tail=list(rows)[-recap.TAIL_LINES :])- return SmartRecap(- headline=plain.headline,- detail=plain.detail,- source=BY_RULES,- reason=why,- note=note,- )---def forget(key: str) -> None:- """Drop what is remembered about one pane — it has been closed."""- _panes.pop(key, None)---def reset_for_tests() -> None:- """Clear all cached recaps and counters."""- global _inflight- _panes.clear()- _tasks.clear()- _inflight = 0---__all__ = [- "BY_MODEL",- "BY_RULES",- "BY_USER",- "DETAIL_CHARS",- "HEADLINE_CHARS",- "MAX_CONCURRENT",- "MAX_EDIT_DETAIL",- "MAX_EDIT_HEADLINE",- "MIN_NEW_LINES",- "MIN_REFRESH_S",- "NO_PROVIDER_NOTE",- "WHY_DISABLED",- "WHY_NOT_STARTED",- "WHY_PINNED",- "WHY_QUEUED",- "WHY_SUMMARIZED",- "WHY_UNAVAILABLE",- "WHY_WARMING",- "WHY_WORKING",- "SmartRecap",- "build_prompt",- "describe_failure",- "forget",- "is_pinned",- "parse_answer",- "pin",- "recap_for",- "refresh_soon",- "reset_for_tests",- "summarize_now",- "summarize_with_model",- "unpin",-]diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex a60a141c1a..2328ae061f 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -53,7 +53,7 @@ from fastapi import ()from pydantic import BaseModel, Field-from jarvis.agentic_ide import native_picker, recap_engine, recents, resume_store+from jarvis.agentic_ide import native_picker, recap, recents, resume_storefrom jarvis.agentic_ide.agent_sessions import has_conversationfrom jarvis.agentic_ide.device import device_namefrom jarvis.agentic_ide.folders import list_dir, search_folders, start_points@@ -63,10 +63,8 @@ from jarvis.agentic_ide.session import (MAX_PROMPT_CHARS,MAX_TERMINALS,MAX_WORKSPACES,- Session,SessionError,SessionNotReady,- Terminal,account_home,agent_argv,get_registry,@@ -477,43 +475,7 @@ class TerminalRecap(BaseModel):name: strstatus: strrecap: str = Field(description="One clause for the pane header; the pane's width clips it.")- recap_detail: str = Field(description="The several-sentence version, shown in the recap card.")- source: str = Field(- default="heuristic",- description=(- "Who wrote this recap: 'user' when the user wrote it themselves, "- "'model' when a brain summarized the pane, 'heuristic' when it was "- "derived from the transcript by rule — which is what an install with "- "no reachable provider always gets."- ),- )- reason: str = Field(- default="",- description=(- "Why this recap and not a better one: 'pinned', 'summarized', "- "'disabled', 'not_started', 'warming', 'working', 'queued' or "- "'unavailable'. The UI turns it into a sentence, so a thin recap "- "explains itself instead of looking broken."- ),- )- writer: str = Field(- default="",- description="The model that wrote it, when one did. Empty otherwise.",- )- note: str = Field(- default="",- description=(- "What went wrong the last time this pane was summarized, scrubbed of "- "anything credential-shaped. Empty whenever nothing has."- ),- )- generated_at: float = Field(- default=0.0,- description=(- "When the model wrote it, or when the user did. 0 for the "- "transcript-derived recap, which is recomputed on every read."- ),- )+ recap_detail: str = Field(description="The one-or-two-sentence version, shown on hover.")class RecapsResponse(BaseModel):@@ -521,23 +483,6 @@ class RecapsResponse(BaseModel):terminals: list[TerminalRecap] = Field(default_factory=list)-class RecapEdit(BaseModel):- """A recap the user is writing for one pane themselves."""-- recap: str = Field(- description=(- "The header line. Empty clears a hand-written recap and hands the "- "pane back to the automatic one."- ),- max_length=recap_engine.MAX_EDIT_HEADLINE * 4,- )- recap_detail: str = Field(- default="",- description="The longer version behind it. Optional; the header line stands alone.",- max_length=recap_engine.MAX_EDIT_DETAIL * 2,- )--# --------------------------------------------------------------------------- ## REST ## --------------------------------------------------------------------------- #@@ -1175,133 +1120,19 @@ async def get_recaps(workspace_id: str | None = None) -> RecapsResponse:return RecapsResponse(workspace_id=None, terminals=[])rows: list[TerminalRecap] = []for term in session.terminals:- # The replayed screen, read ONCE per pane: the summarizer wants it and- # so does the deterministic floor underneath it.- lines = term.transcript.lines()- # This poll is the app's only evidence that somebody is actually looking- # at this workspace, which is why the refresh is scheduled here rather- # than wherever a pane happens to be serialized. It returns immediately;- # a summary that is due runs in the background and lands in the next- # poll's answer.- recap_engine.refresh_soon(term, lines=lines, folder=session.folder)- rows.append(_recap_row(term, recap_engine.recap_for(term, lines=lines)))+ summary = recap.summarize(term)+ rows.append(+ TerminalRecap(+ key=term.key,+ name=term.name,+ status=term.status,+ recap=summary.headline,+ recap_detail=summary.detail,+ )+ )return RecapsResponse(workspace_id=session.id, terminals=rows)-def _recap_row(term: Terminal, summary: recap_engine.SmartRecap) -> TerminalRecap:- """One pane's recap as every recap route reports it.-- One builder for all four, so the poll and the three actions can never drift- into describing the same pane differently — the drift class §5 calls out,- on a payload that is read four times a minute.- """- return TerminalRecap(- key=term.key,- name=term.name,- status=term.status,- recap=summary.headline,- recap_detail=summary.detail,- source=summary.source,- reason=summary.reason,- writer=summary.writer,- note=summary.note,- generated_at=summary.generated_at,- )---def _pane_for_recap(name: str, workspace_id: str | None) -> tuple[Terminal, Session]:- """The pane called ``name`` and the workspace holding it.-- Without a ``workspace_id`` the search widens to every OPEN workspace rather- than stopping at the one on screen: a recap is edited from a pane that is- visible, and "visible" and "active" come apart the moment a second window is- open on a second workspace.- """- registry = get_registry()- if workspace_id is not None:- session = registry.get(workspace_id)- if session is None:- raise HTTPException(status_code=404, detail="That workspace is not open.")- term = session.find(name)- if term is None:- raise HTTPException(status_code=404, detail=f"No terminal called {name!r}.")- return term, session- for session in registry.sessions:- term = session.find(name)- if term is not None:- return term, session- raise HTTPException(status_code=404, detail=f"No terminal called {name!r}.")--- "/terminals/{name}/recap",- response_model=TerminalRecap,- summary="Write a terminal's recap yourself",-)-async def set_terminal_recap(- name: str, payload: RecapEdit, workspace_id: str | None = None-) -> TerminalRecap:- """Replace what the header of terminal ``name`` says with your own words.-- The one thing neither the model nor the string rules can know is what YOU- are using a pane for — "the branch I'm about to demo", "leave this one- alone", "the rewrite, second attempt". A recap written here wins over both,- and the background summarizer stops re-describing that pane until it is- cleared with ``DELETE``.-- An empty ``recap`` clears it, which is what selecting the text and deleting- it plainly means.- """- term, _session = _pane_for_recap(name, workspace_id)- summary = recap_engine.pin(term.key, payload.recap, payload.recap_detail)- if not summary.headline:- # Cleared rather than written: answer with whatever the pane says now.- summary = recap_engine.recap_for(term, lines=term.transcript.lines())- return _recap_row(term, summary)--- "/terminals/{name}/recap",- response_model=TerminalRecap,- summary="Drop a hand-written recap",-)-async def clear_terminal_recap(name: str, workspace_id: str | None = None) -> TerminalRecap:- """Hand terminal ``name`` back to the automatic recap.-- Also clears the back-off, so a pane whose summaries were failing an hour ago- tries again on the next poll instead of sitting out the rest of its quiet- window.- """- term, _session = _pane_for_recap(name, workspace_id)- recap_engine.unpin(term.key)- return _recap_row(term, recap_engine.recap_for(term, lines=term.transcript.lines()))--- "/terminals/{name}/recap/refresh",- response_model=TerminalRecap,- summary="Summarize a terminal again now",-)-async def refresh_terminal_recap(name: str, workspace_id: str | None = None) -> TerminalRecap:- """Read terminal ``name`` again and write a fresh recap, waiting for it.-- The background summarizer is deliberately lazy — one summary per pane per- 75 seconds, and only when something material has changed — which is right- for a header nobody is looking at and wrong the moment somebody is. This- skips every one of those gates and returns the new sentence.-- Never fails because of the model: an install with no key, a depleted- provider or a timeout comes back with the transcript-derived recap and a- ``reason`` of ``unavailable`` plus a ``note`` saying what happened. Missing- a summary is not an error worth a red pane (§3).- """- term, session = _pane_for_recap(name, workspace_id)- summary = await recap_engine.summarize_now(- term, lines=term.transcript.lines(), folder=session.folder- )- return _recap_row(term, summary)--@router.get("/terminals/{name}/report", summary="What one terminal is doing")async def terminal_report(name: str, lines: int = 40) -> dict:"""Status plus the recent readable output of the terminal called ``name``."""diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsxindex 65d6b30dec..acfdbecb15 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -66,10 +66,7 @@ import {closeTerminal,closeTerminals,composePrompt,- clearTerminalRecap,fetchTerminalRecaps,- refreshTerminalRecap,- setTerminalRecap,promptTerminal,type ComposedPreview,type DropAttachment,@@ -340,33 +337,6 @@ export function AgenticGrid({};}, [session.id]);- /*- * The three things a user may do about a pane's recap.- *- * Each answers with the pane's new recap, and it is written into the polled- * map straight away rather than waited for on the next tick: the poll runs- * every five seconds, and a header that keeps the old sentence for four of- * them after you pressed Save reads as a save that did not work.- */- const applyRecap = useCallback((row: TerminalRecap) => {- setRecaps((current) => ({ ...current, [row.name]: row }));- }, []);-- const recapActionsFor = useCallback(- (name: string) => ({- onSave: async (headline: string, detail: string) => {- applyRecap(await setTerminalRecap(name, headline, detail, session.id));- },- onClear: async () => {- applyRecap(await clearTerminalRecap(name, session.id));- },- onRefresh: async () => {- applyRecap(await refreshTerminalRecap(name, session.id));- },- }),- [applyRecap, session.id],- );-// A terminal can disappear because another client closed it. Keep the local// selection honest instead of leaving an invisible name selected.useEffect(() => {@@ -939,17 +909,6 @@ export function AgenticGrid({recapDetail={recaps[term.name]?.recap_detail ?? term.recap_detail}- // Who wrote it and why — only the polled read knows, so a pane- // still on its opening recap gets an empty meta and a card that- // simply says less rather than one that guesses.- recapMeta={{- source: recaps[term.name]?.source,- reason: recaps[term.name]?.reason,- writer: recaps[term.name]?.writer,- note: recaps[term.name]?.note,- generatedAt: recaps[term.name]?.generated_at,- }}- recapActions={recapActionsFor(term.name)}// Only the panes that are NOT on the default login carry a// badge. Labelling every pane "Default Claude Code login" would// be noise for the many; labelling the odd one out is the wholediff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex cf4d5acd89..38159aff1b 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -71,9 +71,7 @@ import {type PaneDropPayload,} from "./paneDrop";import { usePaneFileDrag } from "./paneFileDrag";-import { PaneRecap } from "./PaneRecap";import { attachToTerminal } from "@/lib/agenticIdeApi";-import type { RecapReason, RecapSource } from "@/lib/agenticIdeApi";import { attachTerminalBridge } from "@/lib/editActions";import { robustPaste } from "@/lib/clipboard";import { installPasteBridge } from "./terminalPaste";@@ -105,31 +103,6 @@ export interface SplitAgentChoice {export type SplitDirection = "right" | "down";-/**- * Where a pane's recap came from, kept together rather than as five more props.- *- * None of it changes what the header SAYS — it changes what the card behind the- * header can explain about it, which is the difference between a thin recap and- * a thin recap that tells you no model could be reached to write a better one.- */-export interface PaneRecapMeta {- source?: RecapSource;- reason?: RecapReason;- /** The model that wrote it, when one did. */- writer?: string;- /** What went wrong the last time this pane was summarized. */- note?: string;- /** Unix seconds; 0 for the recap derived from the pane's own output. */- generatedAt?: number;-}--/** What the recap card may do about the recap. Absent leaves it read-only. */-export interface PaneRecapActions {- onSave?: (headline: string, detail: string) => Promise<void>;- onClear?: () => Promise<void>;- onRefresh?: () => Promise<void>;-}-interface AgenticTerminalProps {/** Terminal call-sign — also the WS path segment. */name: string;@@ -153,12 +126,8 @@ interface AgenticTerminalProps {* badge never moves.*/recap?: string;- /** The several-sentence version of `recap`, read in the recap card. */+ /** The one-or-two-sentence version of `recap`, revealed on hover. */recapDetail?: string;- /** Who wrote the recap and why — the card's footer and its explanation. */- recapMeta?: PaneRecapMeta;- /** Rewriting, resetting and re-summarizing it. Absent = read-only card. */- recapActions?: PaneRecapActions;/*** Which subscription this pane runs on ("Work seat"), when that is worth* saying. Undefined for everyone with a single login — the header must not@@ -833,8 +802,6 @@ function PaneHeader({displayName,recap,recapDetail,- recapMeta,- recapActions,accountLabel,appearance,focused,@@ -851,8 +818,6 @@ function PaneHeader({displayName: string;recap?: string;recapDetail?: string;- recapMeta?: PaneRecapMeta;- recapActions?: PaneRecapActions;accountLabel?: string | null;appearance: TerminalAppearance;focused: boolean;@@ -907,15 +872,7 @@ function PaneHeader({displayName={displayName}recap={recap}detail={recapDetail}- source={recapMeta?.source}- reason={recapMeta?.reason}- writer={recapMeta?.writer}- note={recapMeta?.note}- generatedAt={recapMeta?.generatedAt}light={light}- onSave={recapActions?.onSave}- onClear={recapActions?.onClear}- onRefresh={recapActions?.onRefresh}/>{/* Which of several subscriptions this pane is spending. Only renderedwhen the user actually has more than one, so the header stays quiet@@ -1011,6 +968,135 @@ function PaneHeader({);}+/**+ * Is this element showing all of its text, or has CSS clipped it?+ *+ * `scrollWidth > clientWidth` is the only honest answer: whether a sentence fits+ * depends on the pane's width, the font that ended up loading and how long the+ * agent's last line happened to be — none of which can be guessed from the+ * string. Re-measured whenever the text changes or the element is resized, which+ * in a draggable grid of terminals is constantly.+ *+ * Environments without a ResizeObserver (jsdom, very old engines) simply keep+ * the first measurement, which is the behaviour this replaces rather than a+ * regression.+ */+function useIsTruncated(+ ref: React.RefObject<HTMLElement | null>,+ text: string,+): boolean {+ const [truncated, setTruncated] = useState(false);+ useEffect(() => {+ const node = ref.current;+ if (!node) {+ setTruncated(false);+ return;+ }+ // A one-pixel slack: sub-pixel font metrics make scrollWidth exceed+ // clientWidth on text that visibly fits, and a tooltip that appears for+ // nothing is worse than one that occasionally does not.+ const measure = () => setTruncated(node.scrollWidth > node.clientWidth + 1);+ measure();+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(measure);+ observer.observe(node);+ return () => observer.disconnect();+ }, [ref, text]);+ return truncated;+}++/**+ * The pane header's headline: what this session is doing, in one line.+ *+ * Two things happen here and both matter for a grid of eight terminals:+ *+ * 1. **The recap replaces the agent name.** "CLAUDE CODE" is identical on every+ * pane, so as a label it answers nothing; the recap is the part that differs+ * pane to pane. Without one — a pane that has just been opened, or a backend+ * that predates the field — the agent name is shown exactly as before.+ * 2. **The clipped part is one hover away.** A header is a few centimetres wide+ * and a recap is a sentence, so it WILL be cut. The tooltip carries the+ * longer form, and it is offered when the line is actually clipped or when+ * the longer form says more than the line does — never merely because there+ * is text.+ *+ * A native `title` would have been free, but it appears after a browser-chosen+ * delay, renders as unstyled OS chrome, and cannot show the two-part layout+ * (which CLI, then the recap) that makes this readable at a glance.+ */+function PaneRecap({+ name,+ displayName,+ recap,+ detail,+ light,+}: {+ name: string;+ displayName: string;+ recap?: string;+ detail?: string;+ light: boolean;+}) {+ const lineRef = useRef<HTMLSpanElement | null>(null);+ const headline = (recap ?? "").trim();+ const clipped = useIsTruncated(lineRef, headline);++ if (!headline) {+ return (+ <span+ className="truncate text-[11px] uppercase tracking-wider"+ style={{ color: light ? "#77777f" : "#8a8a95" }}+ data-testid={`pane-agent-${name}`}+ >+ {displayName}+ </span>+ );+ }++ const body = (detail ?? "").trim() || headline;+ const showsTooltip = clipped || body !== headline;+ const tipId = `pane-recap-tip-${name}`;++ return (+ <span className="group/recap min-w-0 flex-1">+ <span+ ref={lineRef}+ // Reachable without a mouse: the tooltip opens on focus too, so the+ // clipped half of the sentence is not mouse-only information.+ tabIndex={showsTooltip ? 0 : undefined}+ aria-describedby={showsTooltip ? tipId : undefined}+ className="block truncate rounded-sm text-[11px] leading-tight outline-none focus-visible:ring-1 focus-visible:ring-primary/60"+ style={{ color: light ? "#5f5f68" : "#9b9ba6" }}+ data-testid={`pane-recap-${name}`}+ >+ {headline}+ </span>+ {showsTooltip && (+ /*+ * Positioned against the HEADER, not against this span: the header is+ * the only positioned ancestor that spans the pane, so the card can be+ * wide enough to read without hanging off a narrow pane's edge. The+ * pane clips its own overflow, so a card anchored to a 60 px label+ * would be cut in half.+ */+ <span+ role="tooltip"+ id={tipId}+ data-testid={`pane-recap-tooltip-${name}`}+ className="pointer-events-none absolute left-3 top-full z-50 mt-1 hidden w-max max-w-[calc(100%-1.5rem)] flex-col gap-1 rounded-lg border border-border bg-card p-2.5 text-left shadow-xl group-focus-within/recap:flex group-hover/recap:flex"+ >+ <span className="block text-[10px] uppercase tracking-wider text-muted-foreground">+ {displayName} · {name}+ </span>+ <span className="block text-[11px] leading-relaxed text-foreground">+ {body}+ </span>+ </span>+ )}+ </span>+ );+}+/*** The picker a split button opens: what should run in the new pane?*diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.test.tsxdeleted file mode 100644index 7f4aa36a7c..0000000000--- a/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.test.tsx+++ /dev/null@@ -1,243 +0,0 @@-/**- * The pane header's recap line and the card behind it.- *- * What is pinned here is what the version this replaces got wrong: the long- * form has to be reachable and readable, a thin recap has to say WHY it is- * thin, and the user has to be able to overrule it. The old tooltip failed all- * three — it could not be moved into, it never explained itself, and there was- * nothing to press.- */-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";-import { PaneRecap } from "./PaneRecap";--const BASE = {- name: "Mika",- displayName: "Claude Code",- light: false,-};--describe("the header line", () => {- it("shows the recap in place of the agent name", () => {- render(<PaneRecap {...BASE} recap="Rewrote the auth middleware" />);-- expect(screen.getByTestId("pane-recap-Mika").textContent).toBe(- "Rewrote the auth middleware",- );- expect(screen.queryByTestId("pane-agent-Mika")).toBeNull();- });-- it("keeps showing which CLI runs here until there is a recap", () => {- render(<PaneRecap {...BASE} />);-- expect(screen.getByTestId("pane-agent-Mika").textContent).toBe("Claude Code");- expect(screen.queryByTestId("pane-recap-Mika")).toBeNull();- });-});--describe("the recap card", () => {- it("opens on click and carries the full long form", () => {- render(- <PaneRecap- {...BASE}- recap="Rewrote the auth middleware"- detail="The goal was to fix the failing login test. The session lookup in auth/middleware.py now reads the token once. Two tests still fail."- />,- );-- fireEvent.click(screen.getByTestId("pane-recap-Mika"));-- const card = screen.getByTestId("pane-recap-card-Mika");- expect(card.getAttribute("role")).toBe("dialog");- // The whole point of opening it: the sentence the header clipped, entire.- expect(screen.getByTestId("pane-recap-detail-Mika").textContent).toContain(- "Two tests still fail.",- );- expect(card.textContent).toContain("Claude Code");- });-- it("opens on hover as well, and closes when the pointer leaves", () => {- render(<PaneRecap {...BASE} recap="Rewrote the auth middleware" />);-- const line = screen.getByTestId("pane-recap-Mika");- fireEvent.mouseEnter(line.parentElement!);- expect(screen.getByTestId("pane-recap-card-Mika")).toBeTruthy();- });-- it("closes on Escape", () => {- render(<PaneRecap {...BASE} recap="Rewrote the auth middleware" />);-- fireEvent.click(screen.getByTestId("pane-recap-Mika"));- fireEvent.keyDown(document, { key: "Escape" });-- expect(screen.queryByTestId("pane-recap-card-Mika")).toBeNull();- });-- it("repeats nothing when the long form says what the line says", () => {- render(- <PaneRecap {...BASE} recap="Not started yet." detail="Not started yet." />,- );-- fireEvent.click(screen.getByTestId("pane-recap-Mika"));-- expect(screen.queryByTestId("pane-recap-detail-Mika")).toBeNull();- });-});--describe("why the recap is what it is", () => {- it("says so when nothing could summarize the pane, and what went wrong", () => {- render(- <PaneRecap- {...BASE}- recap="Running pytest"- detail="Working now: Running pytest."- source="heuristic"- reason="unavailable"- note="AuthenticationError: invalid x-api-key"- />,- );-- fireEvent.click(screen.getByTestId("pane-recap-Mika"));-- const why = screen.getByTestId("pane-recap-why-Mika");- expect(why.textContent).toContain("No model could summarize this pane");- // The provider's own words, so a broken key is a fixable fact rather than- // an unexplained thin sentence.- expect(why.textContent).toContain("AuthenticationError");- });-- it("credits the model that wrote it instead of explaining itself", () => {- render(- <PaneRecap- {...BASE}- recap="Rewrote the auth middleware"- detail="Where the work stands."- source="model"- reason="summarized"- writer="claude-opus-5"- generatedAt={Date.now() / 1000 - 30}- />,- );-- fireEvent.click(screen.getByTestId("pane-recap-Mika"));-- const card = screen.getByTestId("pane-recap-card-Mika");- expect(card.textContent).toContain("claude-opus-5");- expect(card.textContent).toContain("30s ago");- // A summary needs no excuse — the footer already says who and when.- expect(screen.queryByTestId("pane-recap-why-Mika")).toBeNull();- });-- it("explains a pane that has printed too little to summarize", () => {- render(- <PaneRecap {...BASE} recap="Running — nothing printed yet." reason="warming" />,- );-- fireEvent.click(screen.getByTestId("pane-recap-Mika"));-- expect(screen.getByTestId("pane-recap-why-Mika").textContent).toContain(- "Too little output so far",- );- });-});--describe("writing the recap yourself", () => {- it("opens the editor from the pencil in the header", async () => {- const onSave = vi.fn().mockResolvedValue(undefined);- render(<PaneRecap {...BASE} recap="Running pytest" onSave={onSave} />);-- fireEvent.click(screen.getByTestId("pane-recap-edit-Mika"));-- const line = screen.getByTestId("pane-recap-input-Mika") as HTMLInputElement;- // Pre-filled with what is on screen: correcting a recap is the common case,- // replacing it from nothing the rare one.- expect(line.value).toBe("Running pytest");-- fireEvent.change(line, { target: { value: "Demo branch — leave alone" } });- fireEvent.change(screen.getByTestId("pane-recap-detail-input-Mika"), {- target: { value: "Recording for the Thursday walkthrough." },- });- fireEvent.click(screen.getByTestId("pane-recap-save-Mika"));-- await waitFor(() =>- expect(onSave).toHaveBeenCalledWith(- "Demo branch — leave alone",- "Recording for the Thursday walkthrough.",- ),- );- });-- it("saves on Ctrl+Enter without reaching for the mouse", async () => {- const onSave = vi.fn().mockResolvedValue(undefined);- render(<PaneRecap {...BASE} recap="Running pytest" onSave={onSave} />);-- fireEvent.click(screen.getByTestId("pane-recap-edit-Mika"));- fireEvent.keyDown(screen.getByTestId("pane-recap-input-Mika"), {- key: "Enter",- ctrlKey: true,- });-- await waitFor(() => expect(onSave).toHaveBeenCalledWith("Running pytest", ""));- });-- it("shows what went wrong rather than closing on a failed save", async () => {- const onSave = vi.fn().mockRejectedValue(new Error("That workspace is not open."));- render(<PaneRecap {...BASE} recap="Running pytest" onSave={onSave} />);-- fireEvent.click(screen.getByTestId("pane-recap-edit-Mika"));- fireEvent.click(screen.getByTestId("pane-recap-save-Mika"));-- await waitFor(() =>- expect(screen.getByTestId("pane-recap-error-Mika").textContent).toContain(- "That workspace is not open.",- ),- );- // The text is still in the editor: a failed save must not eat what was typed.- expect(screen.getByTestId("pane-recap-input-Mika")).toBeTruthy();- });-- it("leaves the pencil off a card that cannot be edited", () => {- render(<PaneRecap {...BASE} recap="Running pytest" />);-- expect(screen.queryByTestId("pane-recap-edit-Mika")).toBeNull();- });-});--describe("the card's actions", () => {- it("offers a refresh on an automatic recap", async () => {- const onRefresh = vi.fn().mockResolvedValue(undefined);- render(- <PaneRecap {...BASE} recap="Running pytest" source="model" onRefresh={onRefresh} />,- );-- fireEvent.click(screen.getByTestId("pane-recap-Mika"));- fireEvent.click(screen.getByTestId("pane-recap-refresh-Mika"));-- await waitFor(() => expect(onRefresh).toHaveBeenCalled());- // The card stays open — you asked for a new sentence, you want to read it.- expect(screen.getByTestId("pane-recap-card-Mika")).toBeTruthy();- });-- it("offers a reset instead once the user has written one", async () => {- const onClear = vi.fn().mockResolvedValue(undefined);- const onRefresh = vi.fn().mockResolvedValue(undefined);- render(- <PaneRecap- {...BASE}- recap="Demo branch — leave alone"- source="user"- reason="pinned"- onClear={onClear}- onRefresh={onRefresh}- />,- );-- fireEvent.click(screen.getByTestId("pane-recap-Mika"));-- expect(screen.queryByTestId("pane-recap-refresh-Mika")).toBeNull();- fireEvent.click(screen.getByTestId("pane-recap-reset-Mika"));-- await waitFor(() => expect(onClear).toHaveBeenCalled());- expect(onRefresh).not.toHaveBeenCalled();- });-});diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.tsxdeleted file mode 100644index 62f8cd33aa..0000000000--- a/jarvis/ui/web/frontend/src/components/agentic/PaneRecap.tsx+++ /dev/null@@ -1,642 +0,0 @@-/**- * The pane header's headline — what this session is doing — and the card behind- * it.- *- * ## What was wrong with the version this replaces- *- * The header line itself was never the problem: a header is a few centimetres- * wide, a recap is a sentence, and CSS clipping it is correct. The problem was- * everything around that:- *- * * **The long form was unreadable.** It lived in a CSS-only hover tooltip- * anchored inside the pane, capped at the pane's own width. On a quarter of a- * screen that is a column of 11 px text a dozen characters wide — the text- * was all there and none of it could be read.- * * **It could not be touched.** `pointer-events-none` meant the moment you- * moved the mouse toward it, it vanished. Nothing in it could be selected,- * copied, or clicked.- * * **A thin recap never explained itself.** The backend has always known- * whether a model wrote the line or the string rules did, and why not the- * model — that never reached the screen, so "the recaps are not meaningful"- * had no visible cause.- * * **It could not be corrected.** No summarizer knows that a pane is "the- * branch I'm about to demo" or "leave this one alone".- *- * So the long form is a real card now: rendered in a portal so the pane's own- * `overflow: hidden` cannot clip it, wide enough to read a paragraph in, given- * the app's card surface rather than a bespoke one, and interactive — it says- * who wrote the recap and when, it can be refreshed, and the pencil lets the- * user write the header themselves.- *- * ## Why a portal- *- * A pane clips its own content; that is what makes a grid of terminals a grid.- * Anything anchored inside a pane is therefore bounded by it, and a recap card- * bounded by a narrow pane is the unreadable column described above. Fixed- * positioning off the trigger's rect is the only placement that can be as wide- * as the sentence needs while still pointing at the pane it belongs to.- */-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";-import { createPortal } from "react-dom";-import { Loader2, Pencil, RotateCw, Sparkles, Terminal, User, X } from "lucide-react";-import { cn } from "@/lib/utils";-import type { RecapReason, RecapSource } from "@/lib/agenticIdeApi";--/** How wide the card gets before it starts wrapping, and its floor on a phone. */-const CARD_WIDTH = 440;-const VIEWPORT_MARGIN = 12;-/**- * Room the card needs below the header before it opens downwards. Below this it- * flips above the pane instead — a card that opens off the bottom of the window- * is the same unreadable as one clipped by the pane.- */-const ROOM_NEEDED = 260;-/**- * How long the card survives the pointer leaving it. Long enough to cross the- * gap between the header line and the card, short enough that brushing past a- * pane on the way somewhere else does not leave a card hanging.- */-const CLOSE_DELAY_MS = 160;--/** The same two caps the backend enforces, so the counter cannot lie. */-export const MAX_HEADLINE = 200;-export const MAX_DETAIL = 2000;--/**- * Why the recap on screen is the one on screen, in a sentence.- *- * Every key here was a silent early return in the backend's scheduler. Saying- * them out loud is the entire fix for "the recap is thin and nobody knows why".- * `summarized` is deliberately absent: the footer already names the model that- * wrote it and how long ago, and repeating that in a sentence is noise.- */-const WHY: Partial<Record<RecapReason, string>> = {- pinned: "You wrote this. It stays until you reset it.",- disabled:- "Model recaps are switched off, so this is read from the pane's own output.",- not_started: "Nothing is running in this pane yet, so there is nothing to summarize.",- warming:- "Too little output so far to summarize — this line is read from the pane's own output.",- working: "A summary is being written now. This line is read from the pane's own output.",- queued:- "Waiting its turn to be summarized. This line is read from the pane's own output.",- unavailable:- "No model could summarize this pane, so this line is read from its own output.",-};--/** What the footer badge says about who wrote the sentence above it. */-function credit(source: RecapSource, writer: string): { label: string; icon: JSX.Element } {- if (source === "user")- return { label: "Written by you", icon: <User className="h-3 w-3" /> };- if (source === "model")- return {- label: writer ? `Summarized by ${writer}` : "Summarized by a model",- icon: <Sparkles className="h-3 w-3" />,- };- return { label: "Read from the output", icon: <Terminal className="h-3 w-3" /> };-}--/** "34s ago" / "6 min ago" — the same wording the backend uses for idle time. */-function ago(at: number): string {- if (!at) return "";- const seconds = Math.max(0, Math.round(Date.now() / 1000 - at));- if (seconds < 60) return `${seconds}s ago`;- if (seconds < 3600) return `${Math.floor(seconds / 60)} min ago`;- return `${Math.floor(seconds / 3600)} h ago`;-}--interface Anchor {- left: number;- width: number;- /** One of the two is set: the card hangs below the header, or above it. */- top?: number;- bottom?: number;-}--/** Where the card goes, measured off the header line it belongs to. */-function anchorTo(node: HTMLElement | null): Anchor | null {- if (!node || typeof window === "undefined") return null;- const rect = node.getBoundingClientRect();- const width = Math.min(CARD_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2);- const left = Math.max(- VIEWPORT_MARGIN,- Math.min(rect.left, window.innerWidth - width - VIEWPORT_MARGIN),- );- const below = window.innerHeight - rect.bottom;- if (below < ROOM_NEEDED && rect.top > below) {- return { left, width, bottom: window.innerHeight - rect.top + 6 };- }- return { left, width, top: rect.bottom + 6 };-}--export interface PaneRecapProps {- /** The pane's call-sign — "Mika". */- name: string;- /** The coding CLI behind it — "Claude Code". */- displayName: string;- recap?: string;- detail?: string;- source?: RecapSource;- reason?: RecapReason;- writer?: string;- /** What went wrong the last time this pane was summarized, if anything. */- note?: string;- /** When the model wrote it, or when the user did. Unix seconds; 0 for derived. */- generatedAt?: number;- light: boolean;- /** Write this pane's recap. Absent leaves the pencil off the header. */- onSave?: (headline: string, detail: string) => Promise<void>;- /** Hand the pane back to the automatic recap. */- onClear?: () => Promise<void>;- /** Read the pane again and summarize it now. */- onRefresh?: () => Promise<void>;-}--export function PaneRecap({- name,- displayName,- recap,- detail,- source = "heuristic",- reason = "",- writer = "",- note = "",- generatedAt = 0,- light,- onSave,- onClear,- onRefresh,-}: PaneRecapProps) {- const lineRef = useRef<HTMLButtonElement | null>(null);- const cardRef = useRef<HTMLDivElement | null>(null);- const closeTimer = useRef<number | null>(null);- /**- * When the card was last dismissed on purpose.- *- * Escape returns focus to the header line, and the header line opens the card- * on focus — so without this, dismissing it re-opens it immediately. The same- * guard covers the pointer that is still resting on the line after a click.- */- const dismissedAt = useRef(0);-- const [open, setOpen] = useState(false);- /** Opened by a click rather than by hovering: it stays until dismissed. */- const [sticky, setSticky] = useState(false);- const [editing, setEditing] = useState(false);- const [busy, setBusy] = useState<"save" | "clear" | "refresh" | null>(null);- const [failure, setFailure] = useState("");- const [anchor, setAnchor] = useState<Anchor | null>(null);-- const headline = (recap ?? "").trim();- const body = (detail ?? "").trim();-- const cancelClose = useCallback(() => {- if (closeTimer.current !== null) {- window.clearTimeout(closeTimer.current);- closeTimer.current = null;- }- }, []);-- const close = useCallback(() => {- cancelClose();- dismissedAt.current = Date.now();- setOpen(false);- setSticky(false);- setEditing(false);- setFailure("");- }, [cancelClose]);-- /** Leaving the trigger or the card closes it — unless it was clicked open. */- const closeSoon = useCallback(() => {- if (sticky || editing) return;- cancelClose();- closeTimer.current = window.setTimeout(() => setOpen(false), CLOSE_DELAY_MS);- }, [cancelClose, editing, sticky]);-- const reveal = useCallback(() => {- // Dismissing means dismissed: neither the focus Escape hands back to the- // header line nor a pointer still resting on it may spring the card open- // again in the same breath.- if (Date.now() - dismissedAt.current < 250) return;- cancelClose();- setAnchor(anchorTo(lineRef.current));- setOpen(true);- }, [cancelClose]);-- useEffect(() => () => cancelClose(), [cancelClose]);-- // The card is positioned in viewport coordinates, so anything that moves the- // pane underneath it — scrolling the workspace, resizing the window, dragging- // the prompt bar's seam — has to move the card with it.- useLayoutEffect(() => {- if (!open) return;- const track = () => setAnchor(anchorTo(lineRef.current));- track();- window.addEventListener("resize", track);- window.addEventListener("scroll", track, true);- return () => {- window.removeEventListener("resize", track);- window.removeEventListener("scroll", track, true);- };- }, [open]);-- // Escape closes, and a click anywhere outside dismisses a card that was- // clicked open. Bound only while it IS open, so a grid of eight panes is not- // eight permanent document listeners.- useEffect(() => {- if (!open) return;- const onKey = (event: KeyboardEvent) => {- if (event.key === "Escape") {- event.stopPropagation();- close();- lineRef.current?.focus();- }- };- const onDown = (event: MouseEvent) => {- const target = event.target as Node;- if (cardRef.current?.contains(target) || lineRef.current?.contains(target)) return;- close();- };- document.addEventListener("keydown", onKey, true);- document.addEventListener("mousedown", onDown);- return () => {- document.removeEventListener("keydown", onKey, true);- document.removeEventListener("mousedown", onDown);- };- }, [close, open]);-- // A pane with nothing to say yet keeps showing which CLI it runs, exactly as- // it did before recaps existed. Inventing a sentence for it would be noise.- if (!headline) {- return (- <span- className="truncate text-[11px] uppercase tracking-wider"- style={{ color: light ? "#77777f" : "#8a8a95" }}- data-testid={`pane-agent-${name}`}- >- {displayName}- </span>- );- }-- const run = async (kind: "save" | "clear" | "refresh", action: () => Promise<void>) => {- setBusy(kind);- setFailure("");- try {- await action();- if (kind !== "refresh") setEditing(false);- } catch (error) {- setFailure(error instanceof Error ? error.message : String(error));- } finally {- setBusy(null);- }- };-- const tipId = `pane-recap-card-${name}`;-- return (- <span- className="flex min-w-0 flex-1 items-center gap-1"- onMouseEnter={reveal}- onMouseLeave={closeSoon}- >- <button- ref={lineRef}- type="button"- aria-expanded={open}- aria-controls={open ? tipId : undefined}- aria-label={`What ${name} is doing`}- data-testid={`pane-recap-${name}`}- onFocus={reveal}- onBlur={closeSoon}- onMouseDown={(e) => e.stopPropagation()}- onClick={(e) => {- e.stopPropagation();- if (sticky) close();- else {- setSticky(true);- reveal();- }- }}- className="block min-w-0 flex-1 truncate rounded-sm text-left text-[11px] leading-tight outline-none transition-colors hover:text-foreground focus-visible:ring-1 focus-visible:ring-primary/60"- style={{ color: light ? "#5f5f68" : "#9b9ba6" }}- >- {headline}- </button>-- {/* The pencil. Quiet until the header is hovered or something in it has- focus, like every other pane action — but it is the affordance the- whole editing feature hangs off, so it is never more than a hover- away, and it stays lit while the card it opened is open. */}- {onSave && (- <button- type="button"- aria-label={`Write ${name}'s recap yourself`}- title={`Write ${name}'s recap yourself`}- data-testid={`pane-recap-edit-${name}`}- onMouseDown={(e) => e.stopPropagation()}- onClick={(e) => {- e.stopPropagation();- setSticky(true);- setEditing(true);- reveal();- }}- className={cn(- "flex h-5 w-5 shrink-0 items-center justify-center rounded transition-all",- light ? "hover:bg-black/10" : "hover:bg-white/10",- open- ? "opacity-100"- : "opacity-0 focus-visible:opacity-100 group-hover/header:opacity-100",- )}- style={{ color: light ? "#6b6b73" : "#9a9aa5" }}- >- <Pencil className="h-3 w-3" />- </button>- )}-- {open &&- anchor &&- typeof document !== "undefined" &&- createPortal(- <div- ref={cardRef}- id={tipId}- role="dialog"- aria-label={`What ${name} is doing`}- data-testid={`pane-recap-card-${name}`}- onMouseEnter={cancelClose}- onMouseLeave={closeSoon}- onMouseDown={(e) => e.stopPropagation()}- style={{- position: "fixed",- left: anchor.left,- width: anchor.width,- ...(anchor.top !== undefined- ? { top: anchor.top }- : { bottom: anchor.bottom }),- }}- className="z-[60] flex flex-col gap-2.5 rounded-xl border border-border bg-card/95 p-3.5 text-left shadow-2xl backdrop-blur-sm"- >- <div className="flex items-center justify-between gap-2">- <span className="min-w-0 truncate text-[10px] uppercase tracking-[0.14em] text-muted-foreground">- {name} · {displayName}- </span>- <button- type="button"- aria-label="Close"- data-testid={`pane-recap-close-${name}`}- onClick={close}- className="-mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"- >- <X className="h-3 w-3" />- </button>- </div>-- {editing ? (- <RecapEditor- name={name}- headline={headline}- detail={body}- saving={busy === "save"}- onCancel={() => {- setEditing(false);- setFailure("");- }}- onSave={(nextHeadline, nextDetail) =>- void run("save", () => onSave!(nextHeadline, nextDetail))- }- />- ) : (- <>- {/* The headline in FULL. The header clips it; this is the- place it is allowed to wrap, which is the whole reason- somebody opened the card. */}- <p- className="text-[13px] font-medium leading-snug text-foreground"- data-testid={`pane-recap-headline-${name}`}- >- {headline}- </p>- {body && body !== headline && (- <p- className="max-h-[40vh] overflow-y-auto whitespace-pre-line text-[12.5px] leading-relaxed text-muted-foreground"- data-testid={`pane-recap-detail-${name}`}- >- {body}- </p>- )}- {WHY[reason] && (- <p- className="rounded-lg bg-muted/50 px-2.5 py-1.5 text-[11px] leading-relaxed text-muted-foreground"- data-testid={`pane-recap-why-${name}`}- >- {WHY[reason]}- {note && <span className="mt-1 block opacity-70">{note}</span>}- </p>- )}- </>- )}-- {failure && (- <p- className="text-[11px] leading-relaxed text-destructive"- data-testid={`pane-recap-error-${name}`}- >- {failure}- </p>- )}-- {!editing && (- <div className="flex items-center justify-between gap-2 border-t border-border/60 pt-2">- <span className="flex min-w-0 items-center gap-1.5 text-[10px] text-muted-foreground">- {credit(source, writer).icon}- <span className="truncate">{credit(source, writer).label}</span>- {generatedAt > 0 && (- <span className="shrink-0 opacity-70">· {ago(generatedAt)}</span>- )}- </span>- <span className="flex shrink-0 items-center gap-1">- {onSave && (- <CardAction- label="Write it yourself"- testId={`pane-recap-card-edit-${name}`}- onClick={() => {- setSticky(true);- setEditing(true);- }}- >- <Pencil className="h-3 w-3" />- </CardAction>- )}- {source === "user" && onClear ? (- <CardAction- label="Back to the automatic recap"- testId={`pane-recap-reset-${name}`}- busy={busy === "clear"}- onClick={() => void run("clear", onClear)}- >- <RotateCw className="h-3 w-3" />- </CardAction>- ) : (- onRefresh && (- <CardAction- label="Summarize this pane again"- testId={`pane-recap-refresh-${name}`}- busy={busy === "refresh"}- onClick={() => void run("refresh", onRefresh)}- >- <RotateCw className="h-3 w-3" />- </CardAction>- )- )}- </span>- </div>- )}- </div>,- document.body,- )}- </span>- );-}--function CardAction({- label,- testId,- busy = false,- onClick,- children,-}: {- label: string;- testId: string;- busy?: boolean;- onClick: () => void;- children: React.ReactNode;-}) {- return (- <button- type="button"- aria-label={label}- title={label}- data-testid={testId}- disabled={busy}- onClick={(e) => {- e.stopPropagation();- onClick();- }}- className="flex h-6 items-center gap-1 rounded-md px-1.5 text-[10px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40"- >- {busy ? <Loader2 className="h-3 w-3 animate-spin" /> : children}- </button>- );-}--/**- * Writing a pane's recap by hand.- *- * Two fields rather than one, because the recap is two things: the clause the- * header shows and the paragraph the card shows. Somebody labelling a pane- * "don't touch — demo branch" wants only the first; somebody recording where- * they left off wants both, and being made to cram that into one line is how a- * good note becomes a bad one.- */-function RecapEditor({- name,- headline,- detail,- saving,- onSave,- onCancel,-}: {- name: string;- headline: string;- detail: string;- saving: boolean;- onSave: (headline: string, detail: string) => void;- onCancel: () => void;-}) {- const [line, setLine] = useState(headline);- const [body, setBody] = useState(detail);- const firstRef = useRef<HTMLInputElement | null>(null);-- useEffect(() => {- firstRef.current?.focus();- firstRef.current?.select();- }, []);-- const submit = () => {- if (!saving) onSave(line.trim(), body.trim());- };-- // Ctrl/Cmd+Enter saves from either field: the detail box takes plain Enter as- // a newline, so there has to be a way to finish without reaching for a mouse.- const onKeyDown = (event: React.KeyboardEvent) => {- if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {- event.preventDefault();- submit();- }- };-- return (- <div className="flex flex-col gap-2">- <label className="flex flex-col gap-1">- <span className="text-[10px] uppercase tracking-wider text-muted-foreground">- Header line- </span>- <input- ref={firstRef}- value={line}- maxLength={MAX_HEADLINE}- placeholder="What this pane is for"- data-testid={`pane-recap-input-${name}`}- onChange={(e) => setLine(e.target.value)}- onKeyDown={onKeyDown}- className="w-full rounded-lg border border-border bg-background px-2.5 py-1.5 text-[12.5px] text-foreground outline-none focus:border-primary/60"- />- </label>- <label className="flex flex-col gap-1">- <span className="text-[10px] uppercase tracking-wider text-muted-foreground">- The longer version <span className="opacity-60">— optional</span>- </span>- <textarea- value={body}- rows={4}- maxLength={MAX_DETAIL}- placeholder="Where the work stands, what is outstanding…"- data-testid={`pane-recap-detail-input-${name}`}- onChange={(e) => setBody(e.target.value)}- onKeyDown={onKeyDown}- className="w-full resize-y rounded-lg border border-border bg-background px-2.5 py-1.5 text-[12.5px] leading-relaxed text-foreground outline-none focus:border-primary/60"- />- </label>- <div className="flex items-center justify-between gap-2">- <span className="text-[10px] text-muted-foreground">- {/* An empty header line is how you clear a hand-written recap, and- saying so beats a disabled Save nobody can explain. */}- {line.trim()- ? "⌘/Ctrl + Enter to save"- : "Save with an empty line to go back to the automatic recap"}- </span>- <span className="flex items-center gap-1.5">- <button- type="button"- onClick={onCancel}- data-testid={`pane-recap-cancel-${name}`}- className="rounded-md px-2 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"- >- Cancel- </button>- <button- type="button"- onClick={submit}- disabled={saving}- data-testid={`pane-recap-save-${name}`}- className="flex items-center gap-1 rounded-md bg-primary/20 px-2.5 py-1 text-[11px] font-medium text-primary transition-colors hover:bg-primary/30 disabled:opacity-50"- >- {saving && <Loader2 className="h-3 w-3 animate-spin" />}- Save- </button>- </span>- </div>- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex bfd2f56b72..6cfbcf18da 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -99,64 +99,6 @@ export interface TerminalState {account?: string | null;/** Its display name, so the pane header can show it without a second lookup. */account_label?: string | null;- /**- * What this pane is doing, in one clause — the pane header's label.- *- * Only the OPENING value: the state is fetched when the workspace changes,- * and a recap goes stale in seconds. `fetchTerminalRecaps` keeps it current.- */- recap?: string;- /** The one-or-two-sentence version, shown when the header line is hovered. */- recap_detail?: string;-}--/**- * Who wrote the recap on screen.- *- * `"user"` outranks both machines: a pane the user has labelled themselves- * keeps that label until they clear it.- */-export type RecapSource = "user" | "model" | "heuristic";--/**- * Why this recap and not a better one.- *- * The field exists because "the recap is thin and nobody knows why" was the- * actual complaint: every value here used to be a silent early return in the- * backend's scheduler, and the card turns it into a sentence.- */-export type RecapReason =- | "pinned"- | "summarized"- | "disabled"- | "not_started"- | "warming"- | "working"- | "queued"- | "unavailable"- | "";--/** One pane's live recap, as `/recaps` reports it. */-export interface TerminalRecap {- key: string;- name: string;- status: string;- recap: string;- recap_detail: string;- source?: RecapSource;- reason?: RecapReason;- /** The model that wrote it, when one did. */- writer?: string;- /** What went wrong the last time this pane was summarized. */- note?: string;- /** When the model wrote it, or when the user did. 0 for the derived one. */- generated_at?: number;-}--export interface RecapsResponse {- /** Which workspace answered; null when none is on screen. */- workspace_id: string | null;- terminals: TerminalRecap[];}export interface SessionState {@@ -300,83 +242,6 @@ export function fetchIdeAgents(): Promise<AgentsResponse> {return getJson<AgentsResponse>("/api/agentic-ide/agents");}-/**- * What each pane of a workspace is doing right now.- *- * Deliberately its own read rather than part of `fetchIdeState`: the layout- * changes when a pane is opened or closed, the recaps change whenever an agent- * prints a line. Polling the full state often enough for the second would- * re-send the whole workspace to update one sentence.- */-export function fetchTerminalRecaps(- workspaceId?: string,-): Promise<RecapsResponse> {- const query = workspaceId- ? `?workspace_id=${encodeURIComponent(workspaceId)}`- : "";- return getJson<RecapsResponse>(`/api/agentic-ide/recaps${query}`);-}--function recapUrl(name: string, workspaceId?: string, suffix = ""): string {- const query = workspaceId- ? `?workspace_id=${encodeURIComponent(workspaceId)}`- : "";- return `/api/agentic-ide/terminals/${encodeURIComponent(name)}/recap${suffix}${query}`;-}--async function recapCall(- url: string,- init: RequestInit,-): Promise<TerminalRecap> {- const res = await fetch(url, { cache: "no-store", ...init });- if (!res.ok) throw new Error(await detail(res));- return (await res.json()) as TerminalRecap;-}--/**- * Write a pane's recap yourself.- *- * Neither the model nor the string rules can know what YOU are keeping a pane- * for — "the branch I'm about to demo", "leave this one alone". What is written- * here wins over both and stops the background summarizer re-describing that- * pane until it is cleared.- */-export function setTerminalRecap(- name: string,- recap: string,- recapDetail: string,- workspaceId?: string,-): Promise<TerminalRecap> {- return recapCall(recapUrl(name, workspaceId), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ recap, recap_detail: recapDetail }),- });-}--/** Drop a hand-written recap and hand the pane back to the automatic one. */-export function clearTerminalRecap(- name: string,- workspaceId?: string,-): Promise<TerminalRecap> {- return recapCall(recapUrl(name, workspaceId), { method: "DELETE" });-}--/**- * Read the pane again and write a fresh recap, waiting for it.- *- * The background summarizer is lazy on purpose — right for a header nobody is- * looking at, wrong the moment somebody is. This skips its cooldown. It never- * fails because of the model: no key or an unreachable provider comes back as- * the derived recap with `reason: "unavailable"`.- */-export function refreshTerminalRecap(- name: string,- workspaceId?: string,-): Promise<TerminalRecap> {- return recapCall(recapUrl(name, workspaceId, "/refresh"), { method: "POST" });-}-export function fetchFolders(path?: string | null): Promise<FoldersResponse> {const query = path ? `?path=${encodeURIComponent(path)}` : "";return getJson<FoldersResponse>(`/api/agentic-ide/folders${query}`);diff --git a/tests/unit/agentic_ide/test_recap.py b/tests/unit/agentic_ide/test_recap.pyindex 1ecece7c17..a0bec40bf9 100644--- a/tests/unit/agentic_ide/test_recap.py+++ b/tests/unit/agentic_ide/test_recap.py@@ -33,29 +33,16 @@ def test_a_fresh_pane_says_it_has_not_started() -> None:assert recap.detail-def test_the_instruction_beats_the_last_printed_row() -> None:- """What the pane was ASKED to do leads; the row it printed is a fragment.-- This ordering is the whole lesson of the first recap that shipped: opening- with the newest readable row put "without interrupting Claude's current- work" in the header of a pane that had just written a design document.- """+def test_the_headline_reports_what_the_pane_last_printed() -> None:+ """The freshest signal wins: output beats the instruction that caused it."""term = _pane(status="live", last_prompt="Fix the failing login test")term.transcript.feed("Running pytest tests/unit/test_login.py\r\n")recap = summarize(term)- assert "Fix the failing login test" in recap.headline- # ...and what it printed is still there, in the longer form.- assert "Running pytest tests/unit/test_login.py" in recap.detail---def test_the_headline_reports_the_last_printed_row_when_nothing_was_asked() -> None:- """A pane nobody briefed still says something, from what it printed."""- term = _pane(status="live")- term.transcript.feed("Running pytest tests/unit/test_login.py\r\n")-- assert summarize(term).headline == "Running pytest tests/unit/test_login.py"+ assert recap.headline == "Running pytest tests/unit/test_login.py"+ # ...and the instruction is still there, in the longer form.+ assert "Fix the failing login test" in recap.detaildef test_a_live_pane_that_printed_nothing_falls_back_to_its_instruction() -> None:@@ -142,77 +129,8 @@ def test_a_pane_serializes_its_recap_for_the_ui() -> None:data = term.to_dict()- assert "Ship the release" in data["recap"]- assert "Tagging v2.4.0" in data["recap_detail"]---def test_the_headline_quotes_the_job_rather_than_the_briefs_scaffolding() -> None:- """The reported bug: headers that read "## Task" or "Context:".-- A prompt that arrives from the composer is a structured markdown brief, and- quoting its FIRST line quoted the heading above the work instead of the- work. Every pane the composer had written for therefore had a header that- named the shape of the document and nothing about the job.- """- term = _pane(- status="live",- last_prompt=(- "# Task\n"- "\n"- "Replace the session lookup in auth/middleware.py so the token is\n"- "read once per request.\n"- "\n"- "## Context\n"- "The login suite has been red since Tuesday.\n"- ),- )-- headline = summarize(term).headline-- assert headline.startswith("Replace the session lookup")- assert "#" not in headline- assert "Task" not in headline---def test_a_label_on_the_same_line_as_the_job_keeps_only_the_job() -> None:- term = _pane(status="live", last_prompt="Task: fix the failing login test")-- assert summarize(term).headline == "fix the failing login test"---def test_a_brief_of_nothing_but_labels_still_says_something() -> None:- """Better the label than a blank header — it is what the pane was sent."""- term = _pane(status="live", last_prompt="## Instructions\n\n---\n")-- assert summarize(term).headline == "Instructions"---def test_the_headline_carries_the_job_without_framing_it() -> None:- """A header is a few centimetres wide; ten characters of "Working on:" is- ten characters of the answer pushed past the ellipsis."""- term = _pane(status="live", last_prompt="Fix the failing login test")- term.transcript.feed("Running pytest\r\n")-- recap = summarize(term)-- assert recap.headline == "Fix the failing login test"- # The long form still says which of the two the sentence is.- assert 'Last asked to: "Fix the failing login test"' in recap.detail---def test_the_long_form_keeps_a_long_instruction_readable() -> None:- """The old 80-character cap cut the instruction in the CARD as well, which- is the one place there was room to read it."""- brief = (- "Work out why the wake word goes deaf after a GPU hot-swap and write "- "the finding up in docs/local-wakeword/, with the measurements that "- "support it"- )- term = _pane(status="live", last_prompt=brief)-- detail = summarize(term).detail-- assert "docs/local-wakeword/" in detail+ assert data["recap"] == "Tagging v2.4.0"+ assert "Ship the release" in data["recap_detail"]def test_summarize_survives_a_pane_without_a_transcript() -> None:diff --git a/tests/unit/agentic_ide/test_recap_engine.py b/tests/unit/agentic_ide/test_recap_engine.pydeleted file mode 100644index 73181a1ffe..0000000000--- a/tests/unit/agentic_ide/test_recap_engine.py+++ /dev/null@@ -1,354 +0,0 @@-"""The model-written pane recap, and the promises it makes around the model.--The summary itself is a model's sentence, so what is testable here is-everything around it: that a pane always has a recap even when nothing can be-summarized, that a summary is asked for only when something has actually-happened, that the model's answer is read back forgivingly, and that no failure-path reaches the state read a pane header depends on.-"""--from __future__ import annotations--import asyncio-import time--import pytest--from jarvis.agentic_ide import recap_engine-from jarvis.agentic_ide.session import Terminal--[email protected](autouse=True)-def _clean():- recap_engine.reset_for_tests()- yield- recap_engine.reset_for_tests()---def _pane(lines: int = 0, **changes: object) -> Terminal:- term = Terminal(- key="mika",- name="Mika",- agent="claude",- display_name="Claude Code",- index=0,- status="live",- )- for field, value in changes.items():- setattr(term, field, value)- for number in range(lines):- term.transcript.feed(f"Step {number}: reading jarvis/core/config.py\r\n")- return term---def _rows(count: int) -> list[str]:- return [f"Step {number}: reading jarvis/core/config.py" for number in range(count)]---# --------------------------------------------------------------- the fallback---def test_a_pane_with_no_summary_yet_still_has_a_recap() -> None:- """The deterministic recap is the floor, and it is never absent."""- term = _pane(lines=3, last_prompt="Fix the failing login test")-- answer = recap_engine.recap_for(term, lines=term.transcript.lines())-- assert answer.source == recap_engine.BY_RULES- assert "Fix the failing login test" in answer.headline---def test_a_summarized_pane_reports_the_model_sentence() -> None:- term = _pane(lines=3)- state = recap_engine._state(term.key) # noqa: SLF001 - the cache under test- state.headline = "Wrote the swap analysis, not committed"- state.detail = "The document is at docs/plans/agentic-ide-terminal-swap.md."- state.generated_at = time.time()-- answer = recap_engine.recap_for(term, lines=[])-- assert answer.source == recap_engine.BY_MODEL- assert answer.headline == "Wrote the swap analysis, not committed"---def test_a_closed_pane_forgets_its_recap() -> None:- """Pane keys are reused, so a new pane must not inherit the old sentence."""- term = _pane()- recap_engine._state(term.key).headline = "Old news" # noqa: SLF001-- recap_engine.forget(term.key)-- assert recap_engine.recap_for(term, lines=[]).source == recap_engine.BY_RULES---# ------------------------------------------------------------- when it refreshes---def test_a_pane_with_news_is_scheduled_for_a_summary(monkeypatch) -> None:- """The positive case: enough new output, and a background summary starts."""- monkeypatch.setattr(recap_engine, "_enabled", lambda: True)-- async def scenario() -> None:- async def answer(*_args: object, **_kwargs: object) -> recap_engine.SmartRecap:- return recap_engine.SmartRecap("Ran the login tests", "Three fail.")-- monkeypatch.setattr(recap_engine, "summarize_with_model", answer)- term = _pane(lines=40)- recap_engine.refresh_soon(term, lines=_rows(40))- assert recap_engine._tasks # noqa: SLF001 - a task really was created- await asyncio.gather(*list(recap_engine._tasks)) # noqa: SLF001- assert recap_engine.recap_for(term, lines=[]).headline == "Ran the login tests"-- asyncio.run(scenario())---def test_a_quiet_pane_is_not_summarized_again(monkeypatch) -> None:- """A repainting spinner is not news; re-summarizing it would just cost."""- monkeypatch.setattr(recap_engine, "_enabled", lambda: True)-- async def scenario() -> None:- term = _pane(lines=30)- rows = _rows(30)- state = recap_engine._state(term.key) # noqa: SLF001- state.headline = "Already known"- state.generated_at = time.time()- state.lines_at = len(rows)- state.prompts_at = 0- state.status_at = "live"-- recap_engine.refresh_soon(term, lines=rows)-- assert not recap_engine._tasks # noqa: SLF001-- asyncio.run(scenario())---def test_a_pane_that_has_printed_almost_nothing_is_left_to_the_rules() -> None:- """Below a few readable rows there is nothing a model could add."""- term = _pane(lines=2)-- assert not recap_engine._worth_summarizing(term, 2) # noqa: SLF001- assert recap_engine._worth_summarizing(term, 40) # noqa: SLF001---def test_a_pane_that_could_not_start_is_left_to_the_rules() -> None:- """A pane that says "Claude Code is not on PATH" needs no model."""- term = _pane(lines=30, status="error", error="Claude Code is not on PATH.")-- assert not recap_engine._worth_summarizing(term, 30) # noqa: SLF001---def test_a_new_instruction_makes_a_pane_worth_re_reading() -> None:- term = _pane(lines=30, prompts_sent=2)- state = recap_engine._state(term.key) # noqa: SLF001- state.generated_at = time.time()- state.lines_at = 30- state.prompts_at = 1- state.status_at = "live"-- assert recap_engine._material_change(term, state, 30) # noqa: SLF001---def test_the_switch_turns_the_model_off(monkeypatch) -> None:- """Off means off — the deterministic recap, and no scheduling at all."""- monkeypatch.setattr(recap_engine, "_enabled", lambda: False)-- async def scenario() -> None:- recap_engine.refresh_soon(_pane(lines=40), lines=_rows(40))- assert not recap_engine._tasks # noqa: SLF001-- asyncio.run(scenario())---def test_scheduling_outside_an_event_loop_is_a_no_op() -> None:- """A CLI state dump has no loop; it gets the rules and no exception."""- recap_engine.refresh_soon(_pane(lines=40), lines=_rows(40))-- assert recap_engine.recap_for(_pane(lines=40), lines=[]).source == recap_engine.BY_RULES---def test_scheduling_never_raises(monkeypatch) -> None:- """A recap must never be the thing that breaks a workspace read."""-- def boom() -> bool:- raise RuntimeError("config is on fire")-- monkeypatch.setattr(recap_engine, "_enabled", boom)-- recap_engine.refresh_soon(_pane(lines=40), lines=_rows(40)) # must not raise---# ----------------------------------------------------------------- the prompt---def test_the_prompt_carries_the_instruction_and_the_newest_rows() -> None:- 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 "C:/repo" in prompt---def test_a_pane_nobody_briefed_says_so_in_the_prompt() -> None:- prompt = recap_engine.build_prompt(_pane(), _rows(10))-- assert "not been sent an instruction" in prompt---def test_the_prompt_asks_for_the_interface_language(monkeypatch) -> None:- """The header sits among UI labels, so it follows the interface language."""- monkeypatch.setattr(recap_engine, "_ui_language", lambda: "de")-- assert "Write both lines in German." in recap_engine.build_prompt(_pane(), _rows(10))---def test_an_unknown_interface_language_falls_back_to_english(monkeypatch) -> None:- """A locale a newer build introduced must not produce an empty instruction."""- monkeypatch.setattr(recap_engine, "_ui_language", lambda: "fr")-- assert "Write both lines in English." in recap_engine.build_prompt(_pane(), _rows(10))---# ------------------------------------------------------------ reading the answer---def test_the_two_labelled_lines_are_read_back() -> None:- answer = recap_engine.parse_answer(- "HEADLINE: Swap-analysis document written, not committed\n"- "DETAIL: The goal was an analysis of swapping terminal tiles by dragging "- "them. It is finished at docs/plans/agentic-ide-terminal-swap.md but the "- "distribution denylist blocks the commit."- )-- assert answer is not None- assert answer.headline == "Swap-analysis document written, not committed"- assert "distribution denylist" in answer.detail- assert answer.source == recap_engine.BY_MODEL---def test_an_unlabelled_answer_is_split_into_the_two_lengths() -> None:- """Models drop the labels; a recap is not worth failing over that."""- answer = recap_engine.parse_answer(- "Running the login tests\nThree of them fail on a missing fixture."- )-- assert answer is not None- assert answer.headline == "Running the login tests"- assert "missing fixture" in answer.detail---def test_a_fenced_answer_is_read_back() -> None:- answer = recap_engine.parse_answer(- "```\nHEADLINE: Tagging v2.4.0\nDETAIL: The release build is green.\n```"- )-- assert answer is not None- assert answer.headline == "Tagging v2.4.0"---def test_an_empty_answer_is_rejected_rather_than_blanking_the_header() -> None:- assert recap_engine.parse_answer("") is None- assert recap_engine.parse_answer(" \n\n ") is None---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---# ------------------------------------------------------------ the summary itself---def test_an_install_with_no_provider_keeps_the_deterministic_recap(monkeypatch) -> None:- """§3: one key, no key, a dead key — the pane header still says something."""- monkeypatch.setattr(recap_engine, "_resolve_brain", lambda: None)-- assert asyncio.run(recap_engine.summarize_with_model(_pane(), _rows(20))) is None---def test_a_failing_provider_leaves_the_previous_sentence_in_place() -> None:- """A provider that raises costs the refresh, never the recap on screen."""-- async def scenario() -> None:- term = _pane(lines=40)- state = recap_engine._state(term.key) # noqa: SLF001- state.headline = "The sentence already on screen"- state.inflight = True-- async def explode(*_args: object, **_kwargs: object) -> None:- raise RuntimeError("429")-- original = recap_engine.summarize_with_model- recap_engine.summarize_with_model = explode # type: ignore[assignment]- try:- await recap_engine._run(term, term.key, _rows(40), "") # noqa: SLF001- finally:- recap_engine.summarize_with_model = original # type: ignore[assignment]-- assert recap_engine.recap_for(term, lines=[]).headline == (- "The sentence already on screen"- )- assert state.failures == 1- assert not state.inflight-- asyncio.run(scenario())---def test_repeated_failures_stop_the_pane_asking_for_a_while() -> None:- """A depleted key fails for every pane and every poll — back off once."""-- async def scenario() -> None:- term = _pane(lines=40)- state = recap_engine._state(term.key) # noqa: SLF001-- async def explode(*_args: object, **_kwargs: object) -> None:- raise RuntimeError("no key")-- original = recap_engine.summarize_with_model- recap_engine.summarize_with_model = explode # type: ignore[assignment]- try:- for _ in range(recap_engine.FAILURES_BEFORE_QUIET):- state.inflight = True- await recap_engine._run(term, term.key, _rows(40), "") # noqa: SLF001- finally:- recap_engine.summarize_with_model = original # type: ignore[assignment]-- assert state.quiet_until > time.time()-- asyncio.run(scenario())---def test_a_successful_summary_becomes_the_pane_recap() -> None:- async def scenario() -> None:- term = _pane(lines=40, prompts_sent=1)-- async def answer(*_args: object, **_kwargs: object) -> recap_engine.SmartRecap:- return recap_engine.SmartRecap(- headline="Swap analysis written, not committed",- detail="It is at docs/plans/agentic-ide-terminal-swap.md.",- source=recap_engine.BY_MODEL,- )-- original = recap_engine.summarize_with_model- recap_engine.summarize_with_model = answer # type: ignore[assignment]- try:- recap_engine._state(term.key).inflight = True # noqa: SLF001- await recap_engine._run(term, term.key, _rows(40), "") # noqa: SLF001- finally:- recap_engine.summarize_with_model = original # type: ignore[assignment]-- shown = recap_engine.recap_for(term, lines=[])- assert shown.headline == "Swap analysis written, not committed"- assert shown.source == recap_engine.BY_MODEL- # And the pane is now considered summarized as of these rows, so the- # next poll does not immediately ask again.- state = recap_engine._state(term.key) # noqa: SLF001- assert state.lines_at == 40- assert state.prompts_at == 1-- asyncio.run(scenario())diff --git a/tests/unit/agentic_ide/test_recap_route.py b/tests/unit/agentic_ide/test_recap_route.pyindex 5c5fee1faa..f516cb2404 100644--- a/tests/unit/agentic_ide/test_recap_route.py+++ b/tests/unit/agentic_ide/test_recap_route.py@@ -13,7 +13,6 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient-from jarvis.agentic_ide import recap_enginefrom jarvis.agentic_ide import session as idefrom jarvis.ui.web import agentic_ide_routes@@ -21,13 +20,11 @@ from jarvis.ui.web import agentic_ide_routes@pytest.fixturedef client() -> TestClient:ide.reset_registry()- recap_engine.reset_for_tests()app = FastAPI()app.include_router(agentic_ide_routes.router)with TestClient(app) as test_client:yield test_clientide.reset_registry()- recap_engine.reset_for_tests()def _workspace(tmp_path, name: str = "Mika") -> ide.Session:@@ -68,11 +65,8 @@ def test_recaps_describe_every_pane_of_the_open_workspace(client, tmp_path) -> Nrow = body["terminals"][0]assert row["name"] == "Mika"assert row["status"] == "live"- assert "Fix the failing login test" in row["recap"]- assert "Running pytest tests/unit/test_login.py" in row["recap_detail"]- # Nothing was summarized by a model here, and the answer says so rather- # than letting the fallback pass itself off as the real thing.- assert row["source"] == "heuristic"+ assert row["recap"] == "Running pytest tests/unit/test_login.py"+ assert "Fix the failing login test" in row["recap_detail"]def test_the_route_and_the_state_payload_agree(client, tmp_path) -> None:@@ -102,197 +96,3 @@ def test_no_workspace_at_all_is_an_empty_answer(client) -> None:assert response.status_code == 200assert response.json()["terminals"] == []---def test_a_thin_recap_says_why_it_is_thin(client, tmp_path) -> None:- """The complaint this field answers: "the recaps say nothing and nobody- knows why". A pane with four printed rows is below the bar for a summary,- and the payload now says so instead of leaving it a mystery."""- session = _workspace(tmp_path)- session.terminals[0].status = "live"- session.terminals[0].transcript.feed("Reading jarvis/core/config.py\r\n")-- row = client.get("/api/agentic-ide/recaps").json()["terminals"][0]-- assert row["source"] == "heuristic"- assert row["reason"] == "warming"---# --------------------------------------------------------------------------- #-# Writing a recap yourself #-# --------------------------------------------------------------------------- #-def test_a_hand_written_recap_replaces_the_derived_one(client, tmp_path) -> None:- session = _workspace(tmp_path)- session.terminals[0].status = "live"- session.terminals[0].last_prompt = "Fix the failing login test"-- written = client.put(- "/api/agentic-ide/terminals/Mika/recap",- json={- "recap": "Demo branch — leave alone",- "recap_detail": "Recording for the Thursday walkthrough.",- },- ).json()-- assert written["recap"] == "Demo branch — leave alone"- assert written["source"] == "user"- assert written["reason"] == "pinned"- # And it is what every other reader of this pane sees, not a second opinion- # living beside the real one.- polled = client.get("/api/agentic-ide/recaps").json()["terminals"][0]- assert polled["recap"] == "Demo branch — leave alone"- assert polled["recap_detail"] == "Recording for the Thursday walkthrough."- state = client.get("/api/agentic-ide/state").json()["session"]["terminals"][0]- assert state["recap"] == "Demo branch — leave alone"---def test_a_hand_written_recap_is_not_summarized_over(client, tmp_path) -> None:- """A pane the user has labelled must not have a model spend a request to- overwrite the label."""- session = _workspace(tmp_path)- term = session.terminals[0]- term.status = "live"- for index in range(20):- term.transcript.feed(f"Step {index}: doing real work\r\n")-- client.put(- "/api/agentic-ide/terminals/Mika/recap",- json={"recap": "Demo branch — leave alone"},- )- calls: list[object] = []-- async def _never(*args: object, **kwargs: object) -> None:- calls.append(args)- return None-- original = recap_engine.summarize_with_model- recap_engine.summarize_with_model = _never # type: ignore[assignment]- try:- client.get("/api/agentic-ide/recaps")- finally:- recap_engine.summarize_with_model = original # type: ignore[assignment]-- assert calls == []---def test_clearing_hands_the_pane_back_to_the_automatic_recap(client, tmp_path) -> None:- session = _workspace(tmp_path)- session.terminals[0].status = "live"- session.terminals[0].last_prompt = "Fix the failing login test"- client.put(- "/api/agentic-ide/terminals/Mika/recap",- json={"recap": "Demo branch — leave alone"},- )-- cleared = client.delete("/api/agentic-ide/terminals/Mika/recap").json()-- assert cleared["source"] == "heuristic"- assert "Fix the failing login test" in cleared["recap"]---def test_saving_an_empty_recap_clears_it(client, tmp_path) -> None:- """Selecting the text and deleting it means "go back to automatic"."""- session = _workspace(tmp_path)- session.terminals[0].status = "live"- session.terminals[0].last_prompt = "Fix the failing login test"- client.put(- "/api/agentic-ide/terminals/Mika/recap",- json={"recap": "Demo branch — leave alone"},- )-- answer = client.put(- "/api/agentic-ide/terminals/Mika/recap", json={"recap": " "}- ).json()-- assert answer["source"] == "heuristic"- assert recap_engine.is_pinned("mika") is False---def test_editing_an_unknown_terminal_is_a_404(client, tmp_path) -> None:- _workspace(tmp_path)-- response = client.put(- "/api/agentic-ide/terminals/Nobody/recap", json={"recap": "Anything"}- )-- assert response.status_code == 404---# --------------------------------------------------------------------------- #-# Summarizing on demand #-# --------------------------------------------------------------------------- #-def test_refresh_returns_the_fresh_summary(client, tmp_path, monkeypatch) -> None:- session = _workspace(tmp_path)- term = session.terminals[0]- term.status = "live"- for index in range(20):- term.transcript.feed(f"Step {index}: doing real work\r\n")-- async def _summary(*args: object, **kwargs: object) -> recap_engine.SmartRecap:- return recap_engine.SmartRecap(- headline="Rewrote the auth middleware",- detail="Two tests still fail.",- source=recap_engine.BY_MODEL,- reason=recap_engine.WHY_SUMMARIZED,- writer="test-model",- )-- monkeypatch.setattr(recap_engine, "summarize_with_model", _summary)-- answer = client.post("/api/agentic-ide/terminals/Mika/recap/refresh").json()-- assert answer["recap"] == "Rewrote the auth middleware"- assert answer["source"] == "model"- assert answer["writer"] == "test-model"---def test_refresh_without_a_reachable_model_degrades_honestly(- client, tmp_path, monkeypatch-) -> None:- """§3: an install with no key still gets a working pane and an honest- answer, never a 500 and never a red pane."""- session = _workspace(tmp_path)- term = session.terminals[0]- term.status = "live"- term.last_prompt = "Fix the failing login test"- for index in range(20):- term.transcript.feed(f"Step {index}: doing real work\r\n")-- async def _boom(*args: object, **kwargs: object) -> None:- raise RuntimeError("no API key configured for key=sk-live-1234")-- monkeypatch.setattr(recap_engine, "summarize_with_model", _boom)-- response = client.post("/api/agentic-ide/terminals/Mika/recap/refresh")-- assert response.status_code == 200- answer = response.json()- assert answer["source"] == "heuristic"- assert answer["reason"] == "unavailable"- assert "RuntimeError" in answer["note"]- # AP-2/AP-12: this string is rendered on screen and could be screenshotted.- assert "sk-live-1234" not in answer["note"]- assert "Fix the failing login test" in answer["recap"]---def test_refresh_drops_a_hand_written_recap(client, tmp_path, monkeypatch) -> None:- """Asking for a fresh summary of a pane you labelled yourself is asking for- the automatic label back — which is what the button says it does."""- session = _workspace(tmp_path)- term = session.terminals[0]- term.status = "live"- term.last_prompt = "Fix the failing login test"- client.put(- "/api/agentic-ide/terminals/Mika/recap",- json={"recap": "Demo branch — leave alone"},- )-- async def _nothing(*args: object, **kwargs: object) -> None:- return None-- monkeypatch.setattr(recap_engine, "summarize_with_model", _nothing)-- answer = client.post("/api/agentic-ide/terminals/Mika/recap/refresh").json()-- assert answer["source"] != "user"- assert recap_engine.is_pinned("mika") is Falsediff --git a/tests/unit/test_agent_config_parity.py b/tests/unit/test_agent_config_parity.pyindex 7665540234..2a03d38007 100644--- a/tests/unit/test_agent_config_parity.py+++ b/tests/unit/test_agent_config_parity.py@@ -178,6 +178,46 @@ def test_codex_shares_its_config_skills_rules_and_prompts(tmp_path: Path) -> Nonassert not (account.config_dir / "secrets").exists()+# ------------------------------------------------------------------ drift guard+++def test_every_cli_that_can_be_redirected_has_a_setup_allowlist() -> None:+ """A CLI gains accounts, and its panes silently lose the user's setup again.++ That is how this bug arrives a second time: redirecting a config dir is one+ line in ``agent_accounts.ENV_VAR``, while carrying the user's setup across is+ a table somebody has to remember. The two must not be able to drift apart —+ so a platform with an override and no allowlist fails here rather than in+ somebody's terminal six months from now.+ """+ for platform in agent_accounts.PLATFORMS:+ assert platform in agent_accounts.ENV_VAR+ entries = agent_config_parity.USER_SETUP.get(platform)+ assert entries, f"{platform} can be redirected but shares nothing back"+ # Every entry is one the CLI reads; nothing that identifies the account.+ names = {entry.name for entry in entries}+ assert not names & {+ ".credentials.json",+ "auth.json",+ "secrets",+ ".claude.json",+ "projects",+ "sessions",+ "history.jsonl",+ }+++def test_a_merged_key_never_names_a_whole_identity_document() -> None:+ """Merging is the concession made for documents that hold the login too.++ It stays a concession: one key at a time, never the file, and never a key+ that carries the identity itself.+ """+ for merges in agent_config_parity.MERGED_KEYS.values():+ for merged in merges:+ assert merged.key not in {"oauthAccount", "userID", "projects"}++# ------------------------------------------------------------- identity is safe