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
feat(agentic-ide): rebuild the pane scrollbar around what a pane can answer
Ruben Lütke41a2c690aa20
diff --git a/docs/commands-reference.md b/docs/commands-reference.mdindex 7f9e92d925..6b0ec785bb 100644--- a/docs/commands-reference.md+++ b/docs/commands-reference.md@@ -263,7 +263,7 @@ Read what the coding agent in a named terminal is doing — its status and its r## `agentic-ide-prompt` — Prompt an Agentic-IDE terminal-Send an instruction to the coding agent in ONE named terminal. Use this whenever the user tells a terminal to do something ('tell Kai to ...', 'Mika soll ...', 'let Nova refactor ...') — that work belongs to that agent, never to a background worker. For SEVERAL terminals ('Kai and Mika both ...', 'let the two of them ...') call 'agentic-ide-fanout' instead, with every call-sign in 'terminals': it briefs them at once and reports which ones really got the work. Calling this command twice for a pair leaves the second agent idle whenever the second call is forgotten, which is the failure mode fanout exists to remove. Pass the instruction in the USER's words: everything they asked for, every constraint and file they named, nothing invented and nothing summarised away. Do NOT write the brief yourself — a prompt writer that has read this repository turns what you pass into a briefed task with the relevant files attached, and a headline you composed instead arrives at the agent as its whole assignment. Only ever names a terminal that is ALREADY running: if the call fails with 'no terminal called …', opening a pane will not create that name — use 'agentic-ide-fanout' with spawn to open and brief one in a single step, and never repeat the spawn. CHECK THE REPLY: it carries a 'submitted' flag. True means the agent accepted the prompt and started. False means the text is only sitting in that terminal's input box — say so plainly and name the terminal, never report it as done.+Send an instruction to the coding agent in a named terminal. Use this whenever the user tells a terminal to do something ('tell Kai to ...', 'Mika soll ...', 'let Nova refactor ...') — that work belongs to that agent, never to a background worker. Pass the instruction in the USER's words: everything they asked for, every constraint and file they named, nothing invented and nothing summarised away. Do NOT write the brief yourself — a prompt writer that has read this repository turns what you pass into a briefed task with the relevant files attached, and a headline you composed instead arrives at the agent as its whole assignment. Only ever names a terminal that is ALREADY running: if the call fails with 'no terminal called …', opening a pane will not create that name — use 'agentic-ide-fanout' with spawn to open and brief one in a single step, and never repeat the spawn. CHECK THE REPLY: it carries a 'submitted' flag. True means the agent accepted the prompt and started. False means the text is only sitting in that terminal's input box — say so plainly and name the terminal, never report it as done.- **Endpoint:** `POST /api/agentic-ide/terminals/{name}/prompt`- **Arguments:** `name` (string; required); `prompt` (string; required); `compose` (boolean; optional)diff --git a/jarvis/agentic_ide/clarify.py b/jarvis/agentic_ide/clarify.pydeleted file mode 100644index 640d6912ec..0000000000--- a/jarvis/agentic_ide/clarify.py+++ /dev/null@@ -1,742 +0,0 @@-"""Ask which terminal was meant, instead of guessing or going silent.--A call-sign arrives through speech recognition, and the resolver has to draw a-line somewhere: above it a word IS a pane's name, below it the word is ordinary-speech. Both sides of that line have now failed in production, on the same day,-in opposite directions:--* **Silent miss** (2026-07-27 16:18) — a pane called "Ellis" came back as- "Ilies", scoring 0.667 against a 0.72 floor. The addressed-terminal path stood- down without a word, no prompt ever reached the pane, and the live model —- which never learns any of this — told the user an agent was working on it.-* **Silent false hit** — ordinary words of the spoken language reach the pool- from below: "allen" scores 0.750 against "Alex", i.e. ABOVE the same floor.- A sentence about the outside world ("what is Elon Musk up to?") must never- become an instruction typed into somebody's coding agent.--No threshold fixes both, because the two failures overlap on the score axis —-the maintainer's directive (2026-07-27) is therefore to decide by CONTEXT and,-when context says "this is about the panes" but the name is uncertain, to ASK:-- "Did you mean Ellis?"--That is what this module decides. It answers one question — "is this turn-addressing the workspace, and if so, which pane did the user probably mean?" —-and, like ``intent``, it is a detector, not a policy: the caller decides what to-do with the answer.--The asymmetry that shapes every rule below: a needless question costs the user-one word ("yes"), while a wrong guess types a stranger's task into an agent that-then works for minutes on it. So the gate is deliberately hard to pass, and-whatever it is unsure about becomes a question rather than an action.--Cost: pure regex over the utterance, no IO and no LLM (AP-9 / AP-11), so it is-safe on the voice hot path.-"""-from __future__ import annotations--import re-import time-from dataclasses import dataclass, field--from .names import near_miss, resolve--# How long a pending question stays answerable. Voice turns arrive within-# seconds; two minutes covers a slow "uh... yes, Ellis" without letting a-# forgotten question deliver work much later in the session. Same bound as the-# delegation offer window, for the same reason.-_WINDOW_TTL_S = 120.0--# A short answer is an ANSWER to the question ("yes", "Ellis", "the second-# one"); a long sentence is the user moving on and must never deliver the old-# task. Same bound the spawn gate uses for its confirmation.-_ANSWER_MAX_WORDS = 6---# --------------------------------------------------------------------------- #-# Is this turn about the workspace at all? #-# --------------------------------------------------------------------------- #-# The gate that separates "prompt Max" from "what is Elon Musk doing". Evidence-# has to be POSITIVE and explicit: the default answer is no, because that is the-# answer that cannot type a stranger's sentence into a running coding agent.--#: Words that only ever mean the coding workspace. Naming a pane, or the act of-#: handing one work, is the strongest evidence there is.-_WORKSPACE_NOUN_RE = re.compile(- r"\b(?:terminals?|terminales|panes?|workspaces?|"- r"arbeitsbereich\w*|instanz\w*|instances?|" # i18n-allow: input vocab- r"prompte?\w*|prompting|anprompt\w*|" # i18n-allow: input vocab- r"beauftrag\w*|briefe?\w*|briefing)\b", # i18n-allow: input vocab- re.IGNORECASE,-)--#: The work coding agents actually do. A sentence carrying this vocabulary is-#: about the user's own codebase, which is what the panes are for — as opposed-#: to a question about the world, which never contains it.-_CODING_WORK_RE = re.compile(- r"\b(?:"- # investigation / analysis- r"deep[\s-]?dive|root[\s-]?cause|debug\w*|analysier\w*|analyz\w*|analis\w*|"- r"untersuch\w*|investigate\w*|diagnos\w*|" # i18n-allow: input vocab- # change- # i18n-allow: input vocab- r"fix\w*|behebe?\w*|repariere?\w*|refactor\w*|implementier\w*|implement\w*|"- r"commit\w*|merge\w*|rebase\w*|deploy\w*|"- # artifacts- r"bugs?|fehler\w*|tests?|teste\w*|repo\w*|branch\w*|" # i18n-allow: input vocab- r"code\w*|datei\w*|files?|funktion\w*|functions?|" # i18n-allow: input vocab- r"pull[\s-]?request|pr\b|"- # Spanish work vocabulary, kept level with the other two locales- r"arregl\w*|revis\w*|prueba\w*|archivo\w*|rama\w*"- r")\b",- re.IGNORECASE,-)--#: Handing work to somebody — "sag X …", "lass X …", "tell X to …". Reused from-#: the same vocabulary ``intent`` addresses panes with, kept here as a flat verb-#: scan because at this point the NAME is exactly what we are unsure about, so a-#: name-anchored template cannot be built yet.-_HANDOVER_VERB_RE = re.compile(- # Stems, not fixed forms: the maintainer's own phrasing is "… machen- # LASSEN", and a `lass\b` alternative silently misses every separable and- # infinitive form German actually hands work over in.- r"\b(?:sag\w*|schick\w*|gib|geb\w*|frag\w*|lass\w*|l[aä]sst|" # i18n-allow: input vocab- r"beauftrag\w*|[uü]bergib|[uü]bergeb\w*|weiterleit\w*|" # i18n-allow: input vocab- r"tell|send|give|ask|hand|forward|assign|let|have|"- r"dile|d[ií]gale|env[ií]a|manda|preg[uú]nta|pasa|asigna|encarga)\b", # i18n-allow: input vocab- re.IGNORECASE,-)---#: "X SOLL das fixen" — an order aimed at a third party, carried by the modal-#: rather than by a handover verb. This is the other half of how work is-#: assigned in speech, and ``intent`` matches it name-anchored; here the name is-#: precisely what is uncertain, so the modal is scanned on its own and paired-#: with coding work to keep it honest.-_DIRECTIVE_MODAL_RE = re.compile(- r"\b(?:soll|sollen|sollte|sollten|m[uü]ssen|muss|" # i18n-allow: input vocab- r"should|must|shall|"- r"deber[ií]an?|debe|deben)\b", # i18n-allow: input vocab- re.IGNORECASE,-)---#: "What has X done?" / "How far is X?" — asking a NAMED worker for a status-#: report. The shape carries no coding vocabulary at all, which is why it-#: needed its own rule: "was hat Dana gemacht" names no repo, no test, no bug-#: and no branch, so the coding-work pairings below never saw it.-#:-#: Each locale gets both word orders, and the German alternation carries the-#: optional perfect prefix ("gemacht", "getan", "gearbeitet") — the tense-#: spoken German actually uses to ask about work that has already happened, and-#: the exact form the live 2026-07-27 turn was lost on.-_REPORT_QUESTION_RE = re.compile(- # A progress opener is a status question on its own — "wie weit ist Ellis?"- # carries no verb of doing at all, and nothing else is ever asked with it.- r"\b(?:wie\s+weit|wie\s+l[aä]uft|wie\s+steht|how\s+far|" # i18n-allow: input vocab- r"c[oó]mo\s+va)\b|"- r"\bwas\b[^.!?]{0,40}?" # i18n-allow: input vocab- r"\b(?:ge)?(?:macht|machen|tut|tun|tan|treibt|treiben|arbeitet|" # i18n-allow: input vocab- r"arbeiten|schafft|geschafft|erledigt|rausgefunden|" # i18n-allow: input vocab- r"herausgefunden|gebaut|geschrieben|ge[aä]ndert)\b|" # i18n-allow: input vocab- r"\b(?:ist|sind)\b[^.!?]{0,30}?\b(?:fertig|durch|soweit)\b|" # i18n-allow: input vocab- r"\b(?:what|how)\b[^.!?]{0,40}?"- r"\b(?:doing|done|do|did|up\s+to|going|built|found|changed|"- r"working\s+on|progress\w*)\b|"- r"\b(?:is|are)\b[^.!?]{0,30}?\b(?:done|finished|ready|stuck)\b|"- r"\b(?:qu[eé]|c[oó]mo)\b[^.!?]{0,40}?"- r"\b(?:hacen?|haciendo|hecho|hizo|hicieron|va|van|"- r"encontr\w*|cambi\w*)\b|"- r"\b(?:est[aá]|est[aá]n)\b[^.!?]{0,30}?\b(?:listo\w*|terminad\w*)\b|"- r"\b(?:status|fortschritt|estado|progreso)\b", # i18n-allow: input vocab- re.IGNORECASE,-)---def addresses_workspace(text: str) -> bool:- """Whether this turn is plausibly about the open coding workspace.-- Four independent kinds of evidence, any one of which is enough:-- 1. the utterance NAMES the workspace or the act of prompting a pane- ("prompt Max", "beauftrage Max") — unambiguous on its own;- 2. it hands work over AND that work is coding work ("tell Max to fix the- tests");- 3. it gives a third-party order AND that order is coding work ("Ellis soll- einen Deep Dive machen") — the shape that carries no handover verb;- 4. it asks a named worker for a STATUS REPORT ("was hat Ellis gemacht?").-- In 2 and 3 the pairing is what does the work. A handover verb alone- deliberately does NOT qualify: "tell me what Elon Musk is doing" is a- handover verb plus a name and nothing else, and that sentence must never- reach a coding agent.-- 4 stands alone without a coding-work pairing, and it may, because of what- it can and cannot cause. This module only ever produces a QUESTION — "did- you mean Ellis?" — and only for a turn where no pane was certainly named- and exactly one word came close. A status question about somebody the user- really did mean as a person therefore costs one "no"; without the rule, a- call-sign that speech recognition garbled inside the single most common- workspace question there is went silently nowhere, which is the failure- this whole module exists to end.- """- body = str(text or "")- if _WORKSPACE_NOUN_RE.search(body):- return True- # A status question about a FULL personal name is about that person: "sag- # mir was Elon Musk gerade macht" has the identical shape to "sag mir was- # Ellis gerade macht" and the opposite meaning, and the surname is the only- # thing that tells them apart. Same rule the collective address uses, so- # the two cannot drift into disagreeing about one sentence.- if _REPORT_QUESTION_RE.search(body) and not is_outside_world_talk(body):- return True- if not _CODING_WORK_RE.search(body):- return False- return bool(- _HANDOVER_VERB_RE.search(body) or _DIRECTIVE_MODAL_RE.search(body)- )---# --------------------------------------------------------------------------- #-# Is this word a call-sign at all? #-# --------------------------------------------------------------------------- #--#: Word characters only — the unit the resolver scores. Mirrors ``intent``.-_WORD_RE = re.compile(r"[^\W\d_]+", re.UNICODE)--_SENTENCE_START_RE = re.compile(r"(?:^|[.!?:;]\s*|\n\s*)$")--#: Function words that are never a call-sign, however close they score. This is-#: matching *input vocabulary*, not prose.-#:-#: Needed because similarity alone cannot tell them apart from a garbled name —-#: measured against the shipping pool, "kannst" reaches "Casey" at 0.600,-#: "macht" reaches "Max" at 0.571, and "allen" reaches "Alex" at 0.750, which is-#: ABOVE the acting threshold. That last one is the maintainer's own-#: counter-example (2026-07-27): a sentence about the outside world must never-#: become a prompt typed into every open pane.-#:-#: Deliberately only the closed class (pronouns, articles, modals, question-#: words, common auxiliaries). Content words are left out: they are what a-#: person's name competes with legitimately, and the capitalization signal plus-#: the workspace gate already cover them.-#: Kept as one tuple per language rather than one merged literal: the locales-#: overlap ("no", "me", "es", "a" are each two languages' function words), and a-#: single set literal would both hide that and read as a mistake.-_STOPWORDS_DE: tuple[str, ...] = ( # i18n-allow: input vocabulary- "alle", "allen", "aller", "alles", "als", "am", "an", "auch", "auf",- "aus", "bei", "bin", "bis", "bist", "bitte", "da", "dann", "das",- "dass", "dein", "deine", "dem", "den", "denn", "der", "des", "die",- "dir", "doch", "du", "ein", "eine", "einen", "einer", "eines", "er",- "es", "etwas", "euch", "für", "gerade", "gib", "hab", "habe", "haben",- "hast", "hat", "hier", "ich", "ihm", "ihn", "ihr", "im", "in", "ist",- "ja", "kann", "kannst", "können", "könnte", "lass", "lassen", "mach",- "machen", "macht", "mal", "man", "mein", "meine", "mir", "mit", "muss",- "müssen", "nach", "nein", "nicht", "noch", "nur", "ob", "oder", "sag",- "sage", "schon", "sein", "seine", "sich", "sie", "sind", "so", "soll",- "sollen", "über", "um", "und", "uns", "unser", "von", "vor", "war",- "was", "wenn", "wer", "werde", "werden", "wie", "wieso", "will",- "wir", "wird", "wo", "zu", "zum", "zur",-)-_STOPWORDS_EN: tuple[str, ...] = (- "a", "all", "am", "an", "and", "are", "as", "ask", "at", "be", "been",- "but", "by", "can", "could", "did", "do", "does", "for", "from", "get",- "give", "had", "has", "have", "he", "her", "him", "his", "how", "i",- "if", "in", "into", "is", "it", "its", "just", "let", "make", "makes",- "me", "my", "no", "not", "now", "of", "on", "one", "or", "our", "out",- "please", "put", "say", "she", "should", "so", "some", "tell", "that",- "the", "their", "them", "then", "there", "these", "they", "this",- "to", "up", "us", "was", "we", "were", "what", "when", "where",- "which", "who", "why", "will", "with", "would", "yes", "you", "your",-)-_STOPWORDS_ES: tuple[str, ...] = ( # i18n-allow: input vocabulary- "a", "al", "algo", "aqui", "así", "como", "con", "cual", "cuando",- "de", "del", "dile", "donde", "el", "ella", "ellos", "en", "era",- "es", "esa", "ese", "eso", "esta", "este", "esto", "está", "están",- "haz", "la", "las", "le", "les", "lo", "los", "mas", "me", "mi",- "no", "nos", "o", "para", "pero", "por", "que", "qué", "quien",- "se", "ser", "si", "sí", "sobre", "solo", "son", "su", "sus", "te",- "tu", "un", "una", "uno", "y", "ya", "yo",-)-_STOPWORDS: frozenset[str] = frozenset(- _STOPWORDS_DE + _STOPWORDS_EN + _STOPWORDS_ES-)---def _capitalization_is_informative(text: str) -> bool:- """Whether this transcript capitalizes at all, i.e. whether case can rule.-- An all-lowercase transcript is a provider quirk, not evidence that the- utterance contains no names.- """- body = str(text or "")- return any(ch.isupper() for ch in body)---def _is_proper_name_position(text: str, start: int, end: int) -> bool:- """Whether the word at ``[start:end)`` reads as a proper name.-- Two filters, in this order, because they fail differently:-- 1. **a function word is never a name** — decisive in every transcript,- including one with no capitals at all;- 2. **otherwise capitalization decides**, when the transcript capitalizes at- all. Position is deliberately NOT considered: a call-sign opening the- sentence is the most natural way to address a pane ("Ellis, schau dir- das an"), and excluding sentence-initial words would blind the check to- exactly that shape.- """- word = text[start:end]- if word.casefold() in _STOPWORDS:- return False- if _is_vocabulary_word(word):- return False- if not _capitalization_is_informative(text):- return True- return word[:1].isupper()---#: What somebody ASKS FOR about a pane, as a noun: "Alex Status?", "Dana-#: Fortschritt", "Casey progress". German capitalizes every noun, so without-#: this these read as surnames and the pane is disowned as a person out in the-#: world — which is how "Alex Status?", a textbook status question, matched-#: nothing at all.-_STATUS_NOUN_RE = re.compile(- r"\b(?:status|fortschritt\w*|stand|update\w*|progress|" # i18n-allow: input vocab- r"bericht\w*|report\w*|estado|progreso|informe\w*)\b", # i18n-allow: input vocab- re.IGNORECASE,-)---def _is_vocabulary_word(word: str) -> bool:- """Whether the word is one this module already reads as something else.-- A word that names the WORK cannot also name the worker. Without this, an- all-lowercase transcript — where capitalization cannot rule anything out —- let "fixen" stand in for the pane "Finn" (0.667) and ask about a sentence- that names no pane at all.-- Anchored so only a WHOLE word counts: the vocabulary patterns are written- to find their stems anywhere in a sentence, and reused unanchored they- would reject any call-sign that merely contains one.- """- for pattern in (- _WORKSPACE_NOUN_RE,- _CODING_WORK_RE,- _HANDOVER_VERB_RE,- _DIRECTIVE_MODAL_RE,- _STATUS_NOUN_RE,- ):- match = pattern.match(word)- if match is not None and match.end() == len(word):- return True- return False---#: A second capitalized word directly after the candidate — "Elon MUSK", "Max-#: MUSTERMANN". Panes carry exactly one given name (see ``names.NAME_POOL``), so-#: a surname is positive evidence that a PERSON is meant, not a terminal. This-#: is the maintainer's own criterion (2026-07-27): "when I only say a first-#: name" is the case that should ask.-_SURNAME_FOLLOWS_RE = re.compile(r"^[\s,]*[A-ZÄÖÜ][^\W\d_]+")-_SURNAME_PRECEDES_RE = re.compile(r"[A-ZÄÖÜ][^\W\d_]+[\s,]*$")---def is_part_of_full_name(text: str, start: int, end: int) -> bool:- """Whether the candidate is part of a longer proper name ("Elon Musk").-- Public because ``intent`` needs exactly this answer too: a call-sign is a- single given name, so a first name carrying a surname is a PERSON out in- the world and never the pane. Two copies of that rule would be two chances- to disagree about one sentence, which is how "what has Dana Schmidt done"- ends up read as a question about a terminal.- """- if not _capitalization_is_informative(text):- return False- following = _SURNAME_FOLLOWS_RE.match(text[end:])- if following is not None:- # German capitalizes every noun, so the word after a call-sign is- # capitalized whether it is a surname or the thing being asked about.- # A word this module already reads as work, a workspace or a status is- # therefore never the surname: "Alex Status?" is a question about the- # pane, and reading "Status" as a family name struck the pane out of- # its own status question. Same reasoning for "sag Dana Bescheid".- if not _is_vocabulary_word(following.group(0).strip(" ,")):- return True- preceding = text[:start]- leading = _SURNAME_PRECEDES_RE.search(preceding)- if leading is None:- return False- if _is_vocabulary_word(leading.group(0).strip(" ,")):- return False- # A capitalized word in FRONT only makes this a surname when that word is- # not itself the one opening the sentence. The sentence-start test has to- # be aimed at THAT word, not at the candidate: aimed at the candidate it- # read "Ist Blake fertig?" as a person called Ist Blake, because "Ist" is- # capitalized for grammar and stands at the very beginning — which silently- # withdrew the pane from every question opening with a verb.- return not _SENTENCE_START_RE.search(preceding[: leading.start()])---#: Two capitalized words in a row, the second not opening a sentence — a person-#: or organisation out in the world ("Elon Musk", "Barack Obama"). Panes carry a-#: single given name, so this shape never describes one.-_MULTIWORD_NAME_RE = re.compile(- r"(?<![.!?:;\n])\s[A-ZÄÖÜ][^\W\d_]+\s+[A-ZÄÖÜ][^\W\d_]+"-)---def is_outside_world_talk(text: str) -> bool:- """Whether this turn is about the world rather than the user's codebase.-- Guards the COLLECTIVE address ("sag allen …"), which reaches every open- pane at once and is therefore the most expensive thing a misheard word can- trigger. The maintainer's counter-example (2026-07-27): a question about a- public figure that speech recognition turns into "sag allen …" must not- become an instruction typed into every running coding agent.-- Deliberately narrow — it answers yes only for a full personal name with no- coding work anywhere in the sentence. "Tell everyone to stop" carries no- such name and stays a perfectly good collective instruction.- """- body = str(text or "")- if not _capitalization_is_informative(body):- return False- return bool(- _MULTIWORD_NAME_RE.search(body) and not _CODING_WORK_RE.search(body)- )---# --------------------------------------------------------------------------- #-# The detector #-# --------------------------------------------------------------------------- #---@dataclass(frozen=True, slots=True)-class UncertainName:- """One word that came close to a call-sign, and the panes it might be."""-- spoken: str- """The word as the transcript spelled it ("Ilies")."""-- candidates: tuple[str, ...]- """Panes it could mean, best first. Never empty."""---@dataclass(frozen=True, slots=True)-class ClarificationNeeded:- """Everything one turn addressed that could not simply be acted on.-- A turn addresses a FLEET, not a pane — "Alex und Blaike, macht beide einen- Deep Dive" is one instruction for two agents — so this carries a list on- both axes. The single-name shape it started as could not represent that- turn at all, and the resulting behaviour was the worst of the three- possible ones: Alex was briefed, Blaike was dropped without a word, and the- user watched one agent work believing two were (live 2026-07-27 19:07).- """-- uncertain: tuple[UncertainName, ...]- """The words that need a question. Never empty."""-- utterance: str- """The original turn, kept verbatim so the confirmed pane gets the REAL- task and not a paraphrase assembled from fragments."""-- certain: tuple[str, ...] = ()- """Panes the SAME turn named beyond doubt. They are not in question and- must be briefed whatever the answer is; they travel with the question only- so the caller can tell "one pane is uncertain" from "everything is"."""-- @property- def spoken(self) -> str:- """The first uncertain word — the one a single-name question names."""- return self.uncertain[0].spoken-- @property- def candidates(self) -> tuple[str, ...]:- """Panes the first uncertain word could mean."""- return self.uncertain[0].candidates-- @property- def offered(self) -> tuple[str, ...]:- """Every pane any of the uncertain words could mean, in order."""- seen: list[str] = []- for item in self.uncertain:- for name in item.candidates:- if name not in seen:- seen.append(name)- return tuple(seen)---#: What may stand between two names that are being listed together. Only-#: enumeration punctuation and the supported languages' "and" — anything else-#: means the two words are in different clauses and say nothing about each-#: other. Matching *input vocabulary*, not prose.-_ENUMERATION_GAP_RE = re.compile(- r"^[\s,;&]*"- # i18n-allow: input vocabulary — the supported languages' "and"- r"(?:und|and|y|e|sowie|plus|as\s+well\s+as|together\s+with|junto\s+con)?"- r"[\s,;&]*$",- re.IGNORECASE,-)---def _is_listed_beside(text: str, span: tuple[int, int], others: list[tuple[int, int]]) -> bool:- """Whether the word at ``span`` is enumerated next to one of ``others``.-- "Alex und Blaike" lists two call-signs; "Alex, look at what Blaike wrote"- does not, and the difference is exactly what sits between them. Used only- where a word would otherwise be too weak to ask about on its own, so it- buys reach without widening what a lone stray capital can trigger.- """- start, end = span- for other_start, other_end in others:- if other_end <= start and _ENUMERATION_GAP_RE.match(text[other_end:start]):- return True- if end <= other_start and _ENUMERATION_GAP_RE.match(text[end:other_start]):- return True- return False---def detect_clarification(- user_text: str, *, names: list[str]-) -> ClarificationNeeded | None:- """What this turn addressed but did not clearly name, or ``None``.-- Every condition below removes one way of being wrong:-- 1. **the turn addresses the workspace** — otherwise a question about the- world could put words into a coding agent;- 2. **the word reads as a proper name** — capitalized, not just first in- its sentence;- 3. **it is not part of a longer proper name** — "Elon Musk" is a person;- 4. **a word that stands alone in its uncertainty** may only ask when it is- the turn's ONLY unclear name and no pane was certainly named. Beyond- that single case the word has to be ENUMERATED beside another name- ("Alex und Blaike") — that is what separates a garbled member of a list- from a stray capital in a sentence that already works.-- A certainly-named pane no longer ENDS the search, which is the change that- matters. It used to: any certain name returned ``None``, so "Alex und- Blaike" produced a question about nothing, Alex was briefed alone, and the- second agent the user had just addressed was dropped in silence. The- certain panes now travel with the answer instead (``certain``) — the caller- briefs them immediately and asks only about the rest.- """- text = str(user_text or "").strip()- if len(text) < 3 or not names:- return None- if not addresses_workspace(text):- return None-- certain: list[str] = []- certain_spans: list[tuple[int, int]] = []- uncertain: list[tuple[tuple[int, int], UncertainName]] = []- for match in _WORD_RE.finditer(text):- word = match.group(0)- span = (match.start(), match.end())- # Certain means the exact name or the same sound — deliberately the- # same bar ``near_miss`` uses, so no utterance can fall between the two- # paths and produce neither an action nor a question.- sure = resolve(word, names, fuzzy=False)- if sure is not None:- if sure not in certain:- certain.append(sure)- certain_spans.append(span)- continue- candidates = near_miss(word, names)- if not candidates:- continue- if not _is_proper_name_position(text, *span):- continue- if is_part_of_full_name(text, *span):- continue- uncertain.append(- (span, UncertainName(spoken=word, candidates=tuple(n for n, _ in candidates)))- )-- if not uncertain:- return None-- if len(uncertain) > 1 or certain:- # More than one unclear word, or one standing beside a certain name:- # only the ones being LISTED with another name survive. A single stray- # near miss elsewhere in the sentence is noise, and asking about it- # would tax every turn that already works.- neighbours = certain_spans + [span for span, _ in uncertain]- kept = [- (span, item)- for span, item in uncertain- if _is_listed_beside(text, span, [s for s in neighbours if s != span])- ]- if not kept:- return None- uncertain = kept-- return ClarificationNeeded(- uncertain=tuple(item for _, item in uncertain),- utterance=text,- certain=tuple(certain),- )---# --------------------------------------------------------------------------- #-# The answer window #-# --------------------------------------------------------------------------- #---@dataclass(slots=True)-class _Pending:- uncertain: tuple[UncertainName, ...]- utterance: str- asked_at: float- question: str = ""-- @property- def candidates(self) -> tuple[str, ...]:- """Every pane on offer, in the order they were spoken."""- seen: list[str] = []- for item in self.uncertain:- for name in item.candidates:- if name not in seen:- seen.append(name)- return tuple(seen)---@dataclass(slots=True)-class ClarificationWindow:- """A question waiting for its answer.-- Without this the question would be theatre: "did you mean Ellis?" followed- by "yes" has to actually deliver the ORIGINAL task, or the user has simply- been made to repeat themselves — which is worse than the silent miss it- replaces, because it also cost them a turn.- """-- _pending: _Pending | None = field(default=None)-- def arm(- self, need: ClarificationNeeded, *, question: str = "", now: float | None = None- ) -> None:- self._pending = _Pending(- uncertain=need.uncertain,- utterance=need.utterance,- asked_at=time.monotonic() if now is None else now,- question=question,- )-- def disarm(self) -> None:- self._pending = None-- @property- def armed(self) -> bool:- return self._pending is not None-- def resolve_answer(- self, answer: str, *, language: str = "de", now: float | None = None- ) -> tuple[tuple[str, ...], str] | None:- """``(panes, original_utterance)`` for a clear answer, else ``None``.-- A tuple of panes rather than one, because the question can be about a- fleet: "did you mean Alex and Blake?" is answered by one "yes" and both- agents have to be briefed by it. Answering it with one pane was how the- second agent of an addressed pair got lost.-- Consumed exactly once either way — a question that has been answered,- declined or ignored must never deliver work on a later turn.-- Three shapes count as an answer, in falling directness:-- 1. the user NAMES offered panes ("Ellis", "Alex and Blake") — decisive- even when several were offered;- 2. a short affirmative — it confirms every uncertain word that has only- ONE candidate, because "yes" cannot choose between two;- 3. anything else: the window closes and the turn proceeds normally.- """- pending = self._pending- if pending is None:- return None- current = time.monotonic() if now is None else now- if (current - pending.asked_at) > _WINDOW_TTL_S:- self._pending = None- return None-- text = str(answer or "").strip()- if not text:- return None-- offered = list(pending.candidates)- named = [- hit- for hit in (- resolve(match.group(0), offered, fuzzy=False)- for match in _WORD_RE.finditer(text)- )- if hit is not None- ]- if not named:- # The whole answer as one token, which is how a one-word reply and- # a two-word call-sign both arrive.- single = resolve(text, offered)- if single is not None:- named = [single]- if named:- self._pending = None- return tuple(dict.fromkeys(named)), pending.utterance-- # Only a SHORT turn is an answer at all; a full sentence is the user- # moving on, and delivering the old task then would be a surprise. The- # bound grows with the number of names on offer: confirming a fleet- # costs more words than confirming one pane.- if len(text.split()) > _ANSWER_MAX_WORDS + len(pending.uncertain) - 1:- self._pending = None- return None-- verdict = _classify(text, language)- self._pending = None- if verdict != "confirm":- return None- decided = tuple(- dict.fromkeys(- item.candidates[0] for item in pending.uncertain if len(item.candidates) == 1- )- )- return (decided, pending.utterance) if decided else None---def _classify(text: str, language: str) -> str:- """Yes/no verdict for a short answer, across every supported language.-- The per-turn language tag cannot be trusted (STT mislabels are a known- class), so the answer is classified under all supported languages and a- veto keeps its safety priority — exactly what ``spawn_gate`` does.- """- try:- from jarvis.voice.echo_confirmation import classify_response # noqa: PLC0415- except Exception: # noqa: BLE001 — a classifier fault is simply "no answer"- return "unknown"- verdicts = {- classify_response(text, language=lang)- for lang in {"de", "en", "es", str(language or "de")}- }- if "veto" in verdicts:- return "veto"- return "confirm" if "confirm" in verdicts else "unknown"---#: ONE conversation per process (desktop app / headless session), so ONE shared-#: window — the same reasoning as ``spawn_gate.OFFER_WINDOW``. Tests reset it-#: via ``disarm()``.-WINDOW = ClarificationWindow()---__all__ = [- "WINDOW",- "ClarificationNeeded",- "ClarificationWindow",- "UncertainName",- "addresses_workspace",- "detect_clarification",- "is_outside_world_talk",- "is_part_of_full_name",-]diff --git a/jarvis/agentic_ide/intent.py b/jarvis/agentic_ide/intent.pyindex 1cf7fa84cf..5eaf5faf9f 100644--- a/jarvis/agentic_ide/intent.py+++ b/jarvis/agentic_ide/intent.py@@ -874,45 +874,6 @@ def wants_split(user_text: str) -> bool:)-#: "both of you", "you two", "all three of them", "die zwei Terminals". What-#: these have in common is a COUNT the utterance states out loud, which is the-#: only evidence that survives a call-sign speech recognition mangled beyond-#: recognition. Matching *input vocabulary*, not prose.-_PLURAL_ADDRESS_RE = re.compile(- r"\b(?:"- # explicit "both" / "all of you", in every supported language- r"beide[nsr]?|alle\s+beide|ihr\s+(?:beide[nr]?|zwei|drei|vier)|euch\s+beide[nr]?|"- r"both(?:\s+of\s+(?:you|them))?|all\s+(?:of\s+)?(?:you|them)|you\s+(?:two|three|four)|"- r"ambos|ambas|los\s+dos|las\s+dos|ustedes\s+dos|"- # a spoken count next to what is being counted- r"(?:zwei|drei|vier|f[üu]nf|two|three|four|five|dos|tres|cuatro|cinco|[2-9])\s+"- r"(?:der\s+|die\s+|von\s+den\s+|of\s+the\s+|de\s+los\s+)?"- r"(?:terminals?|terminales|panes?|agent(?:s|en)?|instanz\w*|instances?)"- r")\b",- re.IGNORECASE,-)---def expects_several(user_text: str) -> bool:- """True when the utterance says out loud that MORE THAN ONE pane is meant.-- The one signal that outlives a garbled call-sign. Live 2026-07-27 19:07:- "Alexa and Dave should both do a deep dive" — "Alexa" was recoverable as- Alex, "Dave" matched no pane at any threshold, and the turn quietly briefed- one agent while the user watched for two. Nothing in the name resolver can- fix that; the word "both" can, because it says the count independently of- whether either name survived transcription.-- Deliberately narrow: an explicit "both/all of you/you two", or a spoken- number standing next to the thing being counted. A bare plural noun does- NOT qualify — "look at the terminals" states no count.- """- text = (user_text or "").strip()- if len(text) < 6:- return False- return bool(_PLURAL_ADDRESS_RE.search(text))--def owns_turn(user_text: str, *, names: list[str] | None = None) -> bool:"""True when the open workspace should handle this turn instead of a spawn.@@ -946,18 +907,12 @@ def owns_turn(user_text: str, *, names: list[str] | None = None) -> bool:__all__ = ["KIND_PROMPT","KIND_REPORT",- "CloseTerminalsRequest","SpawnGroup","SpawnTerminalsRequest","TerminalIntent","detect","detect_all",- "detect_close_fleet","detect_spawn",- "expects_several","owns_turn",- "references_recent_fleet",- "spawn_instruction",- "spawn_includes_task","wants_split",]diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 52eb80c298..4c0febf532 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -5810,48 +5810,6 @@ class BrainManager:conversation_language=self._conversation_language,)- # A clarified pane is briefed with the ORIGINAL utterance — the sentence- # that actually carried the work — not with the "yes" that confirmed it.- if answered is not None:- panes, original = answered- # Every pane the answer confirmed, not the first one: "Alex und- # Blaike, macht beide …" is ONE instruction for two agents, and a- # single "yes" has to brief both of them. Answering it with one- # pane is how the second agent of an addressed pair was lost (live- # 2026-07-27 19:07).- live = [name for name in panes if session.find(name) is not None]- if live:- log.info(- "Agentic IDE: clarified call-sign(s) resolved to %s",- ", ".join(live),- )- return await self._deliver_agentic_ide_prompt(- session=session,- names=live,- utterance=original,- instruction="",- language=out_lang,- )-- if not addressed:- # No pane was named with certainty — but the turn may still have- # MEANT one. A call-sign arrives through speech recognition, and the- # live 2026-07-27 failure was exactly this: "Ellis" came back as- # "Ilies", scored just under the acting threshold, and this path- # returned None without a word. Nothing reached the pane, nothing- # was said, and the live model — which never learns any of this —- # filled the silence by claiming an agent was working.- #- # Asking costs the user one word and cannot type a stranger's- # sentence into a coding agent, so uncertainty resolves to a- # question. ``detect_clarification`` decides when there is one to- # ask; it stands down for anything that is not addressing the- # workspace.- return self._ask_which_agentic_ide_terminal(- user_text, candidates=candidates, language=out_lang- )- found = addressed[0]-# A question about a pane is read-only: answer it from what that pane# printed, and let the normal brain path phrase the answer with the# focus-context block (which already carries the transcript tail).@@ -5860,17 +5818,6 @@ class BrainManager:names = [item.terminal for item in addressed]- # A turn addresses a FLEET, and speech recognition may have carried- # only part of it across. "Alex und Blaike, macht beide einen Deep- # Dive" resolves Alex and mangles Blake, and this path used to brief- # Alex and say nothing at all about the rest — so the user heard one- # agent confirmed and believed two were working (live 2026-07-27- # 19:07). The pane that WAS understood still gets its brief; the one- # that was not becomes a question appended to the same answer.- leftover = self._agentic_ide_leftover_question(- user_text, candidates=candidates, claimed=names, language=out_lang- )-# NOTHING is spoken between here and the delivery verdict below, and that# silence is the feature. A bridge line lived here for a few hours on# 2026-07-27 to fill the prompt writer's 10-21 s, and it produced the@@ -5913,334 +5860,28 @@ class BrainManager:log.warning("Agentic IDE work split failed", exc_info=True)assignments = None- verdict = await self._deliver_agentic_ide_prompt(- session=session,- names=names,- utterance=user_text,- instruction=found.instruction,- language=out_lang,- assignments=assignments,- )- if leftover is not None:- # Armed only now: a question about the rest of the fleet is worth- # asking once the panes that WERE understood are actually briefed,- # and a delivery that failed on the way there should not leave a- # question standing about work nobody received.- need, question = leftover- ide_clarify.WINDOW.arm(need, question=question)- log.info(- "Agentic IDE: briefed %s, asking about %s",- ", ".join(names),- " / ".join(need.offered),- )- return f"{verdict} {question}" if verdict else question- return verdict-- async def _deliver_agentic_ide_prompt(- self,- *,- session: Any,- names: list[str],- utterance: str,- instruction: str,- language: str,- assignments: dict[str, str] | None = None,- ) -> str | None:- """Compose and type one instruction into the addressed panes.-- Shared by the addressed-terminal path and by the answer to a "did you- mean …?" question, so a clarified pane is briefed through exactly the- same composer and reported by exactly the same verdict line. A second- delivery site would be free to drift into announcing something it did- not do, which is the failure class this whole area exists to prevent.-- No brain is pinned for the composer on purpose. An earlier version- handed it this turn's FAST router model to save 4-5 s, but that- optimised the wrong axis: the prompt is what the coding agent then- works from for minutes, and the maintainer's decision on 2026-07-25- was explicitly for the better prompt over the quicker handoff. The- composer resolves a quality-tier model itself and degrades to its- deterministic prompt when none is reachable.- """- from jarvis.agentic_ide import fanout as ide_fanout-- # Returning None here would hand the turn to the model with nothing to- # go on, and a model asked about a pane it cannot see answers from the- # user's own question — which is precisely how "I have let Alex know"- # was spoken over a terminal that had received nothing (2026-07-27).- # A delivery that did not happen is a fact worth saying out loud, so- # every exit below carries one; ``deliver`` itself never raises for a- # single pane, so reaching these means the whole fan-out fell over.+ # No brain is pinned for the composer on purpose. An earlier version+ # handed it this turn's FAST router model to save 4-5 s, but that+ # optimised the wrong axis: the prompt is what the coding agent then+ # works from for minutes, and the maintainer's decision on 2026-07-25+ # was explicitly for the better prompt over the quicker handoff. The+ # composer resolves a quality-tier model itself and degrades to its+ # deterministic prompt when none is reachable.try:result = await ide_fanout.deliver(session=session,terminals=names,- utterance=utterance,- instruction=instruction,+ utterance=user_text,+ instruction=found.instruction,assignments=assignments,)except Exception: # noqa: BLE001 - never crash the turn over a panelog.warning("Agentic IDE fast-path failed", exc_info=True)- return action_phrase(- "ide_prompt_sent_nobody", language, failed=_join_names(names, language)- )-- if not result.deliveries:- log.warning(- "Agentic IDE fast-path: fan-out returned no verdicts for %s",- ", ".join(names),- )- return action_phrase(- "ide_prompt_sent_nobody", language, failed=_join_names(names, language)- )- return _fanout_reply_line(result, language)-- def _ask_which_agentic_ide_terminal(- self,- user_text: str,- *,- candidates: list[str],- language: str,- ) -> str | None:- """Ask which pane was meant, or ``None`` when there is nothing to ask.-- The question is armed as a one-shot window: the user's next turn ("ja",- "Ellis") delivers the ORIGINAL instruction to the confirmed pane, so- clarifying costs one word rather than a repeated sentence.- """- try:- from jarvis.agentic_ide import clarify as ide_clarify- except Exception: # noqa: BLE001 - optional surface- return None- try:- need = ide_clarify.detect_clarification(user_text, names=candidates)- except Exception: # noqa: BLE001 - a detector fault stays silent- return None- if need is None:- return None-- question = self._agentic_ide_clarify_question(need, language)- ide_clarify.WINDOW.arm(need, question=question)- log.info(- "Agentic IDE: heard %r, asking whether %s was meant",- " / ".join(item.spoken for item in need.uncertain),- " / ".join(need.offered),- )- return question-- @staticmethod- def _agentic_ide_clarify_question(- need: Any, language: str, *, also: bool = False- ) -> str:- """The spoken question for one uncertain call-sign, or for a list.-- Three shapes, because they mean three different things and a user has- to be able to answer each with one word: one pane offered ("did you- mean Blake?"), one word that could be several panes ("Max OR- Maggie?"), and several garbled names in one list ("Alex AND Blake?").- Joining the last one with "or" would ask the user to pick between two- agents they had just addressed together.- """- spoken = need.spoken- if len(need.uncertain) > 1:- heard = [item.spoken for item in need.uncertain]- spoken = action_phrase("join_and", language).join(- (", ".join(heard[:-1]), heard[-1])- )-- offered = need.offered- if len(need.uncertain) == 1 and len(offered) == 1:- if also:- return action_phrase(- "ide_terminal_clarify_also",- language,- spoken=spoken,- names=offered[0],- )- return action_phrase(- "ide_terminal_clarify_one", language, spoken=spoken, name=offered[0]- )- # Alternatives for ONE word are offered with "or"; a list of separate- # names is joined with "and", because both were meant.- joiner = "join_and" if len(need.uncertain) > 1 else "join_or"- joined = action_phrase(joiner, language).join(- (", ".join(offered[:-1]), offered[-1])- )- return action_phrase(- "ide_terminal_clarify_also" if also else "ide_terminal_clarify_many",- language,- spoken=spoken,- names=joined,- )-- def _agentic_ide_leftover_question(- self,- user_text: str,- *,- candidates: list[str],- claimed: list[str],- language: str,- ) -> tuple[Any, str] | None:- """A question about the addressees this turn named but did not resolve.-- Returns ``(need, question)`` when the utterance addressed panes BEYOND- the ones about to be briefed, else ``None``. The caller arms it after- the delivery, so the user hears which agents really got the work before- being asked about the rest.-- Nothing is asked when every uncertain word points at a pane that is- already being briefed — that is the same addressee reached twice, not a- second one.- """- try:- from jarvis.agentic_ide import clarify as ide_clarify- from jarvis.agentic_ide import intent as ide_intent-- need = ide_clarify.detect_clarification(user_text, names=candidates)- except Exception: # noqa: BLE001 - a detector fault stays silent- return None-- already = {name.casefold() for name in claimed}- if need is not None and not all(- all(name.casefold() in already for name in item.candidates)- for item in need.uncertain- ):- return need, self._agentic_ide_clarify_question(need, language, also=True)-- # No word came close enough to name a pane — and a call-sign can be- # mangled past every threshold there is ("Dave" for a pool that holds- # none). What survives that is the COUNT the user stated out loud:- # "both of you" says two agents were addressed however badly the names- # travelled. Briefing one and saying nothing is the failure this- # catches — the user hears one name confirmed and believes two are- # working (live 2026-07-27 19:07).- try:- if not ide_intent.expects_several(user_text):- return None- except Exception: # noqa: BLE001 - a detector fault stays silent- return None- if len(claimed) > 1:return None- rest = tuple(name for name in candidates if name.casefold() not in already)- if not rest:- return None- # Armed over every OTHER pane, so the next word ("Blake") delivers the- # original task. A bare "yes" decides nothing here and must not: there- # is no candidate to confirm, only panes to choose between.- unresolved = ide_clarify.ClarificationNeeded(- uncertain=(ide_clarify.UncertainName(spoken="", candidates=rest),),- utterance=user_text,- certain=tuple(claimed),- )- return unresolved, action_phrase(- "ide_terminal_who_else", language, names=", ".join(claimed)- )- async def _brief_spawned_agentic_ide_fleet(- self,- session: Any,- names: list[str],- user_text: str,- ) -> None:- """Brief newly mounted Codex panes once their real input lines exist."""- from jarvis.agentic_ide import fanout as ide_fanout- from jarvis.agentic_ide import intent as ide_intent- from jarvis.agentic_ide.fleet_actions import wait_for_prompt_ready-- instruction = ide_intent.spawn_instruction(user_text)- assignments: dict[str, str] | None = None- if len(names) > 1 and ide_intent.wants_split(user_text):- try:- from jarvis.agentic_ide import work_split as ide_split-- plan = await ide_split.split(- instruction,- session=session,- count=len(names),- )- assignments = {- name: item.task- for name, item in zip(names, plan.assignments, strict=False)- }- except Exception: # noqa: BLE001 - the common brief is still usable- log.warning("Agentic IDE spawned-fleet split failed", exc_info=True)-- ready = await wait_for_prompt_ready(session, names)- missing = [name for name in names if name not in ready]- if missing:- log.warning(- "Agentic IDE spawned-fleet briefing: panes never became ready: %s",- ", ".join(missing),- )- if not ready:- return-- result = await ide_fanout.deliver(- session=session,- terminals=ready,- utterance=user_text,- instruction=instruction,- assignments=assignments,- )- log.info(- "Agentic IDE spawned-fleet briefing: %d of %d prompts delivered",- len(result.delivered),- len(names),- )-- async def _run_agentic_ide_close_fast_path(- self,- user_text: str,- *,- trace_id: UUID | None = None,- ) -> str | None:- """Close an explicitly requested terminal fleet without model routing."""- try:- from jarvis.agentic_ide import intent as ide_intent- from jarvis.agentic_ide.fleet_actions import (- close_agent_terminals,- terminals_closed_event,- )- from jarvis.agentic_ide.session import get_registry-- request = ide_intent.detect_close_fleet(user_text)- except Exception: # noqa: BLE001 - optional surface- return None- if request is None:+ if not result.deliveries:return None-- out_lang = resolve_output_language(- self._reply_language,- "unknown",- user_text,- default=DEFAULT_LOCALE,- conversation_language=self._conversation_language,- )- registry = get_registry()- session = registry.session- if session is None:- return action_phrase("ide_terminals_none_to_close", out_lang)- closed = await close_agent_terminals(registry, request.agent)- if not closed:- return action_phrase("ide_terminals_none_to_close", out_lang)- if self._bus is not None:- try:- await self._bus.publish(- terminals_closed_event(- session,- closed,- source_layer="brain.agentic_ide_close",- )- )- except Exception: # noqa: BLE001 - the terminals are already closed- log.warning("Agentic IDE close: UI notification failed", exc_info=True)- names = [term.name for term in closed]- return action_phrase(- "ide_terminals_closed",- out_lang,- count=len(names),- names=_join_names(names, out_lang),- )+ return _fanout_reply_line(result, out_lang)async def _run_agentic_ide_spawn_fast_path(self,diff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.pyindex d1e990133e..5045addaea 100644--- a/jarvis/commands/registry.py+++ b/jarvis/commands/registry.py@@ -89,24 +89,6 @@ def _provider_ids(tier: str, *, brain_switchable_only: bool = False) -> list[strreturn sorted(ids)-def _coding_agent_ids() -> list[str]:- """Coding CLIs a workspace pane can run, from the ONE agent registry.-- Never a literal list. A registered CLI that the voice schema does not know- about is unreachable by voice while being fully supported everywhere else —- the pane opens from the UI, resumes, accepts prompts, and is simply absent- from the one surface that is supposed to drive it. Reading the registry is- what lets a newly registered agent be spawned the day it lands, without a- second table remembering to agree (the same rule §5 sets for providers:- gate on the capability, never on a name someone typed twice).- """- try:- from jarvis.workspace.agents import coding_agent_names- except Exception: # pragma: no cover - defensive: registry must not crash- return []- return sorted(coding_agent_names())--def _all_provider_ids() -> list[str]:try:from jarvis.ui.web.provider_spec import PROVIDERS@@ -679,18 +661,11 @@ def _build_registry() -> tuple[AppCommand, ...]:id="agentic-ide-prompt",title="Prompt an Agentic-IDE terminal",description=(- "Send an instruction to the coding agent in ONE named terminal. "+ "Send an instruction to the coding agent in a named terminal. ""Use this whenever the user tells a terminal to do something ""('tell Kai to ...', 'Mika soll ...', 'let Nova refactor ...') ""— that work belongs to that agent, never to a background "- "worker. For SEVERAL terminals ('Kai and Mika both ...', 'let "- "the two of them ...') call 'agentic-ide-fanout' instead, with "- "every call-sign in 'terminals': it briefs them at once and "- "reports which ones really got the work. Calling this command "- "twice for a pair leaves the second agent idle whenever the "- "second call is forgotten, which is the failure mode fanout "- "exists to remove. "- "Pass the instruction in the USER's words: everything "+ "worker. Pass the instruction in the USER's words: everything ""they asked for, every constraint and file they named, nothing ""invented and nothing summarised away. Do NOT write the brief ""yourself — a prompt writer that has read this repository turns "@@ -743,105 +718,17 @@ def _build_registry() -> tuple[AppCommand, ...]:"es": ("dile a mika que ejecute las pruebas",), # i18n-allow: input vocab},),- AppCommand(- id="agentic-ide-fanout",- title="Open and brief Agentic-IDE terminals in one step",- description=(- "Give ONE task to coding terminals — existing ones, brand-new "- "ones, or both — in a single call. This is the ONLY correct way "- "to handle 'if no terminal is called that, open one and prompt "- "it' and 'spawn N terminals and let them do X': pass the work as "- "'instruction', the panes to brief as 'terminals', and the panes "- "to open first as 'spawn'. Never emulate it by opening panes and "- "then prompting — call-signs are assigned automatically, so a "- "pane you open is NOT called the name you had in mind, and "- "re-spawning after a failed prompt just leaves blank panes "- "behind. Set 'split' true only when the user asked for the work "- "to be DIVIDED between the agents. "- "CHECK THE REPLY: 'delivered' names the agents that really got "- "the task and 'undelivered' those that did not — report both, "- "and use the call-signs the reply gives you."- ),- method="POST",- path="/api/agentic-ide/fanout",- params={- "type": "object",- "properties": {- "instruction": _str_param(- "The work the agents should do, in plain words.",- min_length=1,- max_length=4000,- ),- "terminals": {- "type": "array",- "items": {"type": "string"},- "description": (- "Call-signs of running terminals to brief. Leave "- "empty to brief only the newly opened panes."- ),- },- "spawn": {- "type": "array",- "items": {- "type": "object",- "properties": {- "count": {- "type": "integer",- "description": "Panes to open in this group.",- },- "agent": {- "type": "string",- "enum": _coding_agent_ids() or None,- "description": (- "Coding agent for this group; omit to "- "inherit the last pane's."- ),- },- },- "required": ["count"],- },- "description": (- "Panes to open before briefing, group by group. "- "Only the newly opened panes are briefed, so agents "- "already working are not interrupted."- ),- },- "split": {- "type": "boolean",- "default": False,- "description": (- "Divide the instruction into one distinct assignment "- "per agent instead of giving all of them the same "- "brief."- ),- },- },- "required": ["instruction"],- },- ui_section="agentic-ide",- voice_aliases={- # i18n-allow: input vocab- "de": ("spawne ein terminal und lass es die tests fixen",),- "en": ("open a terminal and have it fix the tests",),- "es": ("abre una terminal y que arregle las pruebas",), # i18n-allow: input vocab- },- ),AppCommand(id="agentic-ide-spawn-terminals",title="Open more Agentic-IDE terminals",description=("Open one or more additional coding terminals in the open "- "workspace, WITHOUT giving them work. Use this only when the "- "user asks for bare panes ('spawn five new Claude Code "- "terminals', 'open two more Codex terminals') — that is a "- "request for workspace panes, never for a background worker. "- "When the new panes are also meant to DO something, use "- "'agentic-ide-fanout' instead, which opens and briefs them in "- "one step. Pass count, and agent only when the user named one "- "('claude' or 'codex'); omitted, the new panes run whatever the "- "last pane runs. Their call-signs are assigned automatically — "- "the reply's names are the only way to address them, and calling "- "this again never produces a name you picked. "+ "workspace. Use this when the user asks for MORE TERMINALS / "+ "panes ('spawn five new Claude Code terminals', 'open two more "+ "Codex terminals') — that is a request for workspace panes, "+ "never for a background worker. Pass count, and agent only when "+ "the user named one ('claude' or 'codex'); omitted, the new "+ "panes run whatever the last pane runs. ""CHECK THE REPLY: 'capped' true means the workspace maximum cut ""the request short — say how many actually opened and name them, ""never report the full number as done."@@ -858,7 +745,7 @@ def _build_registry() -> tuple[AppCommand, ...]:},"agent": {"type": "string",- "enum": _coding_agent_ids() or None,+ "enum": ["claude", "codex"],"description": ("Coding agent for the new panes; omit to inherit ""the last pane's."@@ -932,7 +819,7 @@ def _build_registry() -> tuple[AppCommand, ...]:"properties": {"agent": _str_param("Coding agent whose terminals should be closed.",- enum=_coding_agent_ids() or None,+ enum=["claude", "codex"],),},"required": ["agent"],diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsxindex e9788195ce..3e5ad59213 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx@@ -3,12 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Terminal } from "@xterm/xterm";import { PaneScrollbar } from "./PaneScrollbar";-import {- PROBE_RETURN_MS,- PROBE_STALE_MS,- PROBE_WAIT_MS,- SETTLE_MS,-} from "./paneAppScroll";+import { LINES_PER_NOTCH } from "./paneScrollModel";const REGION = { top: 0, bottom: 300, left: 0, right: 400 };const TRACK_PX = 300;@@ -21,49 +16,38 @@ interface FakeOptions {mouseTrackingMode?: string;}-/** A screen of agent output — rows recognisable enough to be tracked. */-function transcript(from: number, count: number): string[] {- return Array.from({ length: count }, (_, i) => `line ${from + i} of output`);-}-function fakeTerminal({type = "normal",length = 1000,rows = 24,- viewportY = 0,+ viewportY = 976,mouseTrackingMode = "none",-}: FakeOptions = {}) {+}: FakeOptions = {}): Terminal {const noop = () => ({ dispose() {} });- let content = transcript(1, rows);- const term = {+ return {rows,modes: { mouseTrackingMode },buffer: {- active: {- type,- length,- viewportY,- baseY: length - rows,- getLine: (index: number) =>- index >= 0 && index < content.length- ? { translateToString: () => content[index] }- : undefined,- },+ active: { type, length, viewportY, baseY: length - rows },onBufferChange: noop,},- onScroll: noop,onRender: noop,onResize: noop,+ onScroll: noop,scrollToLine: vi.fn(),scrollLines: vi.fn(),} as unknown as Terminal;- return {- term,- /** What the CLI repaints after it handled a relayed wheel notch. */- show(next: string[]) {- content = next;- },- };+}++/** A Claude-Code-style pane: the CLI owns the screen and the wheel. */+function appTerminal(rows = 24): Terminal {+ return fakeTerminal({+ type: "alternate",+ length: rows,+ rows,+ viewportY: 0,+ mouseTrackingMode: "any",+ });}function Harness({ term }: { term: Terminal }) {@@ -87,30 +71,47 @@ function Harness({ term }: { term: Terminal }) {);}-/** Move the pointer into the strip along the pane's right edge. */-function reachForTheBar() {- fireEvent.mouseMove(screen.getByTestId("region"), {- clientX: REGION.right - 6,- clientY: 150,- });+/**+ * A pointer move with coordinates on it.+ *+ * jsdom ships no `PointerEvent`, and the synthetic one Testing Library falls+ * back to arrives without `clientY` — so a drag driven by `fireEvent.pointerMove`+ * silently moves the thumb nowhere. A `MouseEvent` of the same type carries the+ * coordinates the handler reads.+ */+function dragTo(element: Element, clientY: number) {+ fireEvent(element, new MouseEvent("pointermove", { clientY, bubbles: true }));}-function thumbTop(): number {- return parseFloat(- screen.getByTestId("pane-scrollbar-thumb-Dana").style.top || "0",- );+const bar = () => screen.queryByTestId("pane-scrollbar-Dana");+const thumb = () => screen.getByTestId("pane-scrollbar-thumb-Dana");+const thumbTop = () => parseFloat(thumb().style.top || "0");+const thumbHeight = () => parseFloat(thumb().style.height || "0");++function reachThePane() {+ fireEvent.mouseEnter(screen.getByTestId("region"));}-function thumbHeight(): number {- return parseFloat(- screen.getByTestId("pane-scrollbar-thumb-Dana").style.height || "0",- );+function leaveThePane() {+ fireEvent.mouseLeave(screen.getByTestId("region"));+}++/** What the CLI is handed when the bar relays a notch. */+function watchRelays(): number[] {+ const relayed: number[] = [];+ document+ .querySelector(".xterm-screen")!+ .addEventListener("wheel", (event) => {+ relayed.push((event as WheelEvent).deltaY);+ });+ return relayed;}describe("PaneScrollbar", () => {beforeEach(() => {- // jsdom measures nothing, and both the hover zone and the thumb's size are- // pure geometry — so the two measurements the component takes are staged.+ // jsdom measures nothing, and both the track's height and the pane's box+ // are pure geometry — so the two measurements the component takes are+ // staged here.Object.defineProperty(HTMLElement.prototype, "clientHeight", {configurable: true,value: TRACK_PX,@@ -130,493 +131,176 @@ describe("PaneScrollbar", () => {vi.restoreAllMocks();});- it("stays out of the way until the pointer reaches for it", () => {- render(<Harness term={fakeTerminal().term} />);+ it("stays out of the way until the pointer arrives", () => {+ render(<Harness term={fakeTerminal()} />);- expect(screen.queryByTestId("pane-scrollbar-Dana")).toBeNull();+ expect(bar()).toBeNull();- reachForTheBar();+ reachThePane();- const bar = screen.getByTestId("pane-scrollbar-Dana");- expect(bar.dataset.shown).toBe("true");- expect(bar.className).toContain("opacity-100");- expect(screen.getByTestId("pane-scrollbar-thumb-Dana")).toBeTruthy();+ expect(bar()!.dataset.shown).toBe("true");+ expect(bar()!.className).toContain("opacity-100");});- it("fades out again once the pointer leaves the edge", () => {+ /*+ * The bug this rewrite exists for, at the level a user meets it. Reaching a+ * Claude Code pane must produce a bar — full stop. The version before this one+ * asked the CLI to prove it had a history first, and every way that question+ * could go unanswered looked exactly like "nothing to scroll", so the bar+ * never appeared in the one kind of pane it was written for.+ */+ it("gives an application-held pane a bar, with nothing measured at all", () => {+ render(<Harness term={appTerminal()} />);++ reachThePane();++ expect(bar()!.dataset.shown).toBe("true");+ // Standing at the newest output: the thumb sits at the bottom.+ expect(thumbTop() + thumbHeight()).toBe(TRACK_PX);+ });++ it("fades out again once the pointer leaves", () => {vi.useFakeTimers();try {- render(<Harness term={fakeTerminal().term} />);- reachForTheBar();- fireEvent.mouseMove(screen.getByTestId("region"), {- clientX: 40,- clientY: 150,- });+ render(<Harness term={fakeTerminal()} />);+ reachThePane();+ leaveThePane();act(() => vi.advanceTimersByTime(1000));} finally {vi.useRealTimers();}- const bar = screen.getByTestId("pane-scrollbar-Dana");- expect(bar.dataset.shown).toBe("false");- expect(bar.className).toContain("opacity-0");+ expect(bar()!.dataset.shown).toBe("false");+ expect(bar()!.className).toContain("opacity-0");// Invisible AND intangible — a transparent strip that still swallowed// clicks would break selecting text at the pane's right edge.- expect(bar.className).toContain("pointer-events-none");+ expect(bar()!.className).toContain("pointer-events-none");});- /*- * The fourth report, and the one that settled where the burden of proof lies.- *- * For one round this pane showed NOTHING until a measurement had been taken,- * so that an unscrolled pane would not spend half its track on an assumed- * screenful of history. Every failure to measure then looked exactly like- * "this pane cannot scroll", and the bar stayed unreachable in the only kind- * of pane it was written for — reported four times, always as "it works in a- * Codex pane and nowhere else". A Codex pane never needed a measurement.- *- * So reaching for the edge of a Claude Code pane gives you a bar you can drag- * immediately, sized from the least its history could be. Only a measurement- * that positively found nothing takes it away again (below).- */- it("gives a Claude-Code-style pane a bar the moment you reach for it", () => {+ it("shows nothing on a pane with nothing to scroll", () => {+ render(<Harness term={fakeTerminal({ length: 24, rows: 24 })} />);++ reachThePane();++ expect(bar()).toBeNull();+ });++ it("draws a scrolled-back terminal's thumb where it actually stands", () => {render(- <Harness- term={- fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- }).term- }- />,+ <Harness term={fakeTerminal({ length: 1000, rows: 24, viewportY: 0 })} />,);- reachForTheBar();+ reachThePane();- const bar = screen.getByTestId("pane-scrollbar-Dana");- expect(bar.dataset.mode).toBe("app");- expect(bar.dataset.shown).toBe("true");- // Sitting at the newest output, which is where an unscrolled pane is.- expect(thumbTop() + thumbHeight()).toBe(TRACK_PX);+ // At the very top of the scrollback.+ expect(thumbTop()).toBe(0);});- /*- * The third report, and the one that made the bar unusable rather than merely- * wrong: in a Claude Code pane there was NO WAY to bring it up. The measurement- * only ever happened as a side effect of a wheel turn, so reaching for the edge- * — the gesture the bar is revealed by — left the pane silent forever, and the- * one input that did work is the one that makes a scrollbar unnecessary.- *- * So reaching for it now ASKS: a notch back, a settle period, a notch home. The- * bar arrives describing a real measurement, and the pointer never moved the- * user anywhere.- */- it("asks the CLI for its history when the pointer reaches for the bar", () => {- vi.useFakeTimers();- try {- const pane = fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- });- const relayed: number[] = [];- render(<Harness term={pane.term} />);- document- .querySelector(".xterm-screen")!- .addEventListener("wheel", (event) => {- const delta = (event as WheelEvent).deltaY;- relayed.push(delta);- // The CLI answers the probe: one line of older output, then home.- pane.show(- delta < 0- ? [...transcript(0, 1), ...transcript(1, 23)]- : transcript(1, 24),- );- });-- reachForTheBar();- act(() =>- vi.advanceTimersByTime(PROBE_WAIT_MS + PROBE_RETURN_MS + SETTLE_MS * 2),- );-- // Asked, and brought back — the user is still at the newest output.- expect(relayed).toEqual([-1, 1]);- // And the bar is there now, describing what was measured.- const bar = screen.getByTestId("pane-scrollbar-Dana");- expect(bar.dataset.mode).toBe("app");- expect(bar.dataset.shown).toBe("true");- expect(thumbTop() + thumbHeight()).toBe(TRACK_PX);- } finally {- vi.useRealTimers();- }- });+ it("scrolls the terminal itself when the terminal owns the history", () => {+ const term = fakeTerminal();+ render(<Harness term={term} />);+ reachThePane();- /*- * The probe is a one-off. It moves the application by a notch and back, which- * nobody notices once — and would be a visible twitch on every pass of the- * pointer along the pane's edge.- */- it("asks only once per terminal", () => {- vi.useFakeTimers();- try {- const pane = fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- });- const relayed: number[] = [];- render(<Harness term={pane.term} />);- document- .querySelector(".xterm-screen")!- .addEventListener("wheel", (event) => {- relayed.push((event as WheelEvent).deltaY);- pane.show(- (event as WheelEvent).deltaY < 0- ? [...transcript(0, 1), ...transcript(1, 23)]- : transcript(1, 24),- );- });-- reachForTheBar();- act(() =>- vi.advanceTimersByTime(PROBE_WAIT_MS + PROBE_RETURN_MS + SETTLE_MS * 2),- );- // Pointer leaves and comes back.- fireEvent.mouseMove(screen.getByTestId("region"), {- clientX: 40,- clientY: 150,- });- act(() => vi.advanceTimersByTime(1000));- reachForTheBar();- act(() =>- vi.advanceTimersByTime(PROBE_WAIT_MS + PROBE_RETURN_MS + SETTLE_MS * 2),- );+ fireEvent.wheel(bar()!, { deltaY: -1 });- expect(relayed).toEqual([-1, 1]);- } finally {- vi.useRealTimers();- }+ expect(term.scrollLines).toHaveBeenCalledWith(-LINES_PER_NOTCH);});/*- * The one answer that expires. A pane opened a minute ago holds a single screen- * and nothing above it, so the first probe honestly finds no history — and a- * pane is at its emptiest exactly when somebody first reaches for its edge. Ten- * minutes of an agent printing later there are pages of it, and treating that- * first reading as final would leave the pane bar-less for good: the original- * bug arriving through a different door.+ * And hands the wheel to the CLI when the CLI owns the screen — the only+ * language a full-screen application listens in. Emitted as a real wheel+ * event so that xterm encodes it in whichever mouse protocol was negotiated.*/- it("asks again once a pane that had no history has had time to fill up", () => {- vi.useFakeTimers();- try {- const pane = fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- });- const relayed: number[] = [];- let hasHistory = false;- render(<Harness term={pane.term} />);- document- .querySelector(".xterm-screen")!- .addEventListener("wheel", (event) => {- const delta = (event as WheelEvent).deltaY;- relayed.push(delta);- // Nothing above the screen at first, so the CLI repaints unchanged.- if (!hasHistory) return;- pane.show(- delta < 0- ? [...transcript(0, 1), ...transcript(1, 23)]- : transcript(1, 24),- );- });-- const reachAndWait = () => {- reachForTheBar();- act(() =>- vi.advanceTimersByTime(- PROBE_WAIT_MS + PROBE_RETURN_MS + SETTLE_MS * 2,- ),- );- // Pointer away again, so the next reach is a fresh one.- fireEvent.mouseMove(screen.getByTestId("region"), {- clientX: 40,- clientY: 150,- });- act(() => vi.advanceTimersByTime(1000));- };-- reachAndWait();- expect(relayed).toEqual([-1, 1]);- expect(screen.queryByTestId("pane-scrollbar-Dana")).toBeNull();-- // Straight away, the answer still stands — no second probe.- reachAndWait();- expect(relayed).toEqual([-1, 1]);-- // A while later the pane has printed, and the question is worth asking- // again.- hasHistory = true;- act(() => vi.advanceTimersByTime(PROBE_STALE_MS));- reachForTheBar();- act(() =>- vi.advanceTimersByTime(PROBE_WAIT_MS + PROBE_RETURN_MS + SETTLE_MS * 2),- );-- expect(relayed).toEqual([-1, 1, -1, 1]);- expect(screen.getByTestId("pane-scrollbar-Dana").dataset.mode).toBe(- "app",- );- } finally {- vi.useRealTimers();- }+ it("hands the wheel to a CLI that owns the screen", () => {+ render(<Harness term={appTerminal()} />);+ reachThePane();+ const relayed = watchRelays();++ fireEvent.wheel(bar()!, { deltaY: -1 });++ expect(relayed).toEqual([-1]);});- /*- * The same rule for the question that was never answered at all — a notch- * relayed into a terminal that was still being built, or while the agent was- * repainting its whole screen. Nothing is measured either way, so the pane- * looks exactly like one with no history: no bar. Treating only an explicit- * "nothing here" as re-askable left such a pane one unlucky probe away from- * having no scrollbar for the rest of its life, which is the original bug- * with a rarer trigger.- */- it("asks again when the first probe went unanswered", () => {- vi.useFakeTimers();- try {- const pane = fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- });- const relayed: number[] = [];- render(<Harness term={pane.term} />);- const host = document.querySelector(".agentic-terminal-host")!;- const paneScreen = host.querySelector(".xterm-screen")!;- paneScreen.addEventListener("wheel", (event) => {- const delta = (event as WheelEvent).deltaY;- relayed.push(delta);- pane.show(- delta < 0- ? [...transcript(0, 1), ...transcript(1, 23)]- : transcript(1, 24),- );- });- // The terminal is not up yet: there is nothing to hand a notch to.- paneScreen.remove();-- reachForTheBar();- act(() =>- vi.advanceTimersByTime(PROBE_WAIT_MS + PROBE_RETURN_MS + SETTLE_MS * 2),- );- expect(relayed).toEqual([]);-- // Pointer away, the terminal arrives, and the question is asked again.- fireEvent.mouseMove(screen.getByTestId("region"), {- clientX: 40,- clientY: 150,- });- host.appendChild(paneScreen);- act(() => vi.advanceTimersByTime(PROBE_STALE_MS));- reachForTheBar();- act(() =>- vi.advanceTimersByTime(PROBE_WAIT_MS + PROBE_RETURN_MS + SETTLE_MS * 2),- );-- expect(relayed).toEqual([-1, 1]);- expect(screen.getByTestId("pane-scrollbar-Dana").dataset.mode).toBe(- "app",- );- } finally {- vi.useRealTimers();- }+ it("pages towards a click on the empty part of the track", () => {+ const term = fakeTerminal({ rows: 24 });+ render(<Harness term={term} />);+ reachThePane();++ // The thumb sits at the bottom, so a click at the top pages backwards.+ fireEvent.pointerDown(bar()!, { clientY: REGION.top + 4 });++ expect(term.scrollLines).toHaveBeenCalledWith(-23);});- /*- * And it is only for panes whose application holds the history. A terminal that- * owns its scrollback already reports the truth, and a relayed notch there would- * scroll the user's view for no reason at all.- */- it("asks nothing of a pane whose terminal owns its scrollback", () => {- vi.useFakeTimers();- try {- render(<Harness term={fakeTerminal({ length: 1000 }).term} />);- const relayed: number[] = [];- document- .querySelector(".xterm-screen")!- .addEventListener("wheel", (event) =>- relayed.push((event as WheelEvent).deltaY),- );-- reachForTheBar();- act(() =>- vi.advanceTimersByTime(PROBE_WAIT_MS + PROBE_RETURN_MS + SETTLE_MS * 2),- );-- expect(relayed).toEqual([]);- // It needed no asking: the bar is up on its own.- expect(screen.getByTestId("pane-scrollbar-Dana").dataset.mode).toBe(- "scrollback",- );- } finally {- vi.useRealTimers();- }+ it("takes a dragged thumb straight to the line it was dropped on", () => {+ const term = fakeTerminal({ length: 1000, rows: 24, viewportY: 976 });+ render(<Harness term={term} />);+ reachThePane();+ const grabbed = thumbTop();++ fireEvent.pointerDown(thumb(), { clientY: 200, pointerId: 1 });+ dragTo(thumb(), 200 - grabbed);++ // Dragged to the top of the track: the top of the scrollback.+ expect(term.scrollToLine).toHaveBeenLastCalledWith(0);++ fireEvent.pointerUp(thumb(), { pointerId: 1 });});- /*- * The FIRST reported bug, which the silence above must not undo: once the pane- * has been scrolled and brought back to the agent's newest output, its thumb- * sits at the BOTTOM. It used to draw a short bright marking halfway up the- * track, which reads as "you are in the middle" to everyone who has ever used- * a scrollbar.- */- it("puts a scrolled pane's thumb at the live end once it returns there", () => {- vi.useFakeTimers();- try {- const pane = fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- });- render(<Harness term={pane.term} />);- reachForTheBar();-- // Back four lines into the history, then all the way home again.- fireEvent.wheel(document.querySelector(".xterm-screen")!, {- deltaY: -1,- deltaMode: 1,- });- pane.show([...transcript(-3, 4), ...transcript(1, 20)]);- act(() => vi.advanceTimersByTime(SETTLE_MS));-- fireEvent.wheel(document.querySelector(".xterm-screen")!, {- deltaY: 1,- deltaMode: 1,- });- pane.show(transcript(1, 24));- act(() => vi.advanceTimersByTime(SETTLE_MS));-- expect(screen.getByTestId("pane-scrollbar-Dana").dataset.mode).toBe(- "app",- );- expect(thumbTop() + thumbHeight()).toBe(TRACK_PX);- // And nothing is drawn on the thumb that could be read as a position of- // its own.- expect(screen.queryByTestId("pane-scrollbar-grip-Dana")).toBeNull();- } finally {- vi.useRealTimers();- }+ it("drags an application-held pane by relaying notches", () => {+ render(<Harness term={appTerminal(24)} />);+ reachThePane();+ const relayed = watchRelays();+ const grabbed = thumbTop();++ fireEvent.pointerDown(thumb(), { clientY: 200, pointerId: 1 });+ dragTo(thumb(), 200 - grabbed);+ fireEvent.pointerUp(thumb(), { pointerId: 1 });++ // A full drag up asks for the whole assumed span — one screen, in notches.+ expect(relayed.length).toBe(Math.trunc(24 / LINES_PER_NOTCH));+ expect(new Set(relayed)).toEqual(new Set([-1]));});/*- * And it moves, because the position is measured rather than assumed: the- * screen's content travelling down the pane IS the user going back through- * the agent's own history.+ * A wheel turn over the pane keeps the bar up on its own, so the user can see+ * where they have got to without having to find its edge first.*/- it("moves the thumb up as the agent's screen scrolls back", () => {+ it("shows itself while the pane is being scrolled", () => {vi.useFakeTimers();try {- const pane = fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- });- render(<Harness term={pane.term} />);- reachForTheBar();-- fireEvent.wheel(document.querySelector(".xterm-screen")!, {- deltaY: -1,- deltaMode: 1,- });- pane.show([...transcript(-3, 4), ...transcript(1, 20)]);- act(() => vi.advanceTimersByTime(SETTLE_MS));-- // The measurement is what brings the bar into the document at all, and it- // arrives already showing the position it measured: above the live end.- expect(thumbTop() + thumbHeight()).toBeLessThan(TRACK_PX);- expect(screen.getByTestId("pane-scrollbar-Dana").dataset.shown).toBe(- "true",- );+ render(<Harness term={appTerminal()} />);+ const host = document.querySelector(".agentic-terminal-host")!;++ fireEvent.wheel(host, { deltaY: -1 });+ act(() => vi.advanceTimersByTime(50));+ expect(bar()!.dataset.shown).toBe("true");++ act(() => vi.advanceTimersByTime(2000));+ expect(bar()!.dataset.shown).toBe("false");} finally {vi.useRealTimers();}});/*- * A full-screen application with no history at all says so by not moving, and- * then gets no bar rather than a thumb filling its own track.+ * And that turn is counted: a pane the user scrolled back through stands away+ * from its newest output, and its thumb has to say so the moment the bar comes+ * up — including on a CLI whose screen reveals nothing about where it is.*/- it("takes the bar away from an app that turns out not to scroll", () => {- vi.useFakeTimers();- try {- const pane = fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- });- render(<Harness term={pane.term} />);- reachForTheBar();-- fireEvent.wheel(document.querySelector(".xterm-screen")!, {- deltaY: -1,- deltaMode: 1,- });- act(() => vi.advanceTimersByTime(SETTLE_MS));-- expect(screen.queryByTestId("pane-scrollbar-Dana")).toBeNull();- } finally {- vi.useRealTimers();- }- });+ it("follows a CLI-held pane back through its own history", () => {+ render(<Harness term={appTerminal(24)} />);+ const host = document.querySelector(".agentic-terminal-host")!;- it("hands wheel turns over the bar to the CLI that owns the screen", () => {- vi.useFakeTimers();- try {- const pane = fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- });- render(<Harness term={pane.term} />);- reachForTheBar();-- // One measured notch, purely to bring the bar into the document: an- // app-mode pane nothing has been measured on draws none, so there would be- // nothing to turn a wheel over.- fireEvent.wheel(document.querySelector(".xterm-screen")!, {- deltaY: -1,- deltaMode: 1,- });- pane.show([...transcript(-3, 4), ...transcript(1, 20)]);- act(() => vi.advanceTimersByTime(SETTLE_MS));-- const relayed: number[] = [];- document- .querySelector(".xterm-screen")!- .addEventListener("wheel", (event) =>- relayed.push((event as WheelEvent).deltaY),- );-- fireEvent.wheel(screen.getByTestId("pane-scrollbar-Dana"), {- deltaY: 120,- });-- expect(relayed).toEqual([1, 1, 1]);- } finally {- vi.useRealTimers();- }- });+ for (let i = 0; i < 4; i += 1) fireEvent.wheel(host, { deltaY: -1 });+ reachThePane();- it("scrolls the viewport itself when the terminal holds the history", () => {- const { term } = fakeTerminal({ length: 1000 });- render(<Harness term={term} />);- reachForTheBar();+ // Away from the live end, so the thumb has left the bottom of the track.+ expect(thumbTop() + thumbHeight()).toBeLessThan(TRACK_PX);- fireEvent.wheel(screen.getByTestId("pane-scrollbar-Dana"), {- deltaY: -120,- });+ for (let i = 0; i < 8; i += 1) fireEvent.wheel(host, { deltaY: 1 });- expect(term.scrollLines).toHaveBeenCalledWith(-3);+ // Back at the newest output, however far past it the wheel was turned.+ expect(thumbTop() + thumbHeight()).toBe(TRACK_PX);});});diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsxindex 08cd3f1103..749fdadb3e 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx@@ -1,94 +1,140 @@/**- * A pane's own scrollbar — hidden until you reach for it.+ * A pane's scrollbar: there whenever the pointer is on the pane, gone when it+ * is not, and able to scroll whatever the pane happens to be running.*- * Replaces the native `.xterm-viewport` bar, for two reasons the CSS version- * could not solve:+ * ## Why the pane draws its own instead of styling the browser's*- * 1. **It was always there.** `overflow-y: scroll` draws a permanent track down- * the side of every pane, and in a grid of eight terminals that is eight- * stripes of furniture nobody asked for. This one appears when the pointer- * comes within reach of the pane's right edge, and while you are scrolled- * back through history — and is otherwise invisible.- * 2. **It only worked for half the CLIs.** Why, and what this does about it,- * is in ./paneScroll and ./paneAppScroll — in short: Claude Code runs on the- * alternate screen with mouse tracking, so the terminal holds no scrollback- * to read a position from and the wheel belongs to the CLI. That pane's- * position is measured from how its screen moves instead, and its thumb is- * drawn from that measurement like any other.+ * Because half the panes have nothing for a browser scrollbar to move. A CLI+ * that prints line by line (Codex, a shell) leaves its transcript in the+ * terminal's scrollback, and `.xterm-viewport` scrolls it. A CLI that takes the+ * whole screen keeps its transcript to itself — measured against Claude Code+ * 2.1.220, it switches to the alternate buffer and asks for full SGR mouse+ * tracking within milliseconds of starting, after which the terminal holds no+ * scrollback at all and the wheel is forwarded to the application. There is+ * nothing there to style.*- * The bar is an overlay, not a layout box: xterm reserves a gutter on the right- * for the scrollbar it thinks it has, and the bar sits in that gutter, so- * nothing is drawn underneath it.+ * So the bar is drawn here and scrolls whichever of the two it is on:*- * That gutter is real even though ./index.css gives the native bar zero width.- * Measured against xterm 5.5.0, `Viewport` computes- * `scrollBarWidth = viewportElement.offsetWidth - scrollArea.offsetWidth || 15`- * — and a scrollbar hidden by CSS makes that difference 0, so the `|| 15`- * fallback takes over and `FitAddon.proposeDimensions` drops 15 px of columns.- * Hence `hostGap`: the bar is placed flush against the terminal host's right- * edge, INSIDE the reserved strip. Floating it in the pane's own padding instead- * (the original `right-1`) left dead space on both sides of it — part of the- * empty right-hand strip reported on 2026-07-27.+ * * the terminal's viewport, by line, when the terminal owns the history;+ * * the application itself, by relayed wheel notches, when it does not.*- * And reaching for it is what MAKES it appear in an agent pane: the position of a- * CLI that holds its own history has to be measured, and until this pane had been- * scrolled there was nothing measured to draw. See `probeAppHistory` in- * ./paneAppScroll — the gesture asks the question now.+ * ## It shows up on hover, and it does not ask permission first+ *+ * Reaching a pane makes its bar appear — no measurement, no probe, no proving+ * that there is a history worth drawing. That rule is the whole point of this+ * rewrite: the version before it demanded evidence from a CLI that cannot give+ * any, and every failure to get that evidence looked exactly like "nothing to+ * scroll here", so the bar never appeared in the panes it was written for. See+ * ./paneScrollModel for what an application-held pane claims instead.+ *+ * A pane with genuinely nothing to scroll — a shell that has printed four lines+ * — still gets no bar, because its terminal says so exactly.+ *+ * ## And it stays off the frame budget+ *+ * A grid can hold a dozen live terminals. So: nothing is read from a terminal+ * while the bar is invisible, everything read while it is visible is coalesced+ * into one animation frame, the track is measured by a ResizeObserver rather+ * than during render, and hover is two events (enter, leave) rather than one+ * per pointer move.*/-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type { Terminal } from "@xterm/xterm";import { cn } from "@/lib/utils";import type { TerminalAppearance } from "./terminalThemes";import {- IDLE_STATE,- lineForThumbTop,- readScrollState,- relayWheelNotch,- thumbGeometry,- type PaneScrollState,-} from "./paneScroll";-import {- appTakesWheel,- AT_LIVE_END,- hasMeasuredHistory,- measuredNoHistory,+ appScroll,+ backForThumbTop,+ bufferScroll,+ LINES_PER_NOTCH,notchesForLines,- probeAppHistory,- PROBE_STALE_MS,- PROBE_WAIT_MS,- trackAppScroll,- type AppScrollPosition,-} from "./paneAppScroll";+ scrollable,+ thumbGeometry,+ type PaneScroll,+} from "./paneScrollModel";-/** How close to the pane's right edge the pointer reveals the bar. */-const HOT_ZONE_PX = 28;+/** How long the bar lingers after the pointer leaves, so it cannot flicker. */+const LINGER_MS = 200;++/** How long a wheel turn keeps the bar up when the pointer is elsewhere. */+const FLASH_MS = 700;/**- * Where the bar sits until the real distance has been measured.+ * Where the bar sits before the pane has been measured.*- * It belongs flush against the xterm host's right edge — the near side of the- * gutter xterm reserves for the scrollbar it thinks it has (see the file header).- * That distance is the terminal region's own horizontal padding, and it is- * MEASURED (`hostGap` below) rather than restated here: this constant used to- * name the padding as a number, the padding was then changed in ./AgenticTerminal- * without it, and the bar spent 2 px sitting on top of the agent's output. A- * layout constant duplicated across two files drifts the moment either one is- * touched. Used only for the very first paint, before the measurement lands.+ * xterm reserves a strip on the right for the scrollbar it believes it has, and+ * the bar belongs inside that strip rather than floating in the pane's padding.+ * The real distance is measured below; this is only the first paint.*/-const BAR_INSET_FALLBACK_PX = 6;+const INSET_FALLBACK_PX = 6;-/** Grace period before a bar the pointer left disappears again. */-const HIDE_DELAY_MS = 260;+/** True when the running application receives wheel events itself. */+function appTakesWheel(term: Terminal | null): boolean {+ const tracking = term?.modes?.mouseTrackingMode;+ return Boolean(tracking) && tracking !== "none";+}-/** How long the bar stays up after scrolling back through history. */-const FLASH_MS = 900;+/**+ * What this pane can scroll right now.+ *+ * `back` is what the component has counted for an application-held pane; it is+ * ignored for a terminal that can answer the question itself.+ *+ * Defensive by design — this runs against whatever xterm the app was bundled+ * with, and a missing field must mean "no bar" rather than an exception thrown+ * inside a render.+ */+export function readPaneScroll(+ term: Terminal | null,+ back: number,+): PaneScroll | null {+ const buffer = term?.buffer?.active;+ const rows = term?.rows ?? 0;+ if (!term || !buffer || rows < 1) return null;++ // The application holds the history in EITHER buffer once it has taken the+ // mouse, and in the alternate buffer there is no scrollback either way.+ if (appTakesWheel(term) || buffer.type === "alternate") {+ return appScroll(back, rows);+ }++ const scroll = bufferScroll(+ buffer.length ?? rows,+ buffer.baseY ?? 0,+ buffer.viewportY ?? 0,+ rows,+ );+ return scrollable(scroll) ? scroll : null;+}-function sameState(a: PaneScrollState, b: PaneScrollState): boolean {- return (- a.mode === b.mode &&- a.total === b.total &&- a.rows === b.rows &&- a.top === b.top+/**+ * Hand one wheel notch to whatever is running in `host`.+ *+ * Dispatched as a real wheel event on xterm's screen rather than written to the+ * socket by hand: xterm already knows which mouse protocol the application+ * negotiated and encodes the report accordingly, and for a full-screen+ * application that did NOT take the mouse it sends the cursor keys a real wheel+ * turn would send. Guessing those bytes here would put junk in the CLI's prompt.+ *+ * Line mode with a delta of exactly one, which is what a notch is.+ */+export function relayWheelNotch(+ host: HTMLElement | null,+ direction: 1 | -1,+): boolean {+ if (!host || typeof WheelEvent === "undefined") return false;+ const screen = host.querySelector<HTMLElement>(".xterm-screen");+ if (!screen) return false;+ const box = screen.getBoundingClientRect();+ return screen.dispatchEvent(+ new WheelEvent("wheel", {+ bubbles: true,+ cancelable: true,+ clientX: box.left + box.width / 2,+ clientY: box.top + box.height / 2,+ deltaMode: 1,+ deltaY: direction,+ }),);}@@ -96,20 +142,16 @@ interface PaneScrollbarProps {/** Pane call-sign — used for labels and test ids. */name: string;/**- * The pane's terminal area. Hover is measured against THIS element rather- * than the xterm host, because the bar itself sits inside it: with the host- * as the reference, moving onto the bar would count as leaving the pane and- * the bar would vanish under the pointer.+ * The pane's terminal area. Hover is measured against THIS element, because+ * the bar sits inside it: with the xterm host as the reference, moving onto+ * the bar would count as leaving the pane.*/regionRef: React.RefObject<HTMLElement | null>;/** The xterm host, where a relayed wheel event is dispatched. */hostRef: React.RefObject<HTMLElement | null>;/** The live terminal, or null before it is built. */getTerminal: () => Terminal | null;- /**- * Bumped whenever the terminal behind `getTerminal` is replaced, so the- * subscriptions below are torn down and rebuilt against the new instance.- */+ /** Bumped whenever the terminal behind `getTerminal` is replaced. */epoch: number;appearance: TerminalAppearance;}@@ -123,217 +165,112 @@ export function PaneScrollbar({appearance,}: PaneScrollbarProps) {const trackRef = useRef<HTMLDivElement | null>(null);- const [state, setState] = useState<PaneScrollState>(IDLE_STATE);+ const [scroll, setScroll] = useState<PaneScroll | null>(null);const [trackPx, setTrackPx] = useState(0);- // The gap between the pane's right edge and the xterm host's — measured, not- // restated from ./AgenticTerminal. See `BAR_INSET_FALLBACK_PX`.- const [hostGap, setHostGap] = useState(BAR_INSET_FALLBACK_PX);- const [nearEdge, setNearEdge] = useState(false);+ const [inset, setInset] = useState(INSET_FALLBACK_PX);+ const [hovering, setHovering] = useState(false);const [flashing, setFlashing] = useState(false);const [dragging, setDragging] = useState(false);- // Where the thumb is while it is held. The application answers a relayed- // notch a network round trip later, so a thumb drawn only from the- // measurement would lag behind the pointer holding it.+ // Where the thumb is while it is held. An application answers a relayed+ // notch a moment later, so a thumb drawn only from what has been counted+ // would lag behind the pointer holding it.const [dragTopPx, setDragTopPx] = useState<number | null>(null);- // What ./paneAppScroll has measured of a CLI that holds its own history.- const [position, setPosition] = useState<AppScrollPosition>(AT_LIVE_END);- const shown = nearEdge || flashing || dragging;- const stateRef = useRef(state);- stateRef.current = state;- const positionRef = useRef(position);- positionRef.current = position;+ // How far an application-held pane stands back from its newest output, in+ // lines. Counted from the wheel traffic the pane sees — the user's own turns+ // and the bar's relays alike, since both scroll the same application.+ const backRef = useRef(0);+ const [back, setBack] = useState(0);++ const shown = hovering || flashing || dragging;+ // The track is in the document only while there is something to scroll, so+ // anything that measures it has to run again when it appears.+ const hasBar = scrollable(scroll);+ const scrollRef = useRef(scroll);+ scrollRef.current = scroll;++ // A fresh terminal is a fresh transcript.+ useEffect(() => {+ backRef.current = 0;+ setBack(0);+ setScroll(null);+ }, [epoch]);// ------------------------------------------------------------------ hover+ // Enter and leave, not every pointer move: a grid of a dozen panes must not+ // pay per pixel to know which one the pointer is on.useEffect(() => {const region = regionRef.current;if (!region) return;- let hideTimer: number | undefined;+ let timer: number | undefined;- const clearHide = () => {- if (hideTimer !== undefined) window.clearTimeout(hideTimer);- hideTimer = undefined;+ const enter = () => {+ if (timer !== undefined) window.clearTimeout(timer);+ timer = undefined;+ setHovering(true);};const leave = () => {- clearHide();- hideTimer = window.setTimeout(() => setNearEdge(false), HIDE_DELAY_MS);- };- const onMove = (event: MouseEvent) => {- const rect = region.getBoundingClientRect();- const inside =- event.clientY >= rect.top &&- event.clientY <= rect.bottom &&- rect.right - event.clientX <= HOT_ZONE_PX &&- event.clientX <= rect.right;- if (inside) {- clearHide();- setNearEdge(true);- } else {- leave();- }+ if (timer !== undefined) window.clearTimeout(timer);+ timer = window.setTimeout(() => setHovering(false), LINGER_MS);};- region.addEventListener("mousemove", onMove);+ region.addEventListener("mouseenter", enter);region.addEventListener("mouseleave", leave);return () => {- clearHide();- region.removeEventListener("mousemove", onMove);+ if (timer !== undefined) window.clearTimeout(timer);+ region.removeEventListener("mouseenter", enter);region.removeEventListener("mouseleave", leave);};}, [regionRef]);- // -------------------------------------------------- measure an app's scroll+ // ------------------------------------------------------- follow the wheel// Runs whether the bar is visible or not, and costs nothing until a wheel- // actually turns: a bar that only started measuring when it appeared would- // come up knowing nothing about a pane the user scrolled a minute ago.+ // actually turns: a pane scrolled a minute ago must come up knowing where it+ // stands. Capture, so it sees the turn before xterm forwards it, and passive,+ // so it can never interfere with what xterm does next.useEffect(() => {const host = hostRef.current;if (!host) return;- return trackAppScroll({ host, getTerminal, onChange: setPosition });- }, [hostRef, getTerminal, epoch]);-- // A fresh terminal is a fresh transcript — carrying a measured position over- // a restart would put the thumb somewhere in a history that no longer exists.- useEffect(() => {- setPosition(AT_LIVE_END);- }, [epoch]);-- // ------------------------------------------------ measure on first reach- // Reaching for the bar is itself the request for one, so a pane that has- // nothing measured yet gets asked — see `probeAppHistory` in ./paneAppScroll- // for why waiting for a wheel turn instead left the bar unreachable in exactly- // the panes it exists for.- //- // Asked only while nothing is known, and only after the pane has been quiet for- // `PROBE_WAIT_MS`: a probe moves the application by a notch and back, which is- // invisible once but would be a twitch on every pass of the pointer — and a- // probe folded into a burst of the user's own scrolling measures neither of- // them. `probedAt` rather than the position alone, because the answer lands a- // settle period later and a pointer crossing the hot zone twice in that time- // must not ask twice.- //- // Only one answer stands for good: "there IS history here". Everything else- // expires. "This pane has no history at all" is true of the moment it was- // measured, and a pane that was empty when it opened fills up; a probe that- // produced no answer AT ALL — sent while the application was repainting, or- // into a terminal that was still being built — leaves the pane in the very- // same state, without a bar and with nothing measured. Treating only the- // first of those as re-askable is what left a pane one unlucky probe away- // from having no scrollbar for the rest of its life. See `measuredNoHistory`- // and `PROBE_STALE_MS` in ./paneAppScroll.- const probedAt = useRef<{ epoch: number; at: number } | null>(null);- useEffect(() => {- if (!nearEdge) return;- const host = hostRef.current;- const term = getTerminal();- if (!host || !term || !appTakesWheel(term)) return;+ let timer: number | undefined;- const stale = () => {- const last = probedAt.current;- if (!last || last.epoch !== epoch) return true;- return Date.now() - last.at >= PROBE_STALE_MS;- };- // Nothing to ask while a history is known to exist — except when the only- // thing known is that there was none, and that reading has gone stale.- const settled = () =>- hasMeasuredHistory(positionRef.current) &&- !measuredNoHistory(positionRef.current);- if (settled() || !stale()) return;-- let stopProbe: (() => void) | undefined;- let wait: number | undefined;-- const ask = () => {- wait = undefined;- host.removeEventListener("wheel", defer, { capture: true });- // The wait may have been all it took: a wheel turn measures the pane- // better than any probe, so if one landed there is nothing left to ask.- if (settled()) return;- probedAt.current = { epoch, at: Date.now() };- stopProbe = probeAppHistory((direction) =>- relayWheelNotch(host, direction),- );- };- // A wheel turn while the probe is still pending pushes it back, so the- // tracker never has two sources of movement inside one burst.- function defer(event: WheelEvent) {+ const onWheel = (event: WheelEvent) => {if (event.deltaY === 0) return;- if (wait !== undefined) window.clearTimeout(wait);- wait = window.setTimeout(ask, PROBE_WAIT_MS);- }-- host.addEventListener("wheel", defer, { capture: true, passive: true });- wait = window.setTimeout(ask, PROBE_WAIT_MS);- return () => {- if (wait !== undefined) window.clearTimeout(wait);- host.removeEventListener("wheel", defer, { capture: true });- stopProbe?.();- };- }, [nearEdge, getTerminal, epoch, hostRef]);-- // ------------------------------------------------- flash while scrolled back- // Deliberately NOT "flash on any scroll": a pane pinned to the bottom scrolls- // on every line an agent prints, and a bar that lit up for each of them would- // be the permanent stripe this replaces. Only a viewport sitting ABOVE the- // live end means somebody is reading history.- useEffect(() => {- const term = getTerminal();- if (!term?.onScroll) return;- let timer: number | undefined;- const subscription = term.onScroll(() => {- const buffer = term.buffer?.active;- if (!buffer || buffer.viewportY >= buffer.baseY) return;+ const term = getTerminal();+ if (appTakesWheel(term) || term?.buffer?.active?.type === "alternate") {+ const next = Math.max(+ 0,+ backRef.current ++ (event.deltaY > 0 ? -LINES_PER_NOTCH : LINES_PER_NOTCH),+ );+ backRef.current = next;+ setBack(next);+ }setFlashing(true);if (timer !== undefined) window.clearTimeout(timer);timer = window.setTimeout(() => setFlashing(false), FLASH_MS);- });+ };++ host.addEventListener("wheel", onWheel, { capture: true, passive: true });return () => {if (timer !== undefined) window.clearTimeout(timer);- subscription.dispose();+ host.removeEventListener("wheel", onWheel, { capture: true });};- }, [getTerminal, epoch]);-- // The same flash for an app-mode pane, which produces no xterm scroll event- // at all: the only sign that somebody is reading history is the measurement- // moving away from the live end. The timer is held in a ref rather than- // cleared per effect run, because a measurement that lands back AT the live- // end must let the flash run out — not cancel it and leave the bar up.- const flashTimer = useRef<number | undefined>(undefined);- useEffect(() => {- if (position.offset === 0) return;- setFlashing(true);- if (flashTimer.current !== undefined)- window.clearTimeout(flashTimer.current);- flashTimer.current = window.setTimeout(() => setFlashing(false), FLASH_MS);- }, [position]);- useEffect(- () => () => {- if (flashTimer.current !== undefined) {- window.clearTimeout(flashTimer.current);- }- },- [],- );+ }, [hostRef, getTerminal, epoch]);- // ---------------------------------------------------------------- metrics- // Only while the bar is on screen. A hidden bar needs no numbers, and reading- // them on every frame of a busy pane is exactly the kind of work the grid- // spends its frame budget avoiding.+ // ---------------------------------------------------------------- reading+ // Only while the bar is on screen, and never more than once a frame: reading+ // a terminal's buffer on every render of every pane is exactly the kind of+ // work a grid of live agents cannot afford.useEffect(() => {if (!shown) return;const term = getTerminal();if (!term) return;-let frame: number | undefined;+const sync = () => {frame = undefined;- const next = readScrollState(term, positionRef.current);- if (!sameState(next, stateRef.current)) setState(next);- const track = trackRef.current;- if (track) {- const height = track.clientHeight;- setTrackPx((current) => (current === height ? current : height));- }+ const next = readPaneScroll(term, backRef.current);+ setScroll((current) => (same(current, next) ? current : next));};const schedule = () => {if (frame === undefined) frame = requestAnimationFrame(sync);@@ -343,6 +280,7 @@ export function PaneScrollbar({const subscriptions = [term.onRender?.(schedule),term.onResize?.(schedule),+ term.onScroll?.(schedule),term.buffer?.onBufferChange?.(schedule),];return () => {@@ -351,45 +289,25 @@ export function PaneScrollbar({};}, [shown, getTerminal, epoch]);- // A new measurement moves the thumb even on a pane that renders nothing —- // an app scrolled back through its own history repaints once and then sits- // still, and the effect above would never hear about it. Only once something- // HAS been measured, so an untouched pane keeps the bar out of the document- // entirely rather than mounting it invisible.+ // A counted step moves the thumb even on a pane that repaints nothing.useEffect(() => {+ if (!shown) return;const term = getTerminal();- if (!term || position === AT_LIVE_END) return;- const next = readScrollState(term, position);- setState((current) => (sameState(current, next) ? current : next));- }, [position, getTerminal, epoch]);-- /*- * The track's height decides the thumb's, and the bar's distance from the- * pane edge decides where it sits. Both are geometry, so both are MEASURED —- * and both are measured when the boxes actually change rather than after- * every render.- *- * That distinction is the whole point of this effect. It used to run on every- * commit, and reading a box in a commit forces the browser to recompute the- * layout there and then — for each pane, on a thread that has just resized- * all of them. With a dozen panes and a seam being dragged, those forced- * recomputations were the single most expensive thing in the frame, and the- * measured height changing then fed a second render per pane on top. A- * ResizeObserver answers the same question from outside the render, only when- * there is a new answer.- *- * `state.mode` is in the dependencies because the track is in the document- * only while there is something to scroll — the observer has to be attached- * to the element that exists now.- */+ if (!term) return;+ const next = readPaneScroll(term, back);+ setScroll((current) => (same(current, next) ? current : next));+ }, [back, shown, getTerminal, epoch]);++ // ------------------------------------------------------------- geometry+ // Measured from outside the render, and only when a box actually changes.useEffect(() => {const track = trackRef.current;if (!track) return;const measure = () => {- const height = track.clientHeight;- setTrackPx((current) => (current === height ? current : height));-+ setTrackPx((current) =>+ current === track.clientHeight ? current : track.clientHeight,+ );const region = regionRef.current;const host = hostRef.current;if (!region || !host) return;@@ -400,156 +318,169 @@ export function PaneScrollbar({host.getBoundingClientRect().right,),);- setHostGap((current) => (current === gap ? current : gap));+ setInset((current) => (current === gap ? current : gap));};measure();- // No observer in this environment (older engines, some test setups): the- // one measurement above still gives the bar a thumb, which is the- // behaviour that matters.if (typeof ResizeObserver === "undefined") return;const observer = new ResizeObserver(measure);observer.observe(track);if (regionRef.current) observer.observe(regionRef.current);if (hostRef.current) observer.observe(hostRef.current);return () => observer.disconnect();- }, [state.mode, regionRef, hostRef]);+ }, [hasBar, regionRef, hostRef]);// ------------------------------------------------------------------ input- const relay = useCallback(- (notches: number) => {- const direction = notches > 0 ? 1 : -1;- for (let i = 0; i < Math.abs(notches); i += 1) {- relayWheelNotch(hostRef.current, direction);+ /** Does this pane's application hold the screen, rather than the terminal? */+ const appHeld = useCallback(() => {+ const term = getTerminal();+ return Boolean(+ term &&+ (appTakesWheel(term) || term.buffer?.active?.type === "alternate"),+ );+ }, [getTerminal]);++ /** Scroll the pane by `lines` towards older output (negative: newer). */+ const scrollBy = useCallback(+ (lines: number) => {+ const term = getTerminal();+ if (!term || lines === 0) return;+ if (appHeld()) {+ const notches = notchesForLines(lines);+ for (let i = 0; i < Math.abs(notches); i += 1) {+ relayWheelNotch(hostRef.current, notches > 0 ? -1 : 1);+ }+ return;}+ term.scrollLines?.(-lines);},- [hostRef],+ [getTerminal, hostRef, appHeld],+ );++ /**+ * Take the pane to `wanted` lines back from its newest output.+ *+ * A terminal that owns its scrollback is told the line outright, so a fast+ * drag cannot overshoot by however far the reading lags behind the pointer.+ * An application can only be asked in notches, and is: the difference is+ * counted against `backRef`, which our own relay updates as it dispatches.+ */+ const scrollTo = useCallback(+ (wanted: number) => {+ const term = getTerminal();+ if (!term) return;+ if (appHeld()) {+ scrollBy(wanted - backRef.current);+ return;+ }+ const base = term.buffer?.active?.baseY ?? 0;+ term.scrollToLine?.(Math.max(0, base - Math.max(0, wanted)));+ },+ [getTerminal, appHeld, scrollBy],);const onThumbPointerDown = useCallback((event: React.PointerEvent<HTMLDivElement>) => {- const term = getTerminal();const track = trackRef.current;- if (!term || !track) return;+ const term = getTerminal();+ if (!track || !term) return;event.preventDefault();event.stopPropagation();- const current = stateRef.current;const height = track.clientHeight;- const startY = event.clientY;- const geometry = thumbGeometry(current, height);+ const start = scrollRef.current;+ const geometry = thumbGeometry(start, height);const startTop = geometry?.topPx ?? 0;+ const startY = event.clientY;const travel = Math.max(0, height - (geometry?.heightPx ?? 0));- // Where the drag began in the history, and how many notches have been- // relayed towards its target so far. Counted against the START rather- // than against the live measurement, so a reading that lands mid-drag- // cannot make the same notch be sent twice.- const startLine = current.top;- const step = positionRef.current.linesPerNotch;- let sentNotches = 0;const target = event.currentTarget;- target.setPointerCapture(event.pointerId);+ // Capture keeps the drag alive when the pointer runs off the thin bar,+ // but it is not worth losing the drag over: engines and test+ // environments that do not implement it still get a working thumb.+ try {+ target.setPointerCapture(event.pointerId);+ } catch {+ /* no capture — the listeners below carry the drag anyway */+ }setDragging(true);setDragTopPx(startTop);+ // The mapping is frozen at the grab. An application-held pane's assumed+ // span grows as it is scrolled back (see ./paneScrollModel), and a thumb+ // measured against a span that moves under the pointer slides away from+ // the hand holding it.const onMove = (move: PointerEvent) => {+ if (!Number.isFinite(move.clientY)) return;const topPx = Math.min(Math.max(startTop + (move.clientY - startY), 0),travel,);setDragTopPx(topPx);- const line = lineForThumbTop(topPx, height, current);- if (current.mode === "app") {- const wanted = notchesForLines(line - startLine, step);- if (wanted !== sentNotches) {- relay(wanted - sentNotches);- sentNotches = wanted;- }- return;- }- term.scrollToLine?.(line);+ scrollTo(backForThumbTop(topPx, height, start));};- const onUp = () => {+ const finish = () => {target.releasePointerCapture?.(event.pointerId);target.removeEventListener("pointermove", onMove);- target.removeEventListener("pointerup", onUp);- target.removeEventListener("pointercancel", onUp);+ target.removeEventListener("pointerup", finish);+ target.removeEventListener("pointercancel", finish);setDragging(false);setDragTopPx(null);};target.addEventListener("pointermove", onMove);- target.addEventListener("pointerup", onUp);- target.addEventListener("pointercancel", onUp);+ target.addEventListener("pointerup", finish);+ target.addEventListener("pointercancel", finish);},- [getTerminal, relay],+ [getTerminal, scrollBy],);- // A click on the empty part of the track pages towards it, the way every- // other scrollbar does.+ // A click on the empty part of the track pages towards it, as every other+ // scrollbar does.const onTrackPointerDown = useCallback((event: React.PointerEvent<HTMLDivElement>) => {- const term = getTerminal();const track = trackRef.current;- if (!term || !track) return;+ const current = scrollRef.current;+ if (!track || !current) return;event.preventDefault();event.stopPropagation();- const current = stateRef.current;- const rect = track.getBoundingClientRect();- const geometry = thumbGeometry(current, rect.height);+ const box = track.getBoundingClientRect();+ const geometry = thumbGeometry(current, box.height);if (!geometry) return;const page = Math.max(1, current.rows - 1);- const down = event.clientY - rect.top > geometry.topPx;- if (current.mode === "app") {- relay(- notchesForLines(- down ? page : -page,- positionRef.current.linesPerNotch,- ),- );- } else {- term.scrollLines?.(down ? page : -page);- }+ const towardsNewer = event.clientY - box.top > geometry.topPx;+ scrollBy(towardsNewer ? -page : page);},- [getTerminal, relay],+ [scrollBy],);const onWheel = useCallback((event: React.WheelEvent<HTMLDivElement>) => {- const term = getTerminal();- if (!term) return;- const current = stateRef.current;- const notches = event.deltaY > 0 ? 1 : -1;- if (current.mode === "app") relay(notches * 3);- else term.scrollLines?.(notches * 3);+ scrollBy(event.deltaY > 0 ? -LINES_PER_NOTCH : LINES_PER_NOTCH);},- [getTerminal, relay],+ [scrollBy],);// ----------------------------------------------------------------- render- const geometry = thumbGeometry(state, trackPx);- if (state.mode === "none") return null;+ const geometry = useMemo(+ () => thumbGeometry(scroll, trackPx),+ [scroll, trackPx],+ );+ if (!hasBar) return null;const light = appearance === "light";const strength = dragging ? 0.95 : 0.62;- const maxTop = Math.max(0, state.total - state.rows);return (<divref={trackRef}role="scrollbar"aria-orientation="vertical"- aria-label={- state.mode === "app"- ? `Scroll ${name} — moves through the agent's own history`- : `Scroll ${name}`- }+ aria-label={`Scroll ${name}`}aria-valuemin={0}- aria-valuemax={maxTop}- aria-valuenow={Math.min(state.top, maxTop)}+ aria-valuemax={scroll?.span ?? 0}+ aria-valuenow={(scroll?.span ?? 0) - (scroll?.back ?? 0)}data-testid={`pane-scrollbar-${name}`}- data-mode={state.mode}data-shown={shown ? "true" : "false"}onPointerDown={onTrackPointerDown}onWheel={onWheel}@@ -559,11 +490,11 @@ export function PaneScrollbar({shown ? "opacity-100" : "pointer-events-none opacity-0",)}style={{- right: hostGap,+ right: inset,background: shown? light? "rgba(0,0,0,0.06)"- : "rgba(255,255,255,0.06)"+ : "rgba(255,255,255,0.07)": "transparent",}}>@@ -572,16 +503,23 @@ export function PaneScrollbar({data-testid={`pane-scrollbar-thumb-${name}`}onPointerDown={onThumbPointerDown}className={cn(- "absolute left-0 w-full cursor-grab rounded-full",- dragging ? "cursor-grabbing" : "transition-[top] duration-75",+ "absolute left-0 w-full rounded-full",+ dragging ? "cursor-grabbing" : "cursor-grab transition-[top]",)}style={{top: dragTopPx ?? geometry.topPx,height: geometry.heightPx,background: `rgb(var(--jarvis-yellow) / ${strength})`,+ transitionDuration: dragging ? undefined : "80ms",}}/>)}</div>);}++function same(a: PaneScroll | null, b: PaneScroll | null): boolean {+ if (a === b) return true;+ if (!a || !b) return false;+ return a.span === b.span && a.back === b.back && a.rows === b.rows;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.test.tsdeleted file mode 100644index 1517115f5d..0000000000--- a/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.test.ts+++ /dev/null@@ -1,619 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import type { Terminal } from "@xterm/xterm";-import {- AT_LIVE_END,- BURST_MS,- MAX_LINES_PER_NOTCH,- PROBE_RETURN_MS,- SETTLE_MS,- appScrollExtent,- appTakesWheel,- applyShift,- detectShift,- hasMeasuredHistory,- notchesForLines,- probeAppHistory,- trackAppScroll,- visibleRows,- type AppScrollPosition,-} from "./paneAppScroll";--/** A screen of an agent transcript — long enough to identify itself again. */-function transcript(from: number, count: number): string[] {- return Array.from({ length: count }, (_, i) => `line ${from + i} of output`);-}--function fakeTerminal(rows: string[], mouseTrackingMode = "any"): Terminal {- return {- rows: rows.length,- modes: { mouseTrackingMode },- buffer: {- active: {- type: "alternate",- length: rows.length,- viewportY: 0,- baseY: 0,- getLine: (index: number) =>- index >= 0 && index < rows.length- ? { translateToString: () => rows[index] }- : undefined,- },- },- } as unknown as Terminal;-}--describe("visibleRows", () => {- it("reads the screen the user is looking at", () => {- expect(visibleRows(fakeTerminal(transcript(1, 3)))).toEqual([- "line 1 of output",- "line 2 of output",- "line 3 of output",- ]);- });-- it("degrades to an empty screen rather than throwing", () => {- expect(visibleRows(null)).toEqual([]);- expect(visibleRows({} as Terminal)).toEqual([]);- // An xterm build without `getLine` must not take a wheel handler down.- expect(- visibleRows({- rows: 4,- buffer: { active: { viewportY: 0 } },- } as unknown as Terminal),- ).toEqual([]);- });-});--describe("detectShift", () => {- it("sees a screen that did not move, spinner and all", () => {- const before = [...transcript(1, 8), "Fermenting… 3m 23s"];- const after = [...transcript(1, 8), "Fermenting… 3m 41s"];-- expect(detectShift(before, after)).toBe(0);- });-- /*- * The measurement the whole feature rests on: scrolling back two lines pushes- * the content DOWN the screen, and that distance IS how much further from the- * live end the user now is.- */- it("measures how far the content travelled when scrolled back", () => {- const before = transcript(10, 10);- const after = [...transcript(8, 2), ...transcript(10, 8)];-- expect(detectShift(before, after)).toBe(2);- });-- it("measures a move back towards newer output as a negative shift", () => {- const before = transcript(10, 10);- const after = [...transcript(13, 7), ...transcript(20, 3)];-- expect(detectShift(before, after)).toBe(-3);- });-- /*- * A coding agent pins its prompt box and status line to the bottom of the- * screen, so those rows match at a shift of zero no matter what the transcript- * above them did. They must not be able to outvote the part that moved.- */- it("is not fooled by rows the application pins to the bottom", () => {- const box = ["> type here", "bypass permissions on"];- const before = [...transcript(10, 10), ...box];- const after = [...transcript(9, 1), ...transcript(10, 9), ...box];-- expect(detectShift(before, after)).toBe(1);- });-- /*- * The failure the whole bar hung on, in miniature — measured 2026-07-27 by- * replaying a recorded Claude Code 2.1.220 session into a real terminal.- *- * A column of short, look-alike rows (numbers, a file tree, a wrapped list)- * carries nothing recognisable enough to survive a scroll, so the only rows- * that still match are the ones the application pins to the bottom — and- * those match at a shift of zero by construction. Read as "the screen did not- * move", that is an end of the history at distance zero: a pane with nothing- * to scroll, and therefore no scrollbar at all, while its transcript was- * scrolling three lines at a time under the pointer.- *- * "We cannot say how far it went" is the honest answer, and it costs nothing:- * the caller falls back to what it asked for and claims no end of anything.- */- it("refuses to call a screen still that plainly changed", () => {- const furniture = [- "─────────────────",- "> type here",- "─────────────────",- "main · Opus 5 (1M context)",- "bypass permissions on",- ];- const numbers = (from: number) =>- Array.from({ length: 10 }, (_, i) => ` ${from + i}`);-- expect(- detectShift(- [...numbers(40), ...furniture],- [...numbers(37), ...furniture],- ),- ).toBeNull();- });-- it("refuses to guess from a screen with nothing on it", () => {- expect(detectShift(["", "", "a", ""], ["", "", "", "a"])).toBeNull();- expect(detectShift(transcript(1, 2), transcript(1, 2))).toBeNull();- });-- it("refuses to guess when the screen was replaced outright", () => {- expect(detectShift(transcript(1, 10), transcript(500, 10))).toBeNull();- });-});--describe("applyShift", () => {- it("moves away from the live end by exactly what was measured", () => {- const next = applyShift(AT_LIVE_END, 3, -1);-- expect(next.offset).toBe(3);- // One notch moved three lines, so that is what a notch is worth here.- expect(next.linesPerNotch).toBe(3);- // Three lines of history are now proven to exist — and possibly more.- expect(next).toMatchObject({ span: 3, spanKnown: false });- });-- it("pins the top down when a scroll back moves nothing", () => {- const scrolled: AppScrollPosition = {- offset: 42,- span: 42,- spanKnown: false,- linesPerNotch: 3,- };-- expect(applyShift(scrolled, 0, -1)).toMatchObject({- offset: 42,- span: 42,- spanKnown: true,- });- });-- /*- * The reading the reported bug turned on: a pane at the newest output must be- * drawn at the newest output. A scroll down that moves nothing says so exactly,- * whatever the accumulated arithmetic had drifted to.- */- it("snaps back to zero when a scroll down moves nothing", () => {- const drifted: AppScrollPosition = {- offset: 7,- span: 200,- spanKnown: true,- linesPerNotch: 3,- };-- expect(applyShift(drifted, 0, 1)).toMatchObject({- offset: 0,- span: 200,- spanKnown: true,- });- });-- it("learns nothing about a notch from a move that hit the end", () => {- const near: AppScrollPosition = {- offset: 0,- span: 0,- spanKnown: false,- linesPerNotch: 3,- };-- // Four notches asked for, one line delivered: the history ran out mid-burst,- // so this says nothing about how far one notch goes.- expect(applyShift(near, 1, -4).linesPerNotch).toBe(3);- });-- it("keeps a notch's measured size within reason", () => {- expect(applyShift(AT_LIVE_END, 900, -1).linesPerNotch).toBe(- MAX_LINES_PER_NOTCH,- );- });-- /*- * "Nothing moved" and "we could not tell" look the same in a sum and mean- * opposite things: one is the end of the history, the other is a measurement- * that failed. Only the first may ever pin an end down.- */- it("falls back to what was sent without claiming an end", () => {- const known: AppScrollPosition = {- offset: 0,- span: 90,- spanKnown: true,- linesPerNotch: 3,- };-- expect(applyShift(known, null, -4)).toMatchObject({- offset: 12,- spanKnown: true,- linesPerNotch: 3,- });- expect(applyShift(known, null, 4)).toMatchObject({ offset: 0 });- });-- it("gives up a top it turns out to be able to scroll past", () => {- const stale: AppScrollPosition = {- offset: 90,- span: 90,- spanKnown: true,- linesPerNotch: 3,- };-- // The transcript grew while the user sat in it, so the old top was not one.- expect(applyShift(stale, 6, -2)).toMatchObject({- offset: 96,- span: 96,- spanKnown: false,- });- });-- it("never lets a position run below the live end", () => {- expect(applyShift(AT_LIVE_END, -40, 4).offset).toBe(0);- });-});--describe("hasMeasuredHistory", () => {- it("knows nothing about a pane nobody has scrolled", () => {- expect(hasMeasuredHistory(AT_LIVE_END)).toBe(false);- });-- /*- * The three ways something can be known, each on its own — because each is a- * pane the user has already scrolled, and one that must keep the bar it was- * scrolled with even after coming home to the newest output.- */- it("knows something once the pane has been away from the live end", () => {- expect(hasMeasuredHistory({ ...AT_LIVE_END, offset: 4 })).toBe(true);- });-- it("knows something once a depth has been reached", () => {- expect(hasMeasuredHistory({ ...AT_LIVE_END, span: 40 })).toBe(true);- });-- /*- * Including the pane measured as having NO history at all: something IS known- * about it, and what `readScrollState` does with that is take the bar away —- * for a reason of its own, not for want of a measurement.- */- it("knows something once a scroll has hit the top", () => {- expect(hasMeasuredHistory({ ...AT_LIVE_END, spanKnown: true })).toBe(true);- });-});--describe("appScrollExtent", () => {- /*- * The arithmetic for a position whose top is still unfound: one screenful is- * assumed above the deepest point reached, and the viewport sits at the bottom- * of it. Note this is the arithmetic ONLY — whether a bar is drawn at all is- * `hasMeasuredHistory`'s call, and for an untouched pane the answer is no (see- * `readScrollState` in ./paneScroll). Kept as a unit so the "top unknown" case- * that DOES reach the screen — scrolled back, top not yet hit — stays pinned.- */- it("assumes one screen above a position whose top is unfound", () => {- expect(appScrollExtent(AT_LIVE_END, 30)).toEqual({ total: 60, top: 30 });- });-- it("draws the real proportions once the top has been found", () => {- const known: AppScrollPosition = {- offset: 0,- span: 400,- spanKnown: true,- linesPerNotch: 3,- };-- expect(appScrollExtent(known, 24)).toEqual({ total: 424, top: 400 });- expect(appScrollExtent({ ...known, offset: 400 }, 24)).toEqual({- total: 424,- top: 0,- });- expect(appScrollExtent({ ...known, offset: 200 }, 24)).toEqual({- total: 424,- top: 200,- });- });-- it("reports no history at all for an app measured as having none", () => {- const flat: AppScrollPosition = {- offset: 0,- span: 0,- spanKnown: true,- linesPerNotch: 1,- };-- // total === rows, which is how ./paneScroll knows to take the bar away.- expect(appScrollExtent(flat, 24)).toEqual({ total: 24, top: 0 });- });-});--describe("notchesForLines", () => {- it("converts a distance in lines into wheel notches", () => {- expect(notchesForLines(9, 3)).toBe(3);- expect(notchesForLines(-9, 3)).toBe(-3);- expect(notchesForLines(4, 3)).toBe(1);- // A nonsense step must not produce an infinite relay.- expect(notchesForLines(6, 0)).toBe(6);- });-});--describe("appTakesWheel", () => {- it("is the one test that decides which world a pane is in", () => {- expect(appTakesWheel(fakeTerminal([], "any"))).toBe(true);- expect(appTakesWheel(fakeTerminal([], "none"))).toBe(false);- expect(appTakesWheel(null)).toBe(false);- });-});--describe("trackAppScroll", () => {- function wheel(host: HTMLElement, deltaY: number, deltaMode = 1) {- host- .querySelector(".xterm-screen")!- .dispatchEvent(- new WheelEvent("wheel", { bubbles: true, deltaY, deltaMode }),- );- }-- function stage(rows: string[], mouseTrackingMode = "any") {- const host = document.createElement("div");- const screen = document.createElement("div");- screen.className = "xterm-screen";- host.appendChild(screen);- document.body.appendChild(host);-- let term = fakeTerminal(rows, mouseTrackingMode);- let position = AT_LIVE_END;- const stop = trackAppScroll({- host,- getTerminal: () => term,- onChange: (update) => {- position = update(position);- },- });- return {- host,- stop,- show: (next: string[]) => {- term = fakeTerminal(next, mouseTrackingMode);- },- get position() {- return position;- },- };- }-- it("measures the position from a wheel turn the CLI answered", () => {- vi.useFakeTimers();- try {- const pane = stage(transcript(10, 10));-- wheel(pane.host, -1);- pane.show([...transcript(7, 3), ...transcript(10, 7)]);- vi.advanceTimersByTime(SETTLE_MS);-- expect(pane.position).toMatchObject({ offset: 3, linesPerNotch: 3 });- pane.stop();- } finally {- vi.useRealTimers();- }- });-- it("reads the end of the history off a turn that changed nothing", () => {- vi.useFakeTimers();- try {- const pane = stage(transcript(10, 10));-- wheel(pane.host, -1);- vi.advanceTimersByTime(SETTLE_MS);-- expect(pane.position).toMatchObject({ span: 0, spanKnown: true });- pane.stop();- } finally {- vi.useRealTimers();- }- });-- /*- * A held-down wheel would otherwise move the screen further than one screenful- * between snapshots, leaving nothing for the two to be lined up by.- */- it("measures a long burst before it runs off the end of the screen", () => {- vi.useFakeTimers();- try {- const pane = stage(transcript(10, 10));- wheel(pane.host, -1);- pane.show([...transcript(8, 2), ...transcript(10, 8)]);-- // The wheel never stops long enough for the quiet timer to fire, so only- // the burst deadline can produce a reading.- for (let i = 0; i < 5; i += 1) {- vi.advanceTimersByTime(SETTLE_MS - 40);- wheel(pane.host, -1);- }-- expect(pane.position.offset).toBe(2);- pane.stop();- } finally {- vi.useRealTimers();- }- });-- it("only learns a notch's size from notches it sent itself", () => {- vi.useFakeTimers();- try {- const pane = stage(transcript(10, 10));-- // A mouse wheel in pixel mode: the driver's idea of a notch, not ours.- wheel(pane.host, -120, 0);- pane.show([...transcript(4, 6), ...transcript(10, 4)]);- vi.advanceTimersByTime(SETTLE_MS);-- expect(pane.position.offset).toBe(6);- expect(pane.position.linesPerNotch).toBe(AT_LIVE_END.linesPerNotch);- pane.stop();- } finally {- vi.useRealTimers();- }- });-- it("leaves a pane whose terminal owns its scrollback alone", () => {- vi.useFakeTimers();- try {- const pane = stage(transcript(10, 10), "none");-- wheel(pane.host, -1);- vi.advanceTimersByTime(BURST_MS);-- expect(pane.position).toBe(AT_LIVE_END);- pane.stop();- } finally {- vi.useRealTimers();- }- });-- it("leaves no timer running behind a pane that goes away", () => {- vi.useFakeTimers();- try {- const pane = stage(transcript(10, 10));- wheel(pane.host, -1);-- pane.stop();-- expect(vi.getTimerCount()).toBe(0);- } finally {- vi.useRealTimers();- }- });-- /*- * What the probe is FOR: a CLI that holds its own history reveals it, and the- * user ends up back where they started. Measured through the real tracker,- * because keeping the two notches in separate bursts is the whole point.- */- it("makes an untouched pane's history measurable without moving the user", () => {- vi.useFakeTimers();- try {- const pane = stage(transcript(10, 10));- expect(hasMeasuredHistory(pane.position)).toBe(false);-- const stop = probeAppHistory((direction) => {- wheel(pane.host, direction);- // What the CLI repaints in answer: one line of older output on the way- // back, the live screen again on the way home.- pane.show(- direction < 0- ? [...transcript(9, 1), ...transcript(10, 9)]- : transcript(10, 10),- );- });- vi.advanceTimersByTime(PROBE_RETURN_MS);- vi.advanceTimersByTime(SETTLE_MS);- stop();-- // A history is now known to exist — so the bar has something to describe.- expect(hasMeasuredHistory(pane.position)).toBe(true);- // And the user is where they were: at the agent's newest output.- expect(pane.position.offset).toBe(0);- pane.stop();- } finally {- vi.useRealTimers();- }- });-- /*- * And the honest negative: an application with nothing above its screen does- * not move, which is the one exact answer this measurement gets — so the pane- * keeps no bar rather than being given a fake one.- */- it("reports no history for an application that does not scroll", () => {- vi.useFakeTimers();- try {- const pane = stage(transcript(10, 10));-- const stop = probeAppHistory((direction) => wheel(pane.host, direction));- vi.advanceTimersByTime(PROBE_RETURN_MS);- vi.advanceTimersByTime(SETTLE_MS);- stop();-- expect(pane.position.spanKnown).toBe(true);- expect(pane.position.span).toBe(0);- expect(appScrollExtent(pane.position, 10).total).toBe(10);- pane.stop();- } finally {- vi.useRealTimers();- }- });-});--describe("probeAppHistory", () => {- it("goes one notch back and comes straight back", () => {- vi.useFakeTimers();- try {- const sent: number[] = [];- probeAppHistory((direction) => sent.push(direction));-- // Asked immediately, so the answer is on its way the moment the user- // reaches for the bar.- expect(sent).toEqual([-1]);-- vi.advanceTimersByTime(PROBE_RETURN_MS);-- expect(sent).toEqual([-1, 1]);- } finally {- vi.useRealTimers();- }- });-- /*- * The two notches must be measured SEPARATELY. Sent inside one burst they- * cancel out into an intent of zero, `trackAppScroll` measures nothing, and the- * probe would move the screen twice for no answer at all.- */- it("waits out a settle period before returning", () => {- vi.useFakeTimers();- try {- const sent: number[] = [];- probeAppHistory((direction) => sent.push(direction));-- vi.advanceTimersByTime(SETTLE_MS);-- expect(sent).toEqual([-1]);- } finally {- vi.useRealTimers();- }- });-- it("brings the application back when the probe is abandoned early", () => {- vi.useFakeTimers();- try {- const sent: number[] = [];- const stop = probeAppHistory((direction) => sent.push(direction));-- // The pointer left the hot zone a frame later. A pane parked one line into- // its history would be the probe showing through.- stop();-- expect(sent).toEqual([-1, 1]);- expect(vi.getTimerCount()).toBe(0);- } finally {- vi.useRealTimers();- }- });-- it("returns exactly once, however it is torn down", () => {- vi.useFakeTimers();- try {- const sent: number[] = [];- const stop = probeAppHistory((direction) => sent.push(direction));-- vi.advanceTimersByTime(PROBE_RETURN_MS);- stop();- stop();-- expect(sent).toEqual([-1, 1]);- } finally {- vi.useRealTimers();- }- });-});diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.ts b/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.tsdeleted file mode 100644index ccaf26f58e..0000000000--- a/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.ts+++ /dev/null@@ -1,517 +0,0 @@-/**- * Where a full-screen CLI sits in ITS OWN history — measured, not guessed.- *- * ## The problem this exists to solve- *- * A CLI that takes the mouse (Claude Code and every other Ink-style agent UI)- * keeps its transcript to itself: the terminal's buffer holds one screen, the- * wheel is forwarded to the application, and nothing xterm can be asked reveals- * how far back the user has scrolled. See ./paneScroll for the full measurement.- *- * The first answer to that was to draw no position at all — a bar spanning the- * whole track with a small marking parked in its middle, meaning "there is no- * position here". It did not read that way. The full-track bar is drawn faintly- * by design, so the marking is the only part anyone actually sees, and a short- * bright shape halfway up a track says exactly one thing in the only grammar- * scrollbars have: *you are in the middle*. Reported 2026-07-27 by a pane- * sitting at the live end of its transcript. Refusing to answer with the shape- * an answer is given in is not refusing to answer.- *- * ## So the position is measured, from the one thing that is observable- *- * The application will not tell us where it is, but it will SHOW us: scroll it- * and the lines on screen move. That movement is the measurement.- *- * Around every burst of wheel events the screen is snapshotted before and after,- * and {@link detectShift} recovers how far the content travelled by finding the- * row offset that lines the two snapshots up. From there:- *- * * content moved **down** → the user went back into history; the distance from- * the live end grows by exactly that many lines,- * * content did **not move** although a scroll was asked for → an end of the- * history was reached, which is how both the top (the extent becomes known)- * and the bottom (the distance is truly zero) are pinned down exactly,- * * how far one wheel notch moves the application is itself learned from the- * same measurement, so dragging the thumb can aim.- *- * Nothing here is assumed about which CLI is running, what it draws, or what its- * keys do. It is the same technique a screen reader uses to follow a TUI, and it- * works on any application that scrolls its own output.- *- * ## What it is honest about- *- * Before anyone has scrolled, NOTHING about the history is known — not its- * extent and not whether it exists at all — and a bar is drawn only once- * something has actually been measured ({@link hasMeasuredHistory}).- *- * That rule replaces an assumption. An untouched pane used to be credited with- * "at least one more screen above", which put a half-track thumb at the bottom- * of the track — and the other half of the track was then empty furniture down- * the side of every pane that nobody had scrolled yet, which is every pane in a- * fresh workspace (reported 2026-07-27, second round on the same strip). The- * assumed screenful was not measured, so the empty half was paying for a claim- * this module had no evidence for.- *- * Once a wheel notch HAS been measured the extent is real, and the arithmetic- * below applies as before: while the top is still unfound one more screen is- * assumed above the deepest point reached, which is a claim about size only —- * openly made, corrected by the next measurement, and never a claim about- * position. A full-screen application with no history at all (a dashboard, a- * pager on a short file) reveals itself on the first scroll attempt that moves- * nothing, and its pane keeps no bar either.- */-import type { Terminal } from "@xterm/xterm";--/**- * True when the running application receives wheel events itself.- *- * The one test that decides which of the two worlds a pane is in — see- * ./paneScroll, which re-exports this. It lives here because everything on this- * side of the line depends on it, and a shared module may not import back into- * the one that imports it.- */-export function appTakesWheel(term: Terminal | null): boolean {- const tracking = term?.modes?.mouseTrackingMode;- return Boolean(tracking) && tracking !== "none";-}--export interface AppScrollPosition {- /** Lines between the top of the screen and the live end. 0 = newest output. */- offset: number;- /** How much history is known to exist above the live end, in lines. */- span: number;- /**- * True once a scroll towards older output moved nothing: `span` is then the- * real top of the transcript rather than a lower bound.- */- spanKnown: boolean;- /** Lines the application moves per wheel notch, as measured. */- linesPerNotch: number;-}--/** What a pane is before anybody has scrolled it: showing the newest output. */-export const AT_LIVE_END: AppScrollPosition = {- offset: 0,- span: 0,- spanKnown: false,- linesPerNotch: 1,-};--/**- * Has anything about this pane's history actually been measured yet?- *- * The gate between "we know nothing" and "we know something", and the reason a- * fresh pane draws no bar at all — see the file header. Any one of the three is- * enough: the user is standing away from the live end, a depth has been reached- * at some point, or a scroll towards older output ran into the top.- *- * Deliberately a property of the VALUE rather than an identity check against- * {@link AT_LIVE_END}. A position that travelled back into the history and- * returned to the newest output is no longer that constant, but it has learned- * that the history exists — and a pane the user has already scrolled once must- * keep the bar they scrolled it with.- */-export function hasMeasuredHistory(position: AppScrollPosition): boolean {- return position.spanKnown || position.span > 0 || position.offset > 0;-}--/**- * Did the measurement come back saying there is no history at all?- *- * A real answer, but only about the moment it was taken — and that is the whole- * point of asking it separately. A pane opened a minute ago holds one screen and- * nothing above it, so the first probe honestly finds nothing; ten minutes of an- * agent printing later there are pages of it, and a measurement kept as final- * would leave that pane without a bar for the rest of its life. Which is the bug- * the probe exists to fix, arriving through a different door.- *- * So the caller re-asks a pane that answered this way once it has had time to- * produce something (`PROBE_STALE_MS`). "There is history" needs no such- * expiry: a transcript does not get shorter.- */-export function measuredNoHistory(position: AppScrollPosition): boolean {- return position.spanKnown && position.span === 0 && position.offset === 0;-}--/**- * Fewest recognisable rows two screens need before they may be compared.- *- * A near-empty screen matches itself at every offset, so a shift measured off- * one would be noise presented as a position.- */-export const MIN_COMPARABLE_ROWS = 4;--/** Longest jump one notch may be credited with — a guard against a bad match. */-export const MAX_LINES_PER_NOTCH = 12;--function clamp(value: number, low: number, high: number): number {- return value < low ? low : value > high ? high : value;-}--/** Rows carrying enough text to identify themselves again after a scroll. */-function identifiable(text: string): boolean {- return text.trim().length > 2;-}--/**- * How many rows hold different text than they did a moment ago.- *- * The evidence that SOMETHING happened, counted without any claim about what.- * A row that was blank and still is does not count, and neither does trailing- * whitespace — an application that repaints a row with the same text on it has- * not moved anything.- *- * Used by {@link detectShift} to tell its two silences apart. See the reasoning- * there: a screen full of short, look-alike rows can be scrolled without a- * single row being recognisable afterwards, and the difference between "it did- * not move" and "we cannot say how far" is the difference between a pane that- * keeps its scrollbar and one that loses it.- */-function restlessRows(before: string[], after: string[]): number {- const rows = Math.max(before.length, after.length);- let restless = 0;- for (let i = 0; i < rows; i += 1) {- const was = (before[i] ?? "").trim();- const now = (after[i] ?? "").trim();- if (was !== now && (was !== "" || now !== "")) restless += 1;- }- return restless;-}--/**- * The lines currently on screen, top row first.- *- * Defensive like the rest of this area: an xterm build without `getLine`, or a- * pane whose terminal is not up yet, yields an empty screen rather than throwing- * inside an event handler.- */-export function visibleRows(term: Terminal | null): string[] {- const buffer = term?.buffer?.active;- const rows = term?.rows ?? 0;- if (!term || !buffer || rows < 1 || typeof buffer.getLine !== "function") {- return [];- }- const base = buffer.viewportY ?? 0;- const lines: string[] = [];- for (let i = 0; i < rows; i += 1) {- const line = buffer.getLine(base + i);- lines.push(line ? line.translateToString(true).trimEnd() : "");- }- return lines;-}--/**- * How far the screen's content travelled between two snapshots.- *- * Positive means the content moved DOWN the screen — older lines appeared above- * it — which is what scrolling back through a history looks like. Null means the- * two screens have too little in common to compare, which happens when a pane- * repaints completely or scrolls further than one screenful at a time.- *- * The offset that lines up the most rows wins, with a tie going to the smallest- * movement, so a screen where only a spinner changed reads as "did not move"- * rather than as an arbitrary shift. Rows an application pins to the bottom —- * the prompt box and status line of a coding agent — match at zero and nowhere- * else, so they raise every candidate's floor equally and never decide the- * outcome as long as the scrolling region is the larger part of the screen.- *- * ## Zero is a verdict, and it is only reached on a still screen- *- * "Did not move" is the single most consequential answer this function gives:- * {@link applyShift} reads it as an end of the history, and an end of the- * history at distance zero is a pane with nothing to scroll — which takes its- * scrollbar away. So it may only be returned when the screen really did stand- * still, and NOT merely because nothing recognisable lined up.- *- * Those two came apart on a real transcript. When the scrolling region is- * short, look-alike rows — a column of numbers, a file tree, a wrapped list —- * every one of them fails the `identifiable` test above, the only rows left to- * vote are the prompt box and status line the application pins to the bottom,- * and those match at zero by construction. The screen had scrolled by three- * lines; the measurement reported that it had not moved at all, and the pane- * was recorded as having no history to scroll (measured 2026-07-27 against- * Claude Code 2.1.220, replaying a recorded session into a real terminal).- *- * Hence the last guard: if rows changed that no offset accounts for, the honest- * answer is null — we cannot say how far it went — and never zero.- */-export function detectShift(before: string[], after: string[]): number | null {- const anchors = before.filter(identifiable).length;- if (before.length < MIN_COMPARABLE_ROWS || anchors < MIN_COMPARABLE_ROWS) {- return null;- }-- const reach = Math.max(before.length, after.length) - 1;- let best = 0;- let bestScore = -1;- for (let shift = -reach; shift <= reach; shift += 1) {- let score = 0;- for (let i = 0; i < before.length; i += 1) {- const j = i + shift;- if (j < 0 || j >= after.length) continue;- if (identifiable(before[i]) && before[i] === after[j]) score += 1;- }- if (- score > bestScore ||- (score === bestScore && Math.abs(shift) < Math.abs(best))- ) {- best = shift;- bestScore = score;- }- }- if (bestScore < MIN_COMPARABLE_ROWS) return null;- // Zero only stands for a screen that stood still — see the header above.- if (best === 0 && restlessRows(before, after) >= MIN_COMPARABLE_ROWS) {- return null;- }- return best;-}--/**- * Fold one burst of scrolling into a position.- *- * `intent` is the wheel direction that was asked for, in `deltaY` signs —- * positive towards newer output. `observed` is what {@link detectShift} saw, or- * null when the screens could not be compared; an unmeasurable burst falls back- * to what was SENT, and deliberately claims no end of the history, because- * "nothing moved" and "we could not tell" must never collapse into each other.- */-export function applyShift(- position: AppScrollPosition,- observed: number | null,- intent: number,-): AppScrollPosition {- const towardsOlder = intent < 0;- const moved = observed ?? -intent * position.linesPerNotch;-- let offset = Math.max(0, position.offset + moved);- let span = position.span;- let spanKnown = position.spanKnown;- let linesPerNotch = position.linesPerNotch;-- if (observed !== null && intent !== 0) {- if (observed === 0) {- // A scroll that moved nothing is an end of the history — the only exact- // fix this measurement ever gets, and worth more than any accumulated sum.- if (towardsOlder) {- span = offset;- spanKnown = true;- } else {- offset = 0;- }- } else if (Math.abs(observed) >= Math.abs(intent)) {- // Only an unclamped move says anything about a notch's size: one that ran- // into the end of the history moved less than the application would have.- linesPerNotch = clamp(- Math.round(Math.abs(observed) / Math.abs(intent)),- 1,- MAX_LINES_PER_NOTCH,- );- }- }-- // Scrolling past a top we thought we knew means we never knew it — the- // transcript grew, or the earlier reading was wrong.- if (offset > span) {- span = offset;- if (observed === null || observed !== 0 || !towardsOlder) spanKnown = false;- }-- return { offset, span, spanKnown, linesPerNotch };-}--/**- * The buffer arithmetic a scrollbar needs for a measured position.- *- * Returns the numbers a plain scrollback pane would report — total lines and- * the line at the top of the viewport — so both kinds of pane draw their thumb- * through exactly the same geometry.- */-export function appScrollExtent(- position: AppScrollPosition,- rows: number,-): { total: number; top: number } {- const reached = Math.max(position.span, position.offset);- // While the top is unfound, one more screenful is assumed to exist above:- // enough for the thumb to have somewhere to travel, never enough to pretend- // the user is anywhere but where they are.- const span = position.spanKnown ? reached : reached + rows;- return { total: span + rows, top: span - Math.min(position.offset, span) };-}--/** Wheel notches that move an application `lines` towards newer output. */-export function notchesForLines(lines: number, linesPerNotch: number): number {- return Math.round(lines / Math.max(1, linesPerNotch));-}--/** Quiet time after the last wheel event before the screen is re-measured. */-export const SETTLE_MS = 120;--/**- * How long a probe stays one notch back before it returns.- *- * One settle period plus a margin: the two notches must land in SEPARATE bursts- * or {@link trackAppScroll} folds them into one intent of zero and measures- * nothing at all.- */-export const PROBE_RETURN_MS = SETTLE_MS + 60;--/**- * Quiet time a pane must have before it is probed at all.- *- * Longer than one settle period on purpose. A user who is turning the wheel is- * already measuring the pane far better than a probe could, and two sources of- * movement folded into one burst measure neither — so the probe waits for the- * tracker to fall silent, by which time a real scroll has answered the question- * and no probe is sent.- */-export const PROBE_WAIT_MS = SETTLE_MS + 40;--/**- * How long an answer that found nothing stands before the pane may be re-asked.- *- * See {@link measuredNoHistory}: that answer is true of a moment, not of a pane.- * The same goes for the probe that produced no answer at all — a terminal that- * was still being built, a relay that landed while the application was busy- * repainting. Both leave the pane exactly as it was: without a bar.- *- * A minute was far too long for that. Re-asking costs nothing precisely BECAUSE- * the last answer was "nothing here": a probe against a pane with no history- * moves nothing and is invisible, and one against a pane that has since filled- * up is the measurement that gives it its scrollbar back. Seconds, then — long- * enough that nobody meets the probe twice in one reach for the edge, short- * enough that the next reach after the pane fills up finds a working bar.- *- * "There IS history" is the one answer that never expires: a transcript does not- * get shorter.- */-export const PROBE_STALE_MS = 5_000;--/**- * Ask a full-screen CLI whether it has a history — without moving the user.- *- * The measurement above only ever happened as a side effect of somebody turning- * the wheel, and that left the scrollbar unreachable in exactly the panes it was- * written for. A CLI that holds its own history draws NO bar until something has- * been measured (see {@link hasMeasuredHistory}, and the reasoning in the file- * header) — so reaching for the right edge of an untouched Claude Code pane- * revealed nothing, and the only way to make the bar appear was the wheel, which- * is the one input that makes the bar unnecessary. Reported 2026-07-27, third- * round on this strip, and the first two rounds are why the empty bar is not an- * option: the fix cannot be "draw something anyway".- *- * So the question gets asked instead of waited for. One notch towards older- * output, one settle period for the tracker to see what the screen did, one notch- * back — a round trip the user does not end up anywhere different from, and after- * which the answer is real: either a history exists and the bar can describe it,- * or the screen did not move and the pane honestly keeps no bar.- *- * `relay` hands over one notch in the direction given (-1 towards older output),- * i.e. `relayWheelNotch` in ./paneScroll. Returns a teardown that brings the- * application back immediately if the probe is abandoned early — a pane left one- * line into its history because the pointer moved away would be the probe- * showing through.- */-export function probeAppHistory(- relay: (direction: 1 | -1) => void,-): () => void {- let returned = false;- const comeBack = () => {- if (returned) return;- returned = true;- relay(1);- };-- relay(-1);- const timer = window.setTimeout(comeBack, PROBE_RETURN_MS);- return () => {- window.clearTimeout(timer);- comeBack();- };-}--/**- * Longest a burst may run before it is measured anyway.- *- * A held-down scroll would otherwise move the screen further than one screenful- * between snapshots, leaving the two with nothing in common and the measurement- * with nothing to work from.- */-export const BURST_MS = 260;--export interface AppScrollTrackerOptions {- /** The xterm host every wheel event for this pane passes through. */- host: HTMLElement;- getTerminal: () => Terminal | null;- onChange: (next: (previous: AppScrollPosition) => AppScrollPosition) => void;-}--/**- * Watch a pane's wheel traffic and keep its measured position up to date.- *- * Returns the teardown. Attached in the capture phase so it sees the wheel- * whether the user turned it over the terminal or the scrollbar relayed it, and- * passively so it can never interfere with the event xterm is about to encode- * for the application.- */-export function trackAppScroll({- host,- getTerminal,- onChange,-}: AppScrollTrackerOptions): () => void {- let before: string[] | null = null;- let intent = 0;- let notchesOnly = true;- let quiet: number | undefined;- let deadline: number | undefined;-- const settle = () => {- if (quiet !== undefined) window.clearTimeout(quiet);- if (deadline !== undefined) window.clearTimeout(deadline);- quiet = undefined;- deadline = undefined;-- const snapshot = before;- const asked = intent;- const synthetic = notchesOnly;- before = null;- intent = 0;- notchesOnly = true;- if (!snapshot || asked === 0) return;-- const observed = detectShift(snapshot, visibleRows(getTerminal()));- onChange((previous) => {- const next = applyShift(previous, observed, asked);- // A notch's size may only be learned from notches we sent ourselves: a- // mouse wheel reports whatever its driver feels like, so counting its- // events as notches would teach the drag the wrong step.- return synthetic- ? next- : { ...next, linesPerNotch: previous.linesPerNotch };- });- };-- const onWheel = (event: WheelEvent) => {- const term = getTerminal();- // A pane whose terminal owns its scrollback needs none of this: its- // viewport already reports the truth.- if (!appTakesWheel(term) || event.deltaY === 0) return;- if (!before) before = visibleRows(term);- intent += event.deltaY > 0 ? 1 : -1;- // Our own relays are emitted as exactly one line in line mode — see- // `relayWheelNotch` in ./paneScroll.- if (event.deltaMode !== 1 || Math.abs(event.deltaY) !== 1) {- notchesOnly = false;- }- if (quiet !== undefined) window.clearTimeout(quiet);- quiet = window.setTimeout(settle, SETTLE_MS);- if (deadline === undefined) deadline = window.setTimeout(settle, BURST_MS);- };-- host.addEventListener("wheel", onWheel, { capture: true, passive: true });- return () => {- if (quiet !== undefined) window.clearTimeout(quiet);- if (deadline !== undefined) window.clearTimeout(deadline);- host.removeEventListener("wheel", onWheel, { capture: true });- };-}diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.tsdeleted file mode 100644index 297aa08daa..0000000000--- a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.ts+++ /dev/null@@ -1,285 +0,0 @@-import { describe, expect, it } from "vitest";-import type { Terminal } from "@xterm/xterm";-import {- MIN_THUMB_PX,- lineForThumbTop,- readScrollState,- relayWheelNotch,- thumbGeometry,-} from "./paneScroll";-import { AT_LIVE_END, type AppScrollPosition } from "./paneAppScroll";--interface FakeOptions {- type?: "normal" | "alternate";- length?: number;- rows?: number;- viewportY?: number;- mouseTrackingMode?: string;-}--function fakeTerminal({- type = "normal",- length = 100,- rows = 24,- viewportY = 0,- mouseTrackingMode = "none",-}: FakeOptions = {}): Terminal {- return {- rows,- modes: { mouseTrackingMode },- buffer: { active: { type, length, viewportY, baseY: length - rows } },- } as unknown as Terminal;-}--/** An app-mode pane whose history has been measured end to end. */-function measured(- overrides: Partial<AppScrollPosition> = {},-): AppScrollPosition {- return {- offset: 0,- span: 400,- spanKnown: true,- linesPerNotch: 3,- ...overrides,- };-}--describe("readScrollState", () => {- it("reports scrollback for a terminal that holds its own history", () => {- const state = readScrollState(fakeTerminal({ length: 100, rows: 24 }));-- expect(state).toEqual({ mode: "scrollback", total: 100, rows: 24, top: 0 });- });-- it("reports nothing to scroll while the buffer still fits on screen", () => {- expect(readScrollState(fakeTerminal({ length: 24, rows: 24 })).mode).toBe(- "none",- );- });-- /*- * The regression this whole component exists for. Claude Code 2.1.220 opens a- * session with ESC[?1049h (alternate screen) plus ESC[?1000h/1002h/1003h/1006h- * (SGR mouse tracking): the terminal keeps no scrollback, so the native- * viewport scrollbar has nothing to move, and the wheel belongs to the CLI.- */- it("reports app mode for a full-screen CLI that took the mouse", () => {- const state = readScrollState(- fakeTerminal({ type: "alternate", mouseTrackingMode: "any", rows: 30 }),- measured({ offset: 120 }),- );-- expect(state).toEqual({ mode: "app", total: 430, rows: 30, top: 280 });- });-- /*- * The follow-up regression, and the reason the check reads the mouse before- * the buffer type. Claude Code 2.1.195 was measured holding the mouse while- * still on the NORMAL buffer, leaving a viewport of `scrollHeight 286 /- * clientHeight 242 / scrollTop 44` behind it: a few stale lines, pinned to- * the end forever. Read as scrollback that draws a thumb filling 85% of the- * track, parked at the bottom — telling somebody halfway up the agent's own- * transcript that they are at the very end of it.- */- it("reports app mode for a CLI that took the mouse on the normal buffer", () => {- const state = readScrollState(- fakeTerminal({- type: "normal",- mouseTrackingMode: "any",- length: 28,- rows: 24,- viewportY: 4,- }),- measured({ offset: 200 }),- );-- expect(state.mode).toBe("app");- // Not one number from the frozen viewport: the position is the measured one.- expect(state).toMatchObject({ total: 424, rows: 24, top: 200 });- });-- /*- * A pane nobody has scrolled yet still gets a bar, sized from the least its- * history could be — one screenful above the newest output.- *- * This was the other way round for one round, so that an unscrolled pane- * would not spend half its track on an assumption. It made every failed- * measurement indistinguishable from "this pane cannot scroll", and left the- * bar unreachable in the only kind of pane that needs it. Half a track of- * assumption you can drag beats a correct silence you cannot.- */- it("draws a bar for an app-mode pane nothing has been measured on", () => {- const state = readScrollState(- fakeTerminal({ type: "alternate", mouseTrackingMode: "any", rows: 30 }),- AT_LIVE_END,- );-- expect(state).toMatchObject({ mode: "app", total: 60, rows: 30, top: 30 });- // At the newest output: the thumb sits at the bottom of its track.- const geometry = thumbGeometry(state, 300)!;- expect(geometry.topPx + geometry.heightPx).toBe(300);- });-- /*- * And the moment there IS a measurement, the pane showing the agent's newest- * output draws its thumb AT THE BOTTOM — the original reported bug, which the- * gate above must not quietly undo. `span` without `offset` is a pane that- * travelled back through the history and came home to the live end.- */- it("puts a measured app-mode pane at the live end", () => {- const state = readScrollState(- fakeTerminal({ type: "alternate", mouseTrackingMode: "any", rows: 30 }),- measured({ offset: 0, span: 90, spanKnown: true }),- );- const geometry = thumbGeometry(state, 300)!;-- expect(state.mode).toBe("app");- expect(geometry.topPx + geometry.heightPx).toBe(300);- });-- /*- * A full-screen application with no history of its own — a dashboard, a pager- * on a short file — proves it the first time a scroll moves nothing. From then- * on it gets no bar rather than a thumb filling its own track.- */- it("takes the bar away from an app measured as having no history", () => {- const state = readScrollState(- fakeTerminal({ type: "alternate", mouseTrackingMode: "any" }),- measured({ span: 0 }),- );-- expect(state.mode).toBe("none");- });-- it("stays away from a full-screen app that did not take the mouse", () => {- // Relaying a wheel notch to one of those would arrive in its input as the- // raw escape sequence, so no bar is the correct answer.- expect(readScrollState(fakeTerminal({ type: "alternate" })).mode).toBe(- "none",- );- });-- it("survives a terminal that is not built yet", () => {- expect(readScrollState(null).mode).toBe("none");- expect(readScrollState({} as Terminal).mode).toBe("none");- });-});--describe("thumbGeometry", () => {- it("sizes the thumb by how much of the buffer is on screen", () => {- const state = readScrollState(fakeTerminal({ length: 400, rows: 100 }));-- expect(thumbGeometry(state, 400)).toEqual({ topPx: 0, heightPx: 100 });- });-- it("keeps a deep scrollback's thumb grabbable", () => {- const state = readScrollState(fakeTerminal({ length: 10000, rows: 24 }));-- expect(thumbGeometry(state, 300)?.heightPx).toBe(MIN_THUMB_PX);- });-- it("puts the thumb at the bottom when the viewport is at the live end", () => {- const state = readScrollState(- fakeTerminal({ length: 124, rows: 24, viewportY: 100 }),- );- const geometry = thumbGeometry(state, 400)!;-- expect(geometry.topPx + geometry.heightPx).toBe(400);- });-- /*- * The bug this shape exists to prevent, from the other side. A short bright- * shape halfway up a track says "you are in the middle" in the only grammar- * scrollbars have — so an app-mode pane draws its thumb from a real measured- * position, through this same geometry, rather than parking a marking in the- * middle and hoping to be read as saying nothing.- */- it("draws an app-mode pane through the very same geometry", () => {- const term = fakeTerminal({- type: "alternate",- mouseTrackingMode: "any",- rows: 24,- });-- expect(thumbGeometry(readScrollState(term, measured()), 400)).toEqual(- thumbGeometry(- readScrollState(- fakeTerminal({ length: 424, rows: 24, viewportY: 400 }),- ),- 400,- ),- );- // And the top of the history is the top of the track.- expect(- thumbGeometry(readScrollState(term, measured({ offset: 400 })), 400)- ?.topPx,- ).toBe(0);- });-- it("draws nothing when there is nothing to scroll", () => {- expect(thumbGeometry(readScrollState(null), 300)).toBeNull();- expect(- thumbGeometry(readScrollState(fakeTerminal({ length: 400 })), 0),- ).toBeNull();- });-});--describe("lineForThumbTop", () => {- it("maps the ends of the track to the ends of the scrollback", () => {- const state = readScrollState(fakeTerminal({ length: 1024, rows: 24 }));-- expect(lineForThumbTop(0, 400, state)).toBe(0);- expect(lineForThumbTop(400, 400, state)).toBe(1000);- });-- it("clamps a drag that ran past the track", () => {- const state = readScrollState(fakeTerminal({ length: 1024, rows: 24 }));-- expect(lineForThumbTop(-500, 400, state)).toBe(0);- expect(lineForThumbTop(5000, 400, state)).toBe(1000);- });-- it("answers for an app-mode pane too, so its thumb can be dragged", () => {- const state = readScrollState(- fakeTerminal({ type: "alternate", mouseTrackingMode: "any", rows: 24 }),- measured({ offset: 400 }),- );-- expect(lineForThumbTop(0, 400, state)).toBe(0);- expect(lineForThumbTop(400, 400, state)).toBe(400);- });-});--describe("relayWheelNotch", () => {- function host(): HTMLElement {- const element = document.createElement("div");- const screen = document.createElement("div");- screen.className = "xterm-screen";- element.appendChild(screen);- document.body.appendChild(element);- return element;- }-- it("dispatches a wheel event xterm can encode for the running CLI", () => {- const element = host();- const seen: WheelEvent[] = [];- element.addEventListener("wheel", (event) =>- seen.push(event as WheelEvent),- );-- relayWheelNotch(element, -1);-- expect(seen).toHaveLength(1);- // Lines, not pixels: xterm divides a pixel delta by the row height and- // carries the remainder, so a synthetic pixel delta can round to no lines- // at all and be dropped before it is ever encoded. It is also how- // ./paneAppScroll recognises a notch it sent itself.- expect(seen[0].deltaMode).toBe(1);- expect(seen[0].deltaY).toBe(-1);- });-- it("does nothing without a rendered terminal to aim at", () => {- expect(relayWheelNotch(null, 1)).toBe(false);- expect(relayWheelNotch(document.createElement("div"), 1)).toBe(false);- });-});diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.ts b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.tsdeleted file mode 100644index 581c35f2d7..0000000000--- a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.ts+++ /dev/null@@ -1,263 +0,0 @@-/**- * What a terminal pane can scroll right now, and where its scrollbar sits.- *- * ## Why this is not just CSS on the xterm viewport- *- * The obvious way to give a pane a scrollbar is to style `.xterm-viewport` and- * let the browser draw the native one. That works for a CLI which prints line- * by line — Codex does, and its bar behaved perfectly. It does nothing at all- * for Claude Code, and the reason is a property of the CLI rather than a bug in- * the styling: measured against Claude Code 2.1.220, the moment it opens a real- * session it emits- *- * ESC[?1049h switch to the ALTERNATE screen buffer- * ESC[?1000h ESC[?1002h ESC[?1003h ESC[?1006h full SGR mouse tracking- *- * In the alternate buffer a terminal has no scrollback by definition — the- * application owns the whole screen and keeps its own history, exactly like- * `vim` or `less`. So `.xterm-viewport` has nothing to scroll, the native thumb- * fills its track, and no amount of CSS can move it. Meanwhile the mouse- * tracking means the wheel is no longer the terminal's to handle: xterm- * forwards it and Claude Code scrolls its own transcript.- *- * ## The mouse, not the buffer, is what decides- *- * The alternate buffer is the loud symptom, but it is not the cause, and gating- * on it alone was wrong. A CLI may keep its transcript to itself while staying- * on the NORMAL buffer — measured against Claude Code 2.1.195 running here, the- * viewport reported `scrollHeight 286 / clientHeight 242 / scrollTop 44`: a- * handful of stale lines behind a live screen, permanently pinned to the end.- * That is the worst of both worlds, because it looks like honest scrollback:- * the bar drew a thumb filling 85% of its track and parked it at the bottom,- * announcing "you are at the end" to somebody reading the middle of Claude- * Code's own history.- *- * What actually settles it is mouse tracking. Once a CLI asks for the mouse,- * xterm hands it every wheel event and stops scrolling its viewport at all- * (`Terminal._bindMouse`: the viewport only sees a wheel the application did- * not take). From that moment the viewport is frozen furniture in whatever- * buffer it happens to be, its position says nothing about what the user is- * looking at, and any proportional thumb drawn from it is a lie. So the check- * below reads the mouse FIRST and the buffer type second.- *- * Hence two sources for one and the same picture:- *- * * `scrollback` — the terminal holds the history and the wheel (Codex, a plain- * shell). Position and extent are read straight off xterm's buffer.- * * `app` — the application took the mouse, so it holds the history (Claude- * Code). Position and extent are MEASURED from how far the screen's content- * moves when it is scrolled — see ./paneAppScroll.- * * `none` — nothing to scroll: a terminal whose buffer fits on screen, or an- * application MEASURED as having no history at all. The bar stays away- * instead of drawing a dead track.- *- * ## Both modes draw the same thumb, because both now know the same things- *- * `app` mode used to draw a fixed grip centred in the track instead of a- * position, on the reasoning that a shape which never moves cannot lie. It- * lied anyway — just in a language the code was not reading. Every scrollbar- * anyone has ever used says "you are here" with exactly that shape, so a pane- * parked at the live end of Claude Code's transcript showed a marking halfway- * up its track and was read, correctly by the only grammar available, as "you- * are halfway up" (reported 2026-07-27). Abstaining from a claim is not the- * same as saying nothing when the shape you abstain with is the shape the- * claim is made in.- *- * The fix was not a different shape but a real answer: ./paneAppScroll measures- * the application's position from its own screen, so `app` mode has a genuine- * line count to report and the geometry below is shared, unconditionally. The- * only thing still specific to `app` mode is HOW a drag is carried out —- * relayed wheel notches instead of a viewport call — because that is the only- * language the application listens in.- *- * ## A measurement sizes the bar. It does not decide whether there is one.- *- * For one round it did decide, and `app` mode drew nothing until something had- * been measured — so that an unscrolled pane would not spend half its track on- * an assumed screenful of history (reported 2026-07-27 as a strip of empty- * space down a pane's right-hand side). The cure was worse: EVERY way of- * failing to measure — a screen too alike to compare, a probe sent while the- * agent repainted, an answer that never came — became indistinguishable from- * "this pane cannot scroll", and the bar was unreachable in exactly the panes- * it exists for. Reported four times over, always the same way: it works in a- * Codex pane and nowhere else. A Codex pane never needed a measurement.- *- * So an application-held pane now gets a bar as soon as the pointer reaches for- * it, sized from the least history it could have and draggable straight away;- * the measurement corrects the proportions on the first movement. Only a- * measurement that positively found NO history takes the bar away again — see- * `measuredNoHistory` in ./paneAppScroll. Silence has to be earned.- */-import type { Terminal } from "@xterm/xterm";-import {- appScrollExtent,- appTakesWheel,- AT_LIVE_END,- type AppScrollPosition,-} from "./paneAppScroll";--export { appTakesWheel };--/** Which of the two scrolling worlds a pane is in — see the file header. */-export type PaneScrollMode = "scrollback" | "app" | "none";--export interface PaneScrollState {- mode: PaneScrollMode;- /** Buffer lines in total, scrollback included. */- total: number;- /** Lines visible at once. */- rows: number;- /** Buffer line currently at the top of the viewport. */- top: number;-}--export interface ThumbGeometry {- topPx: number;- heightPx: number;-}--export const IDLE_STATE: PaneScrollState = {- mode: "none",- total: 0,- rows: 0,- top: 0,-};--/** A thumb shorter than this is impossible to grab in a tall pane. */-export const MIN_THUMB_PX = 26;--function clamp(value: number, low: number, high: number): number {- return value < low ? low : value > high ? high : value;-}--/**- * Read a pane's scroll situation off the live terminal.- *- * `position` is what ./paneAppScroll has measured of an application that holds- * its own history; it is ignored for a pane whose terminal holds the scrollback- * itself, where xterm's buffer is the better answer.- *- * Defensive by design: this runs against whatever xterm build the app was- * bundled with, and a missing field must degrade to "nothing to scroll" rather- * than throw inside a render.- */-export function readScrollState(- term: Terminal | null,- position: AppScrollPosition = AT_LIVE_END,-): PaneScrollState {- const buffer = term?.buffer?.active;- const rows = term?.rows ?? 0;- if (!term || !buffer || rows < 1) return IDLE_STATE;-- const total = buffer.length ?? rows;- const top = buffer.viewportY ?? 0;-- // The mouse first — see the file header. An application holding the wheel- // holds the history with it, in EITHER buffer, so the viewport it left behind- // is ignored in favour of what the measurement found.- if (appTakesWheel(term)) {- // A bar, unless the pane has been MEASURED as having nothing to scroll.- //- // It used to be the other way round — no bar until something had been- // measured — and that is what kept the whole feature out of reach. Every- // way the measurement could come back empty (a screen that could not be- // compared, a probe that arrived while the agent was repainting, an answer- // that never came) produced the same outcome as "this pane cannot scroll":- // nothing at all, in the one kind of pane the bar was written for. Four- // rounds of reports said the same thing — it works in a Codex pane and- // nowhere else — because a Codex pane needs no measurement to draw a bar.- //- // So the burden of proof is the other way now. Reaching for the edge of a- // pane whose CLI holds its own history gives you a bar you can drag,- // sized from the least it could be — one screenful above, which is what- // `appScrollExtent` assumes until a measurement says otherwise. Dragging- // it relays wheel notches whether anything has been measured or not, and- // the first movement replaces the assumption with the truth.- //- // What still takes the bar away is a real answer: `appScrollExtent`- // reports a total of one screen for a pane measured as having no history,- // and the check below removes it. That is the only silence left.- const extent = appScrollExtent(position, rows);- // A measurement that found no history at all — a dashboard, a pager on a- // short file — takes the bar away rather than drawing a thumb that fills- // its own track.- if (extent.total <= rows) return IDLE_STATE;- return { mode: "app", total: extent.total, rows, top: extent.top };- }-- // Alternate buffer without the mouse: the application draws the whole screen- // and there is nothing to relay a wheel notch to — the escape sequence would- // land in its input as if it had been typed.- if (buffer.type === "alternate") return IDLE_STATE;-- if (total > rows) return { mode: "scrollback", total, rows, top };- return IDLE_STATE;-}--/** Where to draw the thumb inside a track of `trackPx`, or null for no bar. */-export function thumbGeometry(- state: PaneScrollState,- trackPx: number,-): ThumbGeometry | null {- if (trackPx <= 0) return null;- if (state.mode === "none" || state.total <= state.rows) return null;-- const heightPx = Math.min(- trackPx,- Math.max(MIN_THUMB_PX, Math.round((trackPx * state.rows) / state.total)),- );- const maxTop = state.total - state.rows;- const progress = maxTop > 0 ? clamp(state.top / maxTop, 0, 1) : 0;- return { heightPx, topPx: Math.round((trackPx - heightPx) * progress) };-}--/** The buffer line a thumb dragged to `topPx` is asking for. */-export function lineForThumbTop(- topPx: number,- trackPx: number,- state: PaneScrollState,-): number {- const geometry = thumbGeometry(state, trackPx);- if (!geometry) return state.top;- const span = trackPx - geometry.heightPx;- const maxTop = state.total - state.rows;- if (span <= 0 || maxTop <= 0) return 0;- return Math.round(clamp(topPx / span, 0, 1) * maxTop);-}--/**- * Hand one wheel notch to the application running in `host`.- *- * Synthesized as a real `wheel` event on xterm's screen element rather than- * written to the socket by hand, deliberately: xterm already knows which mouse- * protocol the application negotiated (X10, VT200, SGR, …) and encodes the- * report accordingly. Writing the bytes ourselves would mean guessing, and a- * guess wrong by one protocol arrives in the CLI's prompt as garbage.- *- * Emitted in LINE mode with a delta of exactly one, which is also how- * ./paneAppScroll recognises its own relays and learns what a notch is worth.- *- * `direction` is +1 to scroll down (towards newer output), -1 for up.- */-export function relayWheelNotch(- host: HTMLElement | null,- direction: 1 | -1,-): boolean {- if (!host || typeof WheelEvent === "undefined") return false;- const screen = host.querySelector<HTMLElement>(".xterm-screen");- if (!screen) return false;- const rect = screen.getBoundingClientRect();- return screen.dispatchEvent(- new WheelEvent("wheel", {- bubbles: true,- cancelable: true,- clientX: rect.left + rect.width / 2,- clientY: rect.top + rect.height / 2,- // Lines, not pixels: xterm divides a pixel delta by the row height and- // carries the remainder, so a synthetic pixel delta can round to zero- // lines and be dropped entirely.- deltaMode: 1,- deltaY: direction,- }),- );-}diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneScrollModel.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneScrollModel.test.tsnew file mode 100644index 0000000000..99d5f65e67--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/paneScrollModel.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from "vitest";+import {+ appScroll,+ backForThumbTop,+ bufferScroll,+ LINES_PER_NOTCH,+ MIN_THUMB_PX,+ notchesForLines,+ scrollable,+ thumbGeometry,+} from "./paneScrollModel";++describe("bufferScroll", () => {+ it("reads a terminal's own scrollback exactly", () => {+ expect(bufferScroll(1000, 976, 976, 24)).toEqual({+ span: 976,+ back: 0,+ rows: 24,+ });+ });++ it("counts how far back the viewport stands", () => {+ expect(bufferScroll(1000, 976, 900, 24).back).toBe(76);+ });++ it("has nothing to scroll while the buffer fits on screen", () => {+ expect(scrollable(bufferScroll(24, 0, 0, 24))).toBe(false);+ });+});++describe("appScroll", () => {+ /*+ * The claim an application-held pane makes, and the one it must not make. It+ * says "there is at least one more screen above you", which keeps the thumb+ * short enough to travel; it never says "you have reached the top", because+ * nothing outside the application can know that.+ */+ it("always leaves one screen of history above wherever you are", () => {+ expect(appScroll(0, 30)).toEqual({ span: 30, back: 0, rows: 30 });+ expect(appScroll(90, 30)).toEqual({ span: 120, back: 90, rows: 30 });+ });++ it("cannot stand further forward than the newest output", () => {+ expect(appScroll(-40, 30).back).toBe(0);+ });++ it("always has somewhere to scroll, so the bar is always reachable", () => {+ expect(scrollable(appScroll(0, 30))).toBe(true);+ });+});++describe("thumbGeometry", () => {+ it("sizes the thumb by how much of the content is on screen", () => {+ expect(thumbGeometry(bufferScroll(400, 300, 300, 100), 400)).toEqual({+ topPx: 300,+ heightPx: 100,+ });+ });++ /*+ * The reported bug this pins down: a pane showing the newest output must draw+ * its thumb AT THE BOTTOM. A short shape halfway up a track says "you are in+ * the middle" in the only grammar scrollbars have.+ */+ it("puts an untouched pane's thumb at the bottom of the track", () => {+ for (const scroll of [appScroll(0, 30), bufferScroll(1000, 976, 976, 24)]) {+ const geometry = thumbGeometry(scroll, 400)!;+ expect(geometry.topPx + geometry.heightPx).toBe(400);+ }+ });++ it("puts a pane scrolled to the top of its history at the top", () => {+ const geometry = thumbGeometry(bufferScroll(1000, 976, 0, 24), 400)!;+ expect(geometry.topPx).toBe(0);+ });++ it("keeps a deep history's thumb grabbable", () => {+ expect(+ thumbGeometry(bufferScroll(10000, 9976, 9976, 24), 300)?.heightPx,+ ).toBe(MIN_THUMB_PX);+ });++ it("draws no thumb where there is nothing to scroll", () => {+ expect(thumbGeometry(null, 300)).toBeNull();+ expect(thumbGeometry(bufferScroll(24, 0, 0, 24), 300)).toBeNull();+ expect(thumbGeometry(appScroll(0, 30), 0)).toBeNull();+ });++ it("never lets the thumb overflow a very short track", () => {+ const geometry = thumbGeometry(bufferScroll(10000, 9976, 9976, 24), 12)!;+ expect(geometry.heightPx).toBeLessThanOrEqual(12);+ expect(geometry.topPx + geometry.heightPx).toBeLessThanOrEqual(12);+ });+});++describe("backForThumbTop", () => {+ it("reads a dragged thumb as a distance back through the history", () => {+ const scroll = bufferScroll(1000, 976, 976, 24);+ const geometry = thumbGeometry(scroll, 400)!;+ const travel = 400 - geometry.heightPx;++ expect(backForThumbTop(travel, 400, scroll)).toBe(0);+ expect(backForThumbTop(0, 400, scroll)).toBe(976);+ expect(backForThumbTop(travel / 2, 400, scroll)).toBe(488);+ });++ it("is the exact inverse of where the thumb was drawn", () => {+ const scroll = bufferScroll(1000, 976, 500, 24);+ const geometry = thumbGeometry(scroll, 400)!;++ // Within the rounding the thumb's own whole-pixel top costs.+ expect(+ Math.abs(backForThumbTop(geometry.topPx, 400, scroll) - scroll.back),+ ).toBeLessThanOrEqual(3);+ });++ it("stays put when there is nothing to drag", () => {+ expect(backForThumbTop(10, 400, null)).toBe(0);+ });+});++describe("notchesForLines", () => {+ it("converts a distance into whole wheel notches", () => {+ expect(notchesForLines(LINES_PER_NOTCH * 4)).toBe(4);+ expect(notchesForLines(-LINES_PER_NOTCH * 2)).toBe(-2);+ // Less than a notch is no notch — never a rounded-up jump the user did not+ // ask for.+ expect(notchesForLines(LINES_PER_NOTCH - 1)).toBe(0);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneScrollModel.ts b/jarvis/ui/web/frontend/src/components/agentic/paneScrollModel.tsnew file mode 100644index 0000000000..b57e11ce3f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/paneScrollModel.ts@@ -0,0 +1,136 @@+/**+ * What a pane can scroll, and where its scrollbar draws the thumb.+ *+ * Pure arithmetic — no DOM, no terminal, no timers — so the part that decides+ * what the user SEES can be reasoned about on its own.+ *+ * ## Two kinds of pane, one shape of answer+ *+ * * `buffer` — the terminal holds the history and the wheel: Codex, a plain+ * shell. Everything is known exactly, straight off xterm's buffer.+ * * `app` — the application took the whole screen, so it holds its history and+ * answers the wheel itself: Claude Code, and any other full-screen TUI.+ * Nothing about that history is observable from outside.+ *+ * ## What an app-held pane claims, and why it is not a lie+ *+ * A previous version of this feature tried to MEASURE the second kind — nudge+ * the application by a wheel notch, compare the screen before and after, and+ * derive a real position from how far the content travelled. It worked in a+ * test and failed in the product for four rounds straight, because every way+ * that measurement can come back empty (a screen too alike to compare, a nudge+ * that arrives while the agent is repainting) was indistinguishable from "this+ * pane has nothing to scroll" — and the bar simply never appeared.+ *+ * So this one measures nothing. It counts the notches that have been sent and+ * assumes the history goes at least one screen further than wherever you have+ * got to ({@link appScroll}). That yields a thumb which:+ *+ * * sits at the bottom when you are at the newest output — the one position+ * that matters, and the one the application agrees on, because both it and+ * the counter below stop at the same end,+ * * climbs as you scroll back and returns as you scroll forward,+ * * never claims to have reached the top of a history nobody can see.+ *+ * It is an indicator of travel rather than a map of the transcript. That is+ * the honest thing to be when the transcript belongs to somebody else.+ */++/** Lines one wheel notch moves a full-screen application. */+export const LINES_PER_NOTCH = 3;++/** A thumb shorter than this cannot be grabbed in a tall pane. */+export const MIN_THUMB_PX = 28;++export interface PaneScroll {+ /** Lines of history above the current screen. */+ span: number;+ /** Lines the pane stands back from the newest output; 0 is the live end. */+ back: number;+ /** Lines on screen at once. */+ rows: number;+}++export interface ThumbGeometry {+ topPx: number;+ heightPx: number;+}++function clamp(value: number, low: number, high: number): number {+ // A non-finite input is treated as the low end rather than passed through:+ // these numbers come from pointer positions and terminal fields, and one NaN+ // reaching a scroll call moves a pane to nowhere.+ if (!Number.isFinite(value)) return low;+ return value < low ? low : value > high ? high : value;+}++/**+ * What a pane whose terminal owns the scrollback can scroll.+ *+ * `total` is the buffer's length, `base` the line the newest screen starts at,+ * and `viewport` the line currently at the top of it — xterm's own numbers.+ */+export function bufferScroll(+ total: number,+ base: number,+ viewport: number,+ rows: number,+): PaneScroll {+ const span = Math.max(0, total - rows);+ return { span, back: clamp(base - viewport, 0, span), rows };+}++/**+ * What a pane whose APPLICATION owns the screen claims to be able to scroll.+ *+ * One screenful further than wherever the user has travelled, so the thumb+ * always has somewhere left to go — see the file header for why this is a+ * claim about size only, never about position.+ */+export function appScroll(back: number, rows: number): PaneScroll {+ const travelled = Math.max(0, back);+ return { span: travelled + rows, back: travelled, rows };+}++/** Is there anywhere for this pane to scroll to? */+export function scrollable(scroll: PaneScroll | null): boolean {+ return Boolean(scroll && scroll.span > 0 && scroll.rows > 0);+}++/** Where the thumb sits in a track of `trackPx`, or null when there is no bar. */+export function thumbGeometry(+ scroll: PaneScroll | null,+ trackPx: number,+): ThumbGeometry | null {+ if (!scrollable(scroll) || trackPx <= 0) return null;+ const { span, back, rows } = scroll as PaneScroll;+ const total = span + rows;+ const heightPx = clamp(+ Math.round((trackPx * rows) / total),+ Math.min(MIN_THUMB_PX, trackPx),+ trackPx,+ );+ // 1 is the newest output, at the bottom of the track, where an untouched+ // pane stands.+ const progress = 1 - clamp(back / span, 0, 1);+ return { heightPx, topPx: Math.round((trackPx - heightPx) * progress) };+}++/** How far back a thumb dragged to `topPx` is asking to go, in lines. */+export function backForThumbTop(+ topPx: number,+ trackPx: number,+ scroll: PaneScroll | null,+): number {+ const geometry = thumbGeometry(scroll, trackPx);+ if (!geometry || !scroll) return 0;+ const travel = trackPx - geometry.heightPx;+ if (travel <= 0) return scroll.back;+ const progress = clamp(topPx / travel, 0, 1);+ return Math.round((1 - progress) * scroll.span);+}++/** Whole wheel notches that carry an application `lines` towards older output. */+export function notchesForLines(lines: number): number {+ return Math.trunc(lines / LINES_PER_NOTCH);+}diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.pyindex a420a810c0..d55f92d60d 100644--- a/jarvis/voice/action_phrases.py+++ b/jarvis/voice/action_phrases.py@@ -398,52 +398,6 @@ _PHRASES: dict[str, dict[str, str]] = {"en": "I opened {folder}: {names}.","es": "Abrí {folder}: {names}.",},- # A call-sign the transcript almost matched. Both variants REPEAT what was- # heard: the user's own word is the only thing that lets them tell a- # misheard name from a wrong pane, and hearing "I understood Ilies" is what- # makes "no, Ellis" the obvious next thing to say.- "ide_terminal_clarify_one": {- "de": "Ich habe {spoken} verstanden — meinst du {name}?", # i18n-allow- "en": "I heard {spoken} — did you mean {name}?",- "es": "Entendí {spoken}: ¿te refieres a {name}?",- },- "ide_terminal_clarify_many": {- "de": "Ich habe {spoken} verstanden — meinst du {names}?", # i18n-allow- "en": "I heard {spoken} — did you mean {names}?",- "es": "Entendí {spoken}: ¿te refieres a {names}?",- },- # The separator for the final pair of an alternative list ("Maggie or Max").- # A phrase entry rather than a literal, so the choice is offered in the- # turn's language like every other spoken word.- "join_or": {- "de": " oder ", # i18n-allow- "en": " or ",- "es": " o ",- },- # The separator for the final pair of a LIST ("Alex and Blake"). Distinct- # from ``join_or`` because the two questions mean opposite things: "Max or- # Maggie" offers a choice between panes, "Alex and Blake" asks about both.- "join_and": {- "de": " und ", # i18n-allow- "en": " and ",- "es": " y ",- },- # Panes were briefed AND one call-sign of the same breath stayed unclear.- # The two halves are said in one sentence on purpose: the user has to hear- # which agents actually got the work before being asked about the rest.- "ide_terminal_clarify_also": {- "de": "Ich habe außerdem {spoken} verstanden — meinst du {names}?", # i18n-allow- "en": "I also heard {spoken} — did you mean {names}?",- "es": "También entendí {spoken}: ¿te refieres a {names}?",- },- # The user addressed several panes and only one call-sign survived speech- # recognition. Saying which one was placed is the load-bearing half: it is- # what stops the user believing a second agent is working when none is.- "ide_terminal_who_else": {- "de": "Ich konnte nur {names} zuordnen — wer sollte noch ran?", # i18n-allow- "en": "I could only place {names} — who else did you mean?",- "es": "Solo pude identificar a {names}: ¿quién más?",- },"ide_terminals_nowhere": {"de": ( # i18n-allow"Es ist kein Workspace offen und ich habe keinen letzten. " # i18n-allowdiff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.pyindex 7e4c18f296..efbe4ab950 100644--- a/jarvis/workspace/agents.py+++ b/jarvis/workspace/agents.py@@ -29,9 +29,7 @@ rather than handing the PTY an argv that cannot start.from __future__ import annotationsimport logging-from collections.abc import Callable, Mapping-from dataclasses import dataclass, field-from typing import Any, Literal+from dataclasses import dataclassfrom jarvis.clis.prober import CliStatusProberfrom jarvis.clis.spec import AuthConfig, CliSpec, InstallMethods, RiskConfig@@ -43,15 +41,6 @@ log = logging.getLogger(__name__)# "2.1.195 (Claude Code)" and "codex-cli 0.142.3"._SEMVER_RE = r"(\d+\.\d+\.\d+)"-# The same, with the patch component optional. Not every CLI ships three parts:-# the Python-generation Kimi answers ``kimi, version 1.3``, which the strict-# pattern above misses entirely — and a missed version is not a cosmetic loss.-# It reads downstream as ``version=None``, which the wizard and the resume offer-# render as a blank field next to an installed binary, i.e. exactly what a-# broken install looks like. Entries whose CLI numbers itself in two parts opt-# into this instead.-_LOOSE_SEMVER_RE = r"(\d+\.\d+(?:\.\d+)?)"-# The registry key of the plain-shell entry. A name rather than a literal# everywhere, because several layers (the IDE session registry, the pane split# menu, the tests) have to agree on it.@@ -174,28 +163,9 @@ def register_agent(agent: WorkspaceAgent, *, replace: bool = False) -> Workspaceif agent.name in _AGENTS and not replace:raise ValueError(f"A workspace agent called {agent.name!r} is already registered.")_AGENTS[agent.name] = agent- _forget_command_catalog()return agent-def _forget_command_catalog() -> None:- """Drop the cached command catalog, which spells this registry out.-- The voice/LLM schema for "open a pane running X" lists the registered- coding CLIs by name, and that catalog is built once and cached. An agent- registered after the first build would therefore be openable from the UI,- resumable, promptable — and invisible to the one surface meant to drive it.- Never raises: the catalog is optional to this module, and a registration- that fails because of it would be the worse outcome.- """- try:- from jarvis.commands.registry import get_registry-- get_registry.cache_clear()- except Exception: # noqa: BLE001 - the catalog is not this module's job- return--def list_agents() -> list[WorkspaceAgent]:"""Every registered entry, in registration order."""return list(_AGENTS.values())diff --git a/tests/unit/agentic_ide/test_clarify.py b/tests/unit/agentic_ide/test_clarify.pydeleted file mode 100644index 884f12ca46..0000000000--- a/tests/unit/agentic_ide/test_clarify.py+++ /dev/null@@ -1,351 +0,0 @@-"""A misheard call-sign must ask, and only ever ask about the workspace.--Two live failures of 2026-07-27 meet in this module, and they pull in opposite-directions — which is why the cases below are written as two lists that must-BOTH hold, rather than as one threshold:--* the pane "Ellis" came back from speech recognition as "Ilies" and the- addressed-terminal path stood down in silence, so nothing was typed anywhere- and the live model claimed an agent was working;-* ordinary speech reaches the same pool from the other side ("allen" scores- 0.750 against "Alex", above the acting threshold), so a sentence about the- outside world must never be typed into somebody's coding agent.--The maintainer's own examples are pinned verbatim, including the counter-example-("what is Elon Musk up to?") — they are the specification.-"""--from __future__ import annotations--import pytest--from jarvis.agentic_ide import intent-from jarvis.agentic_ide.clarify import (- ClarificationWindow,- addresses_workspace,- detect_clarification,- is_outside_world_talk,-)--PANES = ["Alex", "Blake", "Casey", "Dana", "Ellis", "Finn"]---def _outcome(text: str, names: list[str] | None = None) -> str:- """What the workspace does with this turn: act, ask, or stay out of it.-- Deliberately routed through BOTH detectors in the order the brain calls- them. A case that acts must not also ask, and a case that neither acts nor- asks must be silent for a reason — the three outcomes are only meaningful- together.- """- panes = names or PANES- if intent.detect_all(text, names=panes):- return "act"- return "ask" if detect_clarification(text, names=panes) else "silent"---# --------------------------------------------------------------------------- #-# A turn addresses a FLEET (live 2026-07-27 19:07) #-# --------------------------------------------------------------------------- #---def test_a_garbled_name_beside_a_certain_one_is_still_asked_about() -> None:- """The 19:07 failure: two panes addressed, one briefed, one dropped silent.-- A certainly-named pane used to end the search, so the second addressee —- whose call-sign speech recognition had mangled — produced no action and no- question. The user heard that Alex was working and believed both were.- """- need = detect_clarification(- "Alex und Blaike sollen beide einen Deep Dive machen", names=PANES- )- assert need is not None, "the second addressee must not vanish"- assert need.certain == ("Alex",), "the pane that WAS understood is carried"- assert need.candidates == ("Blake",)- assert need.spoken == "Blaike"---def test_two_garbled_names_in_one_list_both_get_asked_about() -> None:- """"Alexa und Blaike" is one instruction for two agents, not noise."""- need = detect_clarification(- "Alexa und Blaike sollen beide einen Deep Dive machen", names=PANES- )- assert need is not None- assert [item.spoken for item in need.uncertain] == ["Alexa", "Blaike"]- assert need.offered == ("Alex", "Blake")-- window = ClarificationWindow()- window.arm(need)- # ONE "yes" confirms the whole list — that is the point of asking once.- assert window.resolve_answer("ja") == (("Alex", "Blake"), need.utterance)---def test_naming_both_panes_answers_for_both() -> None:- need = detect_clarification(- "Alexa und Blaike sollen beide einen Deep Dive machen", names=PANES- )- assert need is not None- window = ClarificationWindow()- window.arm(need)- resolved = window.resolve_answer("Alex and Blake")- assert resolved is not None- assert resolved[0] == ("Alex", "Blake")---def test_a_stray_near_miss_beside_a_working_turn_stays_silent() -> None:- """The cost of the change must not be a question on every good turn.-- "Alex" is certain and the sentence works; "Kannst" scores against "Casey"- without being listed beside anything, so it is noise and must not produce- a question the user then has to say "no" to.- """- need = detect_clarification(- "Alex soll bitte die Tests reparieren, Kannst das laufen", names=PANES- )- assert need is None---# --------------------------------------------------------------------------- #-# The live failure #-# --------------------------------------------------------------------------- #---def test_the_live_transcript_asks_instead_of_going_silent() -> None:- """The 2026-07-27 16:18 turn, verbatim from the session transcript."""- spoken = (- "kannst du bitte Ilies ein Deep Dive machen lassen und sie soll "- "gucken, wieso wenn man aus dem Agentic IDE Mode rausgeht"- )- need = detect_clarification(spoken, names=PANES)- assert need is not None, "the turn that started this must not be silent"- assert need.candidates == ("Ellis",)- assert need.spoken == "Ilies"- # The ORIGINAL wording is carried, because it holds the actual task.- assert need.utterance == spoken---def test_the_answer_delivers_the_original_task() -> None:- """A question is only worth asking if "yes" still does the work."""- window = ClarificationWindow()- spoken = "kannst du bitte Ilies das Deep Dive machen lassen"- need = detect_clarification(spoken, names=PANES)- assert need is not None- window.arm(need)-- assert window.resolve_answer("ja") == (("Ellis",), spoken)- # One question, one answer: the window is spent.- assert not window.armed- assert window.resolve_answer("ja") is None---def test_naming_the_pane_answers_even_with_several_offered() -> None:- """"Maggie" decides what a bare "yes" cannot."""- window = ClarificationWindow()- panes = ["Alex", "Max", "Maggie"]- need = detect_clarification("Kannst du bitte Mags prompten?", names=panes)- assert need is not None- assert set(need.candidates) == {"Max", "Maggie"}- window.arm(need)-- resolved = window.resolve_answer("Maggie")- assert resolved is not None- assert resolved[0] == ("Maggie",)---def test_a_bare_yes_cannot_choose_between_two_panes() -> None:- window = ClarificationWindow()- need = detect_clarification(- "Kannst du bitte Mags prompten?", names=["Alex", "Max", "Maggie"]- )- assert need is not None- window.arm(need)- assert window.resolve_answer("ja") is None---def test_a_declined_question_delivers_nothing() -> None:- window = ClarificationWindow()- need = detect_clarification("Kannst du bitte Ilies prompten?", names=PANES)- assert need is not None- window.arm(need)- assert window.resolve_answer("nein") is None- assert not window.armed---def test_moving_on_closes_the_question_instead_of_answering_it() -> None:- """A full sentence is the user moving on, not an answer."""- window = ClarificationWindow()- need = detect_clarification("Kannst du bitte Ilies prompten?", names=PANES)- assert need is not None- window.arm(need)- assert (- window.resolve_answer(- "ach lass mal, erzähl mir lieber wie das Wetter morgen wird"- )- is None- )- assert not window.armed---def test_a_stale_question_never_delivers_work() -> None:- window = ClarificationWindow()- need = detect_clarification("Kannst du bitte Ilies prompten?", names=PANES)- assert need is not None- window.arm(need, now=0.0)- assert window.resolve_answer("ja", now=10_000.0) is None---# --------------------------------------------------------------------------- #-# The maintainer's specification (2026-07-27) #-# --------------------------------------------------------------------------- #--# "If I only say a first name that could be roughly the same, it should check-# that I mean the right one."-ASKS = [- ("kannst du bitte Ilies ein Deep Dive machen lassen", None),- ("Ilies soll mal einen Deep Dive machen", None),- ("Kannst du bitte Mags prompten?", ["Alex", "Max", "Maggie"]),- ("Dena soll die Tests fixen", None),- ("Kannst du Ellice beauftragen, den Bug zu fixen", None),-]--# "But not, for example: 'can you tell me what Elon Musk is doing right now?'-# … and then it prompts everyone. That must of course not happen."-STAYS_OUT = [- "Kannst du bitte mir sagen, was Elon Musk gerade macht?",- "Sag mir was Elon Musk gerade macht",- "Was macht Elon gerade?",- "Wer ist Elon Musk?",- "kannst du mir sagen was Barack Obama gerade macht",- "Erzähl mir was über Elias Canetti",- "wie ist das Wetter heute",- "kannst du bitte den Bug fixen",- "mach mal einen Deep Dive in den Code",- "Ilies ist ein schöner Name",- "schick das an Alexander Müller weiter",- "lass die Tests laufen und fixe die Fehler",- "Das soll man mal fixen",-]--[email protected](("spoken", "panes"), ASKS)-def test_an_uncertain_call_sign_asks(spoken: str, panes: list[str] | None) -> None:- assert _outcome(spoken, panes) == "ask", spoken--[email protected]("spoken", STAYS_OUT)-def test_the_outside_world_never_reaches_a_pane(spoken: str) -> None:- assert _outcome(spoken) == "silent", spoken---# --------------------------------------------------------------------------- #-# Certainty still acts — asking must not become the new normal #-# --------------------------------------------------------------------------- #--ACTS = [- "sag Ellis, sie soll die Tests fixen",- # Same sound, different spelling: certain, and therefore acted on. This is- # the gap the canonicalization in ``intent`` closed — the templates are- # built from the exact spelling and used to match none of these.- "Sag Elis, sie soll die Tests fixen",- "beauftrage Ellys mit dem Bug",- "Kannst du Elliss beauftragen, den Bug zu fixen",- "Was macht Ellis gerade?",- "sag allen, sie sollen die Tests fixen",-]--[email protected]("spoken", ACTS)-def test_a_certain_call_sign_is_still_acted_on(spoken: str) -> None:- assert _outcome(spoken) == "act", spoken---def test_a_misheard_collective_address_cannot_brief_the_whole_workspace() -> None:- """The costliest thing a garbled word can do is reach EVERY pane at once."""- assert is_outside_world_talk("sag allen was Elon Musk gerade macht")- assert intent.detect_all(- "sag allen was Elon Musk gerade macht", names=PANES- ) == []- # A genuine collective instruction still reaches everyone.- assert len(intent.detect_all("sag allen, sie sollen aufhören", names=PANES)) == len(- PANES- )---# --------------------------------------------------------------------------- #-# The gate itself #-# --------------------------------------------------------------------------- #--- ("spoken", "expected"),- [- ("Kannst du bitte Max prompten?", True),- ("beauftrage Max mit dem Bug", True),- ("sag Max, er soll die Tests fixen", True),- ("Max soll die Tests fixen", True),- # A handover verb and a name and nothing else is NOT workspace evidence.- ("Sag mir was Elon Musk gerade macht", False),- ("wie ist das Wetter", False),- ],-)-def test_workspace_gate(spoken: str, expected: bool) -> None:- assert addresses_workspace(spoken) is expected---def test_an_all_lowercase_transcript_still_refuses_function_words() -> None:- """Case cannot rule when the provider capitalizes nothing; stopwords still do."""- need = detect_clarification(- "kannst du bitte den bug fixen lassen", names=PANES- )- assert need is None---# --------------------------------------------------------------------------- #-# Asking a pane for a status report #-# --------------------------------------------------------------------------- #-# The 16:53 half of the same day: "Was hat Dana gemacht?" carries no repo, no-# test, no bug and no branch, so the coding-work pairings never saw it — a-# garbled call-sign inside the single most common workspace question there is-# went silently nowhere.--- "spoken",- [- "Was hat Ellis gemacht?",- "Was macht Ellis gerade?", # i18n-allow: German speech input under test- "Wie weit ist Ellis?", # i18n-allow: German speech input under test- "What has Ellis done?",- "How far is Ellis?",- "Que ha hecho Ellis?",- ],-)-def test_a_status_question_addresses_the_workspace(spoken: str) -> None:- assert addresses_workspace(spoken) is True---def test_a_garbled_call_sign_in_a_status_question_asks() -> None:- """The live 16:53 shape, with the name mangled the way 16:18 mangled it."""- need = detect_clarification("Was hat Ilies gemacht?", names=PANES)- assert need is not None- assert need.candidates == ("Ellis",)- # And the confirmed pane is briefed with the ORIGINAL question, not "yes".- window = ClarificationWindow()- window.arm(need)- assert window.resolve_answer("ja") == (("Ellis",), "Was hat Ilies gemacht?")--- "spoken",- [- # A full personal name turns the identical shape into a question about- # a human being — the surname is the only thing that tells them apart.- "Sag mir was Elon Musk gerade macht",- "Was hat Angela Merkel gemacht?",- ],-)-def test_a_status_question_about_a_person_stays_out_of_the_workspace(- spoken: str,-) -> None:- assert addresses_workspace(spoken) is False- assert _outcome(spoken) == "silent"diff --git a/tests/unit/brain/test_agentic_ide_clarify_fast_path.py b/tests/unit/brain/test_agentic_ide_clarify_fast_path.pydeleted file mode 100644index d705c0f995..0000000000--- a/tests/unit/brain/test_agentic_ide_clarify_fast_path.py+++ /dev/null@@ -1,312 +0,0 @@-"""A call-sign the transcript garbled is asked about, then delivered on.--The live failure of 2026-07-27 16:18, end to end: the pane "Ellis" came back-from speech recognition as "Ilies", scoring just under the acting threshold. The-addressed-terminal path returned ``None`` without a word — no prompt was typed,-nothing was said, and the realtime model, which is never told any of this, filled-the silence by announcing that an agent was on it. The maintainer spent the next-two turns being told a lie.--What this file pins is the whole repaired loop, because each half is worthless-alone:--* an uncertain call-sign produces a QUESTION rather than silence, and types- nothing into any pane while it is unanswered;-* the answer delivers the ORIGINAL sentence — the one that carried the task — so- clarifying costs the user one word instead of repeating themselves;-* a sentence about the outside world still reaches no pane at all, which is the- failure the question must not buy at the price of.-"""-from __future__ import annotations--from pathlib import Path--import pytest--from jarvis.agentic_ide import clarify as ide_clarify-from jarvis.agentic_ide import prompt_composer-from jarvis.agentic_ide import session as session_mod-from jarvis.agentic_ide.prompt_composer import ComposedPrompt-from jarvis.agentic_ide.session import Registry-from jarvis.brain.manager import BrainManager-from jarvis.core.bus import EventBus-from jarvis.core.config import JarvisConfig-from tests.fakes.fake_pty_manager import FakePtyManager--[email protected](autouse=True)-def _isolated_recents(- tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch-) -> None:- """Never rewrite the developer's real recent-workspace list from a test."""- from jarvis.agentic_ide import recents-- store = tmp_path_factory.mktemp("recents") / "recents.json"- monkeypatch.setattr(recents, "_store_path", lambda: store)--[email protected](autouse=True)-def _clean_window() -> None:- """The clarification window is process-wide; no test may inherit one."""- ide_clarify.WINDOW.disarm()- yield- ide_clarify.WINDOW.disarm()---def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:- monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))- reg = Registry(pty_manager=FakePtyManager())- monkeypatch.setattr(session_mod, "get_registry", lambda: reg)- return reg---def manager() -> BrainManager:- cfg = JarvisConfig()- cfg.brain.primary = "fake"- mgr = BrainManager(config=cfg, bus=EventBus(), tools={})- # Pinned so the wording assertions never depend on the host's own locale- # (AP-23: never test against the maintainer's configuration).- mgr._reply_language = "en"- return mgr--[email protected](autouse=True)-def _fake_composer(monkeypatch: pytest.MonkeyPatch) -> list[str]:- """A deterministic stand-in for the quality-tier prompt writer."""- seen: list[str] = []-- async def fake_compose(utterance: str, **kwargs: object) -> ComposedPrompt:- seen.append(str(kwargs.get("instruction") or utterance))- return ComposedPrompt(- text=f"## Task\n{utterance}", files=[], composed_by="llm"- )-- monkeypatch.setattr(prompt_composer, "compose", fake_compose)- return seen---async def _noop(_text: str) -> None:- return None---async def _noop_exit(_code: int) -> None:- return None---async def _open(registry: Registry, folder: Path, count: int) -> list[str]:- """Open ``count`` panes AND bring their agents live; return their call-signs."""- await registry.start(str(folder), [{"agent": "claude"} for _ in range(count)])- assert registry.session is not None- for term in list(registry.session.terminals):- await registry.attach(term.name, 100, 30, _noop, _noop_exit)- return [t.name for t in registry.session.terminals]---def _typed(registry: Registry) -> list[str]:- """Everything the panes were actually sent this test."""- return list(registry._pty.typed) # noqa: SLF001 - the fake's recording surface---def _briefs(registry: Registry) -> list[str]:- """Just the prompts, without the Enter that submits each one."""- return [text for text in _typed(registry) if text.strip()]---# --------------------------------------------------------------------------- #---async def test_a_garbled_call_sign_asks_instead_of_silently_doing_nothing(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- """The regression: 'Ilies' must not vanish into a silent ``None``."""- names = await _open(registry, tmp_path, 5)- assert "Ellis" in names, "the fifth pane of the pool is the one that was misheard"-- reply = await manager._run_agentic_ide_fast_path(- "can you have Ilies do a deep dive and find out why the tests fail"- )-- assert reply is not None, "the turn that started all of this must not be silent"- assert "Ellis" in reply- assert "Ilies" in reply, "the user hears what was understood, not just a guess"- assert ide_clarify.WINDOW.armed---async def test_nothing_is_typed_into_a_pane_while_the_question_is_open(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- """Asking must not also act — that would be guessing with extra steps."""- await _open(registry, tmp_path, 5)-- await manager._run_agentic_ide_fast_path(- "can you have Ilies do a deep dive and find out why the tests fail"- )-- assert _typed(registry) == []---async def test_the_answer_delivers_the_original_task(- manager: BrainManager,- registry: Registry,- tmp_path: Path,- _fake_composer: list[str],-) -> None:- """"Yes" must do the work the FIRST sentence described, not repeat itself."""- await _open(registry, tmp_path, 5)- task = "can you have Ilies do a deep dive and find out why the tests fail"-- question = await manager._run_agentic_ide_fast_path(task)- assert question is not None-- verdict = await manager._run_agentic_ide_fast_path("yes")-- assert verdict is not None- assert "Ellis" in verdict- # The composer saw the original sentence, never the bare confirmation.- assert any("deep dive" in seen for seen in _fake_composer)- assert not any(seen.strip().casefold() == "yes" for seen in _fake_composer)- assert not ide_clarify.WINDOW.armed---async def test_declining_delivers_nothing(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- await _open(registry, tmp_path, 5)- await manager._run_agentic_ide_fast_path(- "can you have Ilies do a deep dive and find out why the tests fail"- )-- assert await manager._run_agentic_ide_fast_path("no") is None- assert _typed(registry) == []- assert not ide_clarify.WINDOW.armed---async def test_a_question_about_the_outside_world_neither_asks_nor_types(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- """The maintainer's counter-example, pinned as a hard negative."""- await _open(registry, tmp_path, 5)-- reply = await manager._run_agentic_ide_fast_path(- "can you tell me what Elon Musk is doing right now?"- )-- assert reply is None- assert _typed(registry) == []- assert not ide_clarify.WINDOW.armed---async def test_a_certain_call_sign_still_acts_without_asking(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- """Clarifying must not become the new normal for names that ARE clear."""- names = await _open(registry, tmp_path, 5)-- reply = await manager._run_agentic_ide_fast_path(- f"tell {names[0]} to fix the failing tests"- )-- assert reply is not None- assert not ide_clarify.WINDOW.armed- assert _typed(registry), "a certain call-sign is delivered, not questioned"---# --------------------------------------------------------------------------- #-# A turn addresses a FLEET (live 2026-07-27 19:07) #-# --------------------------------------------------------------------------- #---async def test_two_garbled_call_signs_are_asked_about_together(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- """Two mangled names in one list used to produce nothing at all.-- The detector stood down above one uncertain word, so "Alexa und Blaike,- macht beide ..." reached neither pane and asked nothing — the silent miss- this whole area exists to end, only for a pair instead of a single pane.- """- await _open(registry, tmp_path, 5)-- reply = await manager._run_agentic_ide_fast_path(- "Alexa and Blaike should both do a deep dive on the failing tests"- )-- assert reply is not None- assert "Alex" in reply and "Blake" in reply- assert _typed(registry) == [], "nothing is typed while the question is open"- assert ide_clarify.WINDOW.armed---async def test_one_yes_briefs_the_whole_addressed_pair(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- """One question, one word, both agents working."""- await _open(registry, tmp_path, 5)- task = "Alexa and Blaike should both do a deep dive on the failing tests"- assert await manager._run_agentic_ide_fast_path(task) is not None-- verdict = await manager._run_agentic_ide_fast_path("yes")-- assert verdict is not None- assert "Alex" in verdict and "Blake" in verdict- assert len(_briefs(registry)) == 2, "both addressees are briefed, not the first"- assert all("deep dive" in text for text in _briefs(registry))---async def test_a_pane_that_was_understood_is_briefed_before_the_question(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- """A name past every threshold ("Dave") must not cost the one that worked.-- The live shape: Alex resolves, "Dave" matches no pane at any threshold, and- the turn said "Alex is on it" while the user was waiting for two agents.- The count the user stated out loud is what survives that, so the work goes- out AND the gap is named in the same breath.- """- await _open(registry, tmp_path, 5)-- reply = await manager._run_agentic_ide_fast_path(- "Alex and Dave should both do a deep dive on the failing tests"- )-- assert reply is not None- assert "Alex" in reply- assert len(_briefs(registry)) == 1, "the pane that WAS understood is briefed"- assert ide_clarify.WINDOW.armed, "and the second addressee is asked about"---async def test_naming_the_missing_pane_delivers_the_original_task(- manager: BrainManager,- registry: Registry,- tmp_path: Path,- _fake_composer: list[str],-) -> None:- """"Blake" answers "who else?" with the work the first sentence carried."""- await _open(registry, tmp_path, 5)- await manager._run_agentic_ide_fast_path(- "Alex and Dave should both do a deep dive on the failing tests"- )-- verdict = await manager._run_agentic_ide_fast_path("Blake")-- assert verdict is not None- assert "Blake" in verdict- assert len(_briefs(registry)) == 2- assert all("deep dive" in text for text in _briefs(registry))---async def test_a_single_addressee_is_never_asked_who_else(- manager: BrainManager, registry: Registry, tmp_path: Path-) -> None:- """The plural check must not tax the ordinary one-pane turn."""- names = await _open(registry, tmp_path, 5)-- reply = await manager._run_agentic_ide_fast_path(- f"tell {names[0]} to do a deep dive on the failing tests"- )-- assert reply is not None- assert not ide_clarify.WINDOW.armed- assert len(_briefs(registry)) == 1diff --git a/tests/unit/commands/test_registry_parity.py b/tests/unit/commands/test_registry_parity.pyindex a5be81624c..14db91f913 100644--- a/tests/unit/commands/test_registry_parity.py+++ b/tests/unit/commands/test_registry_parity.py@@ -137,41 +137,6 @@ def test_brain_switch_enum_excludes_subagent_only_providers() -> None:assert "antigravity" not in enum-def test_spawn_agent_enum_follows_the_agent_registry() -> None:- """A newly registered coding CLI must be spawnable by voice the same day.-- The enum used to be the literal ``["claude", "codex"]`` in two schemas, so- an agent added to ``jarvis.workspace.agents`` opened from the UI, resumed- and accepted prompts while being absent from the one surface meant to drive- it. Registering one now invalidates the cached catalog.- """- from jarvis.commands.registry import get_registry as catalog- from jarvis.workspace import agents as workspace_agents-- def spawn_enum() -> list[str]:- cmd = get_command("agentic-ide-spawn-terminals")- assert cmd is not None- return list(cmd.params["properties"]["agent"].get("enum") or [])-- assert set(spawn_enum()) == set(workspace_agents.coding_agent_names())-- added = workspace_agents.make_cli_agent(- "test-cli", "Test CLI", binary="test-cli"- )- try:- workspace_agents.register_agent(added)- assert "test-cli" in spawn_enum()- fanout = get_command("agentic-ide-fanout")- assert fanout is not None- group = fanout.params["properties"]["spawn"]["items"]["properties"]["agent"]- assert "test-cli" in (group.get("enum") or [])- finally:- workspace_agents._AGENTS.pop("test-cli", None) # noqa: SLF001 - test cleanup- catalog.cache_clear()-- assert "test-cli" not in spawn_enum()--def test_registry_served_over_rest() -> None:from jarvis.core.bus import EventBusfrom jarvis.core.config import JarvisConfig