Skip to content

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.

@ test(agentic-ide): drop the assertion the movement rewrite left behind

Ruben Lütkea093d3a2de36
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index c75f426c94..d6a695f143 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -201,12 +201,6 @@ def _unavailable(agent: str) -> str:
# Nobody reaches 100 deliberately; anyone who mistypes their way past it gets a
# sentence instead of a frozen desktop.
MAX_TERMINALS = 100
-# How long a pane's call-sign may be. Half the workspace tab's 80, and for a
-# different reason: a workspace name is read, a call-sign is SAID — it is how a
-# user addresses one agent among several out loud, and it also has to fit in a
-# pane header that may be a quarter of a screen wide. Long enough for "Frontend
-# rewrite", short enough that it stays a name rather than a description.
-MAX_TERMINAL_NAME = 40
# Where a pane may land when it is dragged onto another one, in the same two
# axes the grid is built from (columns of stacked panes). "swap" is listed first
# because it is the one a user reaches for most: two panes are the wrong way
@@ -781,17 +775,17 @@ class Terminal:
agent: str # "claude" | "codex"
display_name: str # "Claude Code"
index: int
- # Stable for THIS pane's lifetime and deliberately unrelated to its visible
- # call-sign. A closed T1 and a new T1 are different panes; a renamed T1 is
- # still the same pane. Prompt-history files use this id to preserve exactly
- # that boundary across app restarts.
- history_id: str = field(default_factory=lambda: uuid4().hex)
# Where the pane sits in the grid, on TWO axes: the workspace is a
# left-to-right list of columns, and each column is a top-to-bottom stack.
# "Split right" opens a new column beside the anchor; "split down" adds a
# pane to the anchor's OWN column and leaves every other column alone.
#
# The second axis is load-bearing. With only a row number, "split down"
+ # Stable for THIS pane's lifetime and deliberately unrelated to its visible
+ # call-sign. A closed T1 and a new T1 are different panes; a renamed T1 is
+ # still the same pane. Prompt-history files use this id to preserve exactly
+ # that boundary across app restarts.
+ history_id: str = field(default_factory=lambda: uuid4().hex)
# could only mean "open a new row", and a row is window-wide by definition —
# so splitting one pane squashed every other pane to half height. A full
# split TREE (arbitrary nesting, draggable separators) is still deliberately
@@ -825,18 +819,18 @@ class Terminal:
last_input_at: float | None = None
prompts_sent: int = 0
last_prompt: str = ""
- # The current process's records are kept as a fallback if the local history
- # file cannot be written. The full durable history is loaded only when its
- # UI is opened, never in the workspace-state hot path.
- prompt_records: list[prompt_history.PromptHistoryEntry] = field(
- default_factory=list, repr=False, compare=False
- )
# When the last prompt was handed to this pane, as a wall-clock timestamp.
#
# The receipt the user is shown is built from THIS rather than from the
# terminal stream, and that is the whole point. A pane proves a prompt
# arrived by echoing it, which requires a chain of things to have gone
# right at one particular moment: the pane on screen, its output un-parked,
+ # The current process's records are kept as a fallback if the local history
+ # file cannot be written. The full durable history is loaded only when its
+ # UI is opened, never in the workspace-state hot path.
+ prompt_records: list[prompt_history.PromptHistoryEntry] = field(
+ default_factory=list, repr=False, compare=False
+ )
# its socket up, the emulator painted. Every link in that chain has failed
# in production at least once, and each failure looks identical from the
# user's chair — Jarvis says it sent the brief and the pane shows nothing,
@@ -1066,13 +1060,13 @@ class Terminal:
key=self.key,
name=self.name,
agent=self.agent,
- history_id=self.history_id,
column=self.column,
slot=self.slot,
resume=self.resume,
prompts_sent=self.prompts_sent,
account=self.account,
continuation_needed=self.resume_continuation_needed,
+ history_id=self.history_id,
)
@@ -1110,24 +1104,12 @@ class Session:
restored_from: str = ""
def find(self, wanted: str) -> Terminal | None:
- """Terminal by call-sign, key, or a spoken phrase containing one.
-
- Call-signs are tried across EVERY pane before any key is, and that
- order is load-bearing once panes can be renamed. A pane keeps the key
- it was opened with (it is what the running pseudo-terminal is filed
- under), so renaming T1 to "Frontend" leaves a pane whose key is still
- ``t1`` — and the next pane opened is free to take the call-sign T1.
- Asking about keys first would then hand "T1" to the pane the user
- renamed precisely so it would stop being T1.
- """
+ """Terminal by key, call-sign, or a spoken phrase containing one."""
if not wanted:
return None
key = normalize(wanted)
for term in self.terminals:
- if normalize(term.name) == key:
- return term
- for term in self.terminals:
- if normalize(term.key) == key:
+ if normalize(term.key) == key or normalize(term.name) == key:
return term
matched = resolve(wanted, [t.name for t in self.terminals])
if matched is None:
@@ -1827,7 +1809,6 @@ class Registry:
agent=entry.agent,
display_name=agent_display(entry.agent),
index=index,
- history_id=entry.history_id or uuid4().hex,
column=entry.column,
slot=entry.slot,
resume=entry.resume,
@@ -1846,6 +1827,7 @@ class Registry:
#
# **The bug this fixes.** `continuation_pending` used to be raised in
# `attach`, which is the moment a pane's process is spawned — and cold
+ history_id=entry.history_id or uuid4().hex,
# starts are deliberately staggered (see COLD_START_LIMIT), so in a
# workspace of a dozen panes most of them are still `pending` seconds
# after the grid appears. Anybody pressing "Continue" in that window got
@@ -2278,11 +2260,6 @@ class Registry:
progress every time somebody looked away, which is precisely what having
several workspaces would otherwise cost.
- A replay is valid only at the geometry that produced its cursor moves.
- When the viewer comes back at another size, the old drawing is replaced
- by its terminal-mode prologue and a live repaint. This is still the same
- process and conversation; only the stale pixels are discarded.
-
**That replay goes out on ``on_replay``, not on ``on_output``, because a
viewer has to CLEAR its screen before drawing it.** The two are the same
bytes and completely different instructions: live output continues a
@@ -2336,40 +2313,25 @@ class Registry:
_watch(term, on_output, on_exit)
term.reattached = True
term.stopping = False
- geometry_changed = (term.transcript.cols, term.transcript.rows) != (
- cols,
- rows,
- )
- if geometry_changed:
- geometry_changed = manager.resize(term.pty_id, cols, rows)
- if geometry_changed:
- term.transcript.resize(cols, rows)
- needs_repaint = term.replay.truncated
- if geometry_changed and is_coding_agent(term.agent):
- # A cursor-addressed TUI stream is meaningful only at the size
- # that produced it. Replaying the old geometry after a grid
- # re-layout leaves status rows and command fragments behind
- # the new paint. Keep the terminal modes, drop those drawing
- # bytes, and let the live agent rebuild one clean screen below.
- replay = term.replay.rebase_for_resize()
- needs_repaint = True
- else:
- replay = term.replay.text()
+ term.transcript.resize(cols, rows)
+ manager.resize(term.pty_id, cols, rows)
+ replay = term.replay.text()
if replay:
- # Hand over either the stream that drew the current screen, or
- # (after a geometry change) the terminal-mode prologue that a
- # clean repaint must draw on. A coding agent's TUI is a painted
- # surface, not a log: the viewer needs one of those two rebuild
- # paths rather than an append to whatever it held before.
+ # Hand over the raw stream that drew the current screen. A
+ # coding agent's TUI is a painted surface, not a log: without
+ # this the pane comes back blank until the agent happens to
+ # repaint, which looks exactly like a dead terminal.
#
# On the replay channel when the viewer offered one — see the
# docstring for what appending it to a screen that already had
# a copy of it looked like.
await (on_replay or on_output)(replay)
- if needs_repaint:
- # Either the tail lost its opening frame, or its cursor moves
- # belong to another geometry. Neither can rebuild this viewer.
- # Ask for a fresh paint instead of hoping one arrives.
+ if term.replay.truncated:
+ # The tail is all this pane has, and it no longer starts where
+ # the agent started drawing. Replaying it alone brings back the
+ # one row the agent rewrote last and empty space where its
+ # prompt box should be — see ReplayBuffer's docstring. Ask for
+ # a fresh paint instead of hoping one arrives.
await self._nudge_repaint(term, cols, rows)
logger.debug("Agentic IDE: {} re-joined a running agent", term.name)
return term
@@ -2881,17 +2843,8 @@ class Registry:
return False
# The replayed screen has to follow the real one; otherwise the
# transcript keeps wrapping at the old width.
- if (term.transcript.cols, term.transcript.rows) == (cols, rows):
- return True
- if not self._manager().resize(term.pty_id, cols, rows):
- return False
- if is_coding_agent(term.agent):
- # Future viewers must not replay cursor moves produced for the old
- # grid into the new one. The live viewer already has its screen;
- # this only starts a clean replay epoch for the next reconnect.
- term.replay.rebase_for_resize()
term.transcript.resize(cols, rows)
- return True
+ return self._manager().resize(term.pty_id, cols, rows)
def detach(self, key: str, workspace_id: str | None = None, viewer: Any = None) -> None:
"""Let go of a pane's viewer. The agent behind it keeps running.
@@ -3194,60 +3147,6 @@ class Registry:
)
return moved
- async def rename_terminal(self, wanted: str, name: str) -> tuple[Session, Terminal]:
- """Give one pane a new call-sign, without touching what runs in it.
-
- The pane's own identity as far as its RUNNING agent is concerned is its
- key, not its call-sign: the pseudo-terminal is filed under the key, and
- the key is deliberately left alone here. So renaming is exactly what a
- user expects it to be — the label changes, the agent keeps working, its
- conversation and scrollback are untouched. The viewer reconnects (it
- addresses the pane by call-sign) and repaints from the transcript,
- which is the same path a workspace switch already takes.
-
- The new call-sign has to be usable as ONE, which is what the checks are
- about: a name nobody can say is a pane nobody can send work to.
-
- * It must contain something to compare — ``normalize`` keeps letters
- and digits only, so a name of pure punctuation would leave the pane
- addressable by nothing at all.
- * It must be free within THIS workspace, the scope a call-sign lives
- in. Two panes answering to one name make every spoken instruction a
- coin flip over which agent gets the work.
-
- Searching every open workspace rather than only the front one, because
- a custom call-sign is exactly what somebody gives a pane so they can
- address it from anywhere — including to rename it.
- """
- cleaned = " ".join(name.split()).strip()
- if not cleaned:
- raise SessionError("Give the terminal a name.")
- if len(cleaned) > MAX_TERMINAL_NAME:
- raise SessionError(
- f"Terminal names can be at most {MAX_TERMINAL_NAME} characters."
- )
- if not normalize(cleaned):
- raise SessionError("Give the terminal a name with letters or numbers in it.")
- async with self._lock:
- found = self.find_terminal(wanted)
- if found is None:
- raise self._unknown_terminal(wanted)
- session, term = found
- if term.name == cleaned:
- return session, term
- if any(
- other is not term and normalize(other.name) == normalize(cleaned)
- for other in session.terminals
- ):
- raise SessionError(
- f"Another terminal in this workspace is already called {cleaned!r}."
- )
- previous = term.name
- term.name = cleaned
- await self._persist()
- logger.info("Agentic IDE: renamed terminal {} to {}", previous, cleaned)
- return session, term
-
async def close_terminal(self, wanted: str) -> Terminal:
"""Stop one terminal's agent and remove its pane from the workspace."""
closed, failed = await self.close_terminals([wanted])
@@ -3439,25 +3338,6 @@ class Registry:
term.last_submit_at = term.last_prompt_at
term.submitted = submitted
term.sent_multiline = multiline and submitted is True
- history_entry = prompt_history.PromptHistoryEntry(
- id=uuid4().hex,
- sequence=term.prompts_sent,
- text=payload,
- at=term.last_prompt_at,
- submitted=submitted,
- )
- # Memory first: even a read-only or temporarily unavailable data folder
- # must not make a prompt disappear from the history while the pane is
- # still open. Disk is the persistence layer, not the only copy.
- term.prompt_records.append(history_entry)
- try:
- await asyncio.to_thread(prompt_history.append, term.history_id, history_entry)
- except OSError as exc:
- logger.warning(
- "Agentic IDE: could not persist the prompt history for {}: {}",
- term.name,
- exc,
- )
# Somebody is driving this pane again, whatever the prompt said. Cleared
# even when the pane did not submit the text: the instruction is sitting
# in its input box in full, so offering to type "continue" behind it
@@ -3538,6 +3418,25 @@ class Registry:
)
return None
return left_the_box
+ history_entry = prompt_history.PromptHistoryEntry(
+ id=uuid4().hex,
+ sequence=term.prompts_sent,
+ text=payload,
+ at=term.last_prompt_at,
+ submitted=submitted,
+ )
+ # Memory first: even a read-only or temporarily unavailable data folder
+ # must not make a prompt disappear from the history while the pane is
+ # still open. Disk is the persistence layer, not the only copy.
+ term.prompt_records.append(history_entry)
+ try:
+ await asyncio.to_thread(prompt_history.append, term.history_id, history_entry)
+ except OSError as exc:
+ logger.warning(
+ "Agentic IDE: could not persist the prompt history for {}: {}",
+ term.name,
+ exc,
+ )
async def _await_arrival(self, term: Terminal, payload: str) -> bool:
"""Wait until the pane visibly holds ``payload``, or give up.
diff --git a/jarvis/agentic_ide/transcript.py b/jarvis/agentic_ide/transcript.py
index 964c8c58ed..cf4139f9a1 100644
--- a/jarvis/agentic_ide/transcript.py
+++ b/jarvis/agentic_ide/transcript.py
@@ -278,29 +278,6 @@ class ReplayBuffer:
text = text[remnant.end() :]
return self._mode_prologue() + "\x1b[0m" + text
- def rebase_for_resize(self) -> str:
- """Forget drawing bytes tied to the old geometry, preserving modes.
-
- Cursor-addressed TUI output only has meaning at the terminal size that
- produced it. Replaying that stream into a differently sized viewer
- leaves old status rows and fragments between the newly painted ones.
- A resize therefore starts a new replay epoch: the caller sends this
- returned prologue to a reset viewer, then asks the live TUI to repaint.
-
- Private modes survive because most coding CLIs negotiate alternate
- screen and mouse tracking only once, at process startup. Dropping
- those together with the stale drawing would repair the text while
- silently breaking the pane's mouse and scrollbar.
- """
- prologue = self._mode_prologue() + "\x1b[0m"
- self._chunks.clear()
- self._size = 0
- self.truncated = False
- self._open_escape = False
- self._chunks.append(prologue)
- self._size = len(prologue)
- return prologue
-
def clear(self) -> None:
"""Forget everything — this buffer is being handed to a fresh process.
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index e279368d04..ebc64088fb 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -31,7 +31,6 @@ Endpoints (prefix ``/api/agentic-ide``):
* ``POST /fanout`` → run ONE task across several agents
(open the panes, divide the work, brief each one, report who was reached)
* ``GET /terminals/{name}/report`` → what one named terminal is doing
-* ``PATCH /terminals/{name}`` → give that pane another call-sign
* ``POST /terminals/{name}/prompt`` → type a prompt into it and press Enter
* ``POST /terminals/{name}/attach`` → drop/paste files onto a pane
* ``WS /pty/{name}`` → the pane's live terminal stream
@@ -66,9 +65,9 @@ from jarvis.agentic_ide import (
interrupted,
native_picker,
notifications,
- prompt_history,
recap_engine,
recents,
+ prompt_history,
resume_store,
)
from jarvis.agentic_ide.agent_sessions import has_conversation
@@ -83,7 +82,6 @@ from jarvis.agentic_ide.names import default_names
from jarvis.agentic_ide.session import (
AGENT_DISPLAY,
MAX_PROMPT_CHARS,
- MAX_TERMINAL_NAME,
MAX_TERMINALS,
MAX_WORKSPACES,
Session,
@@ -319,19 +317,6 @@ class RenameWorkspaceRequest(BaseModel):
)
-class RenameTerminalRequest(BaseModel):
- """A new call-sign for one pane."""
-
- name: str = Field(
- min_length=1,
- max_length=MAX_TERMINAL_NAME,
- description=(
- "New call-sign for the pane. The agent running in it is not touched — "
- "only the name it is addressed by changes."
- ),
- )
-
-
class WorkspaceCard(BaseModel):
"""One open workspace, as the workspace bar shows it."""
@@ -918,6 +903,22 @@ class LastPrompt(BaseModel):
prompts_sent: int = Field(default=0, description="How many prompts this pane has been sent.")
+class RecapEdit(BaseModel):
+ """A recap the user is writing for one pane themselves."""
+
+ recap: str = Field(
+ description=(
+ "The header line. Empty clears a hand-written recap and hands the "
+ "pane back to the automatic one."
+ ),
+ max_length=recap_engine.MAX_EDIT_HEADLINE * 4,
+ )
+ recap_detail: str = Field(
+ default="",
+ description="The longer version behind it. Optional; the header line stands alone.",
+ max_length=recap_engine.MAX_EDIT_DETAIL * 2,
+ )
+
class PromptHistoryItem(BaseModel):
"""One exact prompt in a pane's delivery history."""
@@ -946,22 +947,6 @@ class PromptHistoryResponse(BaseModel):
items: list[PromptHistoryItem] = Field(default_factory=list)
-class RecapEdit(BaseModel):
- """A recap the user is writing for one pane themselves."""
-
- recap: str = Field(
- description=(
- "The header line. Empty clears a hand-written recap and hands the "
- "pane back to the automatic one."
- ),
- max_length=recap_engine.MAX_EDIT_HEADLINE * 4,
- )
- recap_detail: str = Field(
- default="",
- description="The longer version behind it. Optional; the header line stands alone.",
- max_length=recap_engine.MAX_EDIT_DETAIL * 2,
- )
-
# --------------------------------------------------------------------------- #
# REST #
@@ -1869,34 +1854,6 @@ async def close_terminals_by_agent(request: Request, agent: str) -> dict:
}
[email protected]("/terminals/{name}", summary="Rename one terminal")
-async def rename_terminal(name: str, req: RenameTerminalRequest) -> dict:
- """Give the pane ``name`` another call-sign.
-
- Nothing is started, stopped or restarted: the agent in the pane keeps
- working and keeps its conversation. Only the name it is addressed by
- changes — on screen, in a spoken instruction, and in every route that takes
- a ``{name}``.
-
- ``404`` when no pane answers to ``name``, ``409`` when another pane in the
- same workspace already carries the new one.
- """
- try:
- session, term = await get_registry().rename_terminal(name, req.name)
- except SessionError as exc:
- message = str(exc)
- status = 409 if "already called" in message else 404
- raise HTTPException(status_code=status, detail=message) from exc
- return {
- "ok": True,
- "renamed": term.name,
- "previous": name,
- "terminal": term.to_dict(),
- "workspace_id": session.id,
- "state": get_registry().state(),
- }
-
-
@router.delete(
"/terminals/{name}",
summary="Close one terminal",
@@ -2090,43 +2047,6 @@ async def get_last_prompt(name: str, workspace_id: str | None = None) -> LastPro
)
- "/terminals/{name}/prompts",
- response_model=PromptHistoryResponse,
- summary="Every prompt sent to one terminal",
-)
-async def get_prompt_history(
- name: str, workspace_id: str | None = None
-) -> PromptHistoryResponse:
- """Read every exact prompt handed to this pane, newest first.
-
- Prompt bodies live outside the workspace snapshot and are loaded only for
- this request. That keeps the IDE's state poll and first-screen restore small
- even when a workspace has many panes with long coding briefs.
- """
- term, _session = _pane_for_recap(name, workspace_id)
- stored = await asyncio.to_thread(prompt_history.load, term.history_id)
- entries = prompt_history.merged(stored, term.prompt_records)
- total = max(term.prompts_sent, len(entries))
- return PromptHistoryResponse(
- name=term.name,
- total=total,
- available=len(entries),
- complete=len(entries) >= term.prompts_sent,
- items=[
- PromptHistoryItem(
- id=entry.id,
- sequence=entry.sequence,
- text=entry.text,
- chars=len(entry.text),
- at=entry.at,
- submitted=entry.submitted,
- )
- for entry in reversed(entries)
- ],
- )
-
-
@router.get("/terminals/{name}/report", summary="What one terminal is doing")
async def terminal_report(name: str, lines: int = 40) -> dict:
"""Status plus the recent readable output of the terminal called ``name``."""
@@ -2171,6 +2091,43 @@ async def terminal_attach(
which is what makes dropping a screenshot work against an agent that
cannot open one.
* ``deliver=false`` stores and analyses without typing anything into the
+ "/terminals/{name}/prompts",
+ response_model=PromptHistoryResponse,
+ summary="Every prompt sent to one terminal",
+)
+async def get_prompt_history(
+ name: str, workspace_id: str | None = None
+) -> PromptHistoryResponse:
+ """Read every exact prompt handed to this pane, newest first.
+
+ Prompt bodies live outside the workspace snapshot and are loaded only for
+ this request. That keeps the IDE's state poll and first-screen restore small
+ even when a workspace has many panes with long coding briefs.
+ """
+ term, _session = _pane_for_recap(name, workspace_id)
+ stored = await asyncio.to_thread(prompt_history.load, term.history_id)
+ entries = prompt_history.merged(stored, term.prompt_records)
+ total = max(term.prompts_sent, len(entries))
+ return PromptHistoryResponse(
+ name=term.name,
+ total=total,
+ available=len(entries),
+ complete=len(entries) >= term.prompts_sent,
+ items=[
+ PromptHistoryItem(
+ id=entry.id,
+ sequence=entry.sequence,
+ text=entry.text,
+ chars=len(entry.text),
+ at=entry.at,
+ submitted=entry.submitted,
+ )
+ for entry in reversed(entries)
+ ],
+ )
+
+
pane, for a caller that is assembling a prompt rather than handing the
agent a path right now. The files are on disk and referenced either way,
so nothing is lost if the user then walks away.
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index 5709a6ea6f..111990d08e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -39,7 +39,6 @@ vi.mock("@/lib/agenticIdeApi", () => ({
closeTerminals: vi.fn(),
composePrompt: vi.fn(),
moveTerminal: vi.fn(),
- renameTerminal: vi.fn(),
// Polled by the grid so the pane headers keep saying what their agents are
// doing. Resolves empty by default; the recap tests give it real rows.
fetchTerminalRecaps: vi.fn(async () => ({
@@ -100,7 +99,6 @@ vi.mock("./AgenticTerminal", () => ({
agents,
onToggleMaximize,
onSplit,
- onRename,
onClose,
onArrangeStart,
arranging,
@@ -116,7 +114,6 @@ vi.mock("./AgenticTerminal", () => ({
agents?: Array<{ name: string }>;
onToggleMaximize?: () => void;
onSplit?: (direction: "right" | "down", agent?: string) => void;
- onRename?: (name: string) => Promise<boolean>;
onClose?: () => void;
onArrangeStart?: (event: PointerEventLike) => void;
arranging?: boolean;
@@ -168,14 +165,6 @@ vi.mock("./AgenticTerminal", () => ({
>
down as codex
</button>
- {/* The real editor lives in the pane header; here it stands for "the user
- typed a new call-sign and pressed Save". */}
- <button
- data-testid={`pane-rename-${name}`}
- onClick={() => void onRename?.("Frontend")}
- >
- rename
- </button>
<button data-testid={`pane-close-${name}`} onClick={onClose}>
close
</button>
@@ -1984,78 +1973,3 @@ describe("panes that appear from outside the grid", () => {
Reflect.deleteProperty(HTMLElement.prototype, "scrollIntoView");
});
});
-
-describe("renaming a pane", () => {
- /** The workspace as it comes back once "Mika" has become "Frontend". */
- const RENAMED = (() => {
- const next = sessionWith([
- ["Frontend", 0],
- ["Nova", 1],
- ]);
- // The key is what survives a rename — it is what the running terminal is
- // filed under — so the answer keeps Mika's.
- next.terminals[0] = { ...next.terminals[0], key: "mika" };
- return next;
- })();
-
- it("asks the backend and redraws from its answer", async () => {
- vi.mocked(api.renameTerminal).mockResolvedValue(RENAMED);
- const { onSessionChanged } = renderGrid();
-
- fireEvent.click(screen.getByTestId("pane-rename-Mika"));
-
- await waitFor(() =>
- expect(api.renameTerminal).toHaveBeenCalledWith("Mika", "Frontend"),
- );
- expect(onSessionChanged).toHaveBeenCalledWith(RENAMED);
- });
-
- it("carries the maximized pane across to its new name", async () => {
- vi.mocked(api.renameTerminal).mockResolvedValue(RENAMED);
- const { rerender } = renderGrid();
-
- fireEvent.click(screen.getByTestId("pane-maximize-Mika"));
- expect(screen.getByTestId("pane-Mika").getAttribute("data-maximized")).toBe("yes");
-
- fireEvent.click(screen.getByTestId("pane-rename-Mika"));
- await waitFor(() => expect(api.renameTerminal).toHaveBeenCalled());
- rerender({ session: RENAMED });
-
- // Renaming a pane must not un-maximize it: the state is filed under a name
- // this grid itself just changed, and losing it would look like the rename
- // had restarted something.
- expect(screen.getByTestId("pane-Frontend").getAttribute("data-maximized")).toBe(
- "yes",
- );
- });
-
- it("keeps the prompt bar pointed at the pane it was pointed at", async () => {
- vi.mocked(api.renameTerminal).mockResolvedValue(RENAMED);
- const { rerender } = renderGrid();
-
- expect(screen.getByPlaceholderText(/instruction for Mika/i)).toBeTruthy();
-
- fireEvent.click(screen.getByTestId("pane-rename-Mika"));
- await waitFor(() => expect(api.renameTerminal).toHaveBeenCalled());
- rerender({ session: RENAMED });
-
- expect(screen.getByPlaceholderText(/instruction for Frontend/i)).toBeTruthy();
- });
-
- it("says what went wrong and leaves the workspace alone", async () => {
- vi.mocked(api.renameTerminal).mockRejectedValue(
- new Error("Another terminal in this workspace is already called 'Nova'."),
- );
- const { onSessionChanged } = renderGrid();
-
- fireEvent.click(screen.getByTestId("pane-rename-Mika"));
-
- await waitFor(() =>
- expect(pushToast).toHaveBeenCalledWith(
- "error",
- expect.stringContaining("already called"),
- ),
- );
- expect(onSessionChanged).not.toHaveBeenCalled();
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index bd51f0434b..aeec89ccd0 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -90,7 +90,6 @@ import {
clearTerminalRecap,
fetchTerminalRecaps,
refreshTerminalRecap,
- renameTerminal,
setTerminalRecap,
promptTerminal,
type ComposedPreview,
@@ -100,7 +99,6 @@ import {
type PaneNotification,
type SessionState,
type TerminalRecap,
- type TerminalState,
} from "@/lib/agenticIdeApi";
interface AgenticGridProps {
@@ -403,23 +401,6 @@ function takesPrompts(term: { accepts_prompts?: boolean }): boolean {
return term.accepts_prompts !== false;
}
-/**
- * The same map with one pane's entry filed under its new call-sign.
- *
- * This grid keys a pane's UI state (its status, its recap, its restart token)
- * by call-sign, which is the right key right up until a pane is renamed. An
- * untouched map would leave that state stranded under a name nothing looks up
- * any more, and the pane would come back blank for no reason a user could see.
- *
- * Returns the map unchanged when there is nothing filed under `from`, so a
- * rename cannot churn state that was never there.
- */
-function rekey<T>(map: Record<string, T>, from: string, to: string): Record<string, T> {
- if (!(from in map)) return map;
- const { [from]: value, ...rest } = map;
- return { ...rest, [to]: value };
-}
-
function storedAppearance(): TerminalAppearance | null {
return readStored(APPEARANCE_KEY, (raw) =>
raw === "light" || raw === "dark" ? raw : null,
@@ -1069,68 +1050,6 @@ export function AgenticGrid({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jump]);
- /**
- * Give one pane another call-sign.
- *
- * The backend changes a label and nothing else — the agent keeps running and
- * keeps its conversation. This side has more to do than redraw, because a
- * call-sign is the key half this grid files a pane's UI state under: which
- * pane the prompt bar types into, which one is maximized, which are selected,
- * what each is doing. Every one of those maps is carried across to the new
- * name here rather than left to expire, since a pane that loses its focus,
- * its maximized state and its status line the moment it is renamed reads as a
- * rename that restarted something.
- *
- * `knownPanes` is carried too: it is what tells a genuinely NEW pane apart
- * from one that was already here, and without this a rename would announce
- * the pane as freshly opened.
- *
- * Answers whether the name was taken, so the editor can stay open on a
- * refusal (a duplicate call-sign) with the text still in it.
- */
- const renamePane = useCallback(
- async (pane: TerminalState, wanted: string): Promise<boolean> => {
- const from = pane.name;
- const cleaned = wanted.trim();
- if (!cleaned || cleaned === from) return true;
- setWorking(true);
- try {
- const next = await renameTerminal(from, cleaned);
- // The name the backend really settled on, read back off the pane's key
- // rather than assumed from the input — the key is what survives a
- // rename, which is exactly why it is the thing to look the pane up by.
- const to =
- next.terminals.find((term) => term.key === pane.key)?.name ?? cleaned;
- setStatuses((current) => rekey(current, from, to));
- setRecaps((current) => rekey(current, from, to));
- setRestartTokens((current) => rekey(current, from, to));
- setTarget((current) => (current === from ? to : current));
- setMaximized((current) => (current === from ? to : current));
- setPendingClose((current) => (current === from ? to : current));
- setSelectedTerminals((current) => {
- if (!current.has(from)) return current;
- const set = new Set(current);
- set.delete(from);
- set.add(to);
- return set;
- });
- const known = knownPanes.current;
- if (known?.has(from)) {
- known.delete(from);
- known.add(to);
- }
- onSessionChanged?.(next);
- return true;
- } catch (error) {
- pushToast("error", (error as Error).message);
- return false;
- } finally {
- setWorking(false);
- }
- },
- [onSessionChanged, pushToast],
- );
-
/** Where the bell's "jump to pane" goes — here, or via the view for a tab. */
const jumpToNotification = useCallback(
(entry: PaneNotification) => {
@@ -1690,7 +1609,6 @@ export function AgenticGrid({
promptCount={term.prompts_sent}
appearance={appearance}
fontSize={fontSize}
- geometryReady={gridWidth > 0 && gridHeight > 0}
focused={target === term.name}
maximized={isMaximized}
layoutBusy={layoutBusy}
@@ -1704,7 +1622,6 @@ export function AgenticGrid({
setMaximized((current) => (current === term.name ? null : term.name))
}
onSplit={(direction, agent) => void split(term.name, direction, agent)}
- onRename={(next) => renamePane(term, next)}
onClose={() => setPendingClose(term.name)}
onAttachError={(message) => pushToast("error", message)}
// Picked up by its header, put down on another pane. Undefined
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
index ad1b2034b6..4143763e3b 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx
@@ -141,32 +141,6 @@ describe("AgenticTerminal layout", () => {
expect(terminalHarness.open).toHaveBeenCalledWith(host);
expect(terminalHarness.observe).toHaveBeenCalledWith(host);
});
-
- it("waits for the area-aware grid measurement before opening the PTY", () => {
- const view = render(
- <AgenticTerminal
- name="Dana"
- displayName="Claude Code"
- appearance="dark"
- fontSize={13}
- geometryReady={false}
- />,
- );
-
- expect(terminalHarness.open).not.toHaveBeenCalled();
-
- view.rerender(
- <AgenticTerminal
- name="Dana"
- displayName="Claude Code"
- appearance="dark"
- fontSize={13}
- geometryReady
- />,
- );
-
- expect(terminalHarness.open).toHaveBeenCalled();
- });
});
describe("pane keyboard", () => {
@@ -671,119 +645,3 @@ describe("pane start-up feedback", () => {
expect(screen.queryByTestId("agentic-pane-starting-T5")).toBeNull();
});
});
-
-describe("renaming a pane", () => {
- beforeEach(() => {
- globalThis.ResizeObserver = ResizeObserverHarness;
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it("offers no rename control when the owner cannot save one", () => {
- render(
- <AgenticTerminal
- name="T1"
- displayName="Claude Code"
- appearance="dark"
- fontSize={13}
- />,
- );
-
- // A pencil that opens an editor nothing can save would be worse than the
- // plain badge it replaces.
- expect(screen.queryByTestId("pane-rename-T1")).toBeNull();
- });
-
- it("saves the typed call-sign", async () => {
- const onRename = vi.fn(async () => true);
- render(
- <AgenticTerminal
- name="T1"
- displayName="Claude Code"
- appearance="dark"
- fontSize={13}
- onRename={onRename}
- />,
- );
-
- fireEvent.click(screen.getByTestId("pane-rename-T1"));
- const input = screen.getByTestId("pane-rename-input-T1") as HTMLInputElement;
- // It opens on the current name, so a small correction is not a retype.
- expect(input.value).toBe("T1");
- fireEvent.change(input, { target: { value: "Frontend" } });
- fireEvent.click(screen.getByTestId("pane-rename-save-T1"));
-
- await act(async () => undefined);
- expect(onRename).toHaveBeenCalledWith("Frontend");
- expect(screen.queryByTestId("pane-rename-input-T1")).toBeNull();
- });
-
- it("keeps the typing when the name was refused", async () => {
- const onRename = vi.fn(async () => false);
- render(
- <AgenticTerminal
- name="T1"
- displayName="Claude Code"
- appearance="dark"
- fontSize={13}
- onRename={onRename}
- />,
- );
-
- fireEvent.click(screen.getByTestId("pane-rename-T1"));
- fireEvent.change(screen.getByTestId("pane-rename-input-T1"), {
- target: { value: "Api" },
- });
- fireEvent.click(screen.getByTestId("pane-rename-save-T1"));
-
- await act(async () => undefined);
- // A duplicate call-sign is a name to CHANGE — throwing the typing away
- // would make the user retype the part that was fine.
- const input = screen.getByTestId("pane-rename-input-T1") as HTMLInputElement;
- expect(input.value).toBe("Api");
- });
-
- it("closes on Escape without saving", async () => {
- const onRename = vi.fn(async () => true);
- render(
- <AgenticTerminal
- name="T1"
- displayName="Claude Code"
- appearance="dark"
- fontSize={13}
- onRename={onRename}
- />,
- );
-
- fireEvent.click(screen.getByTestId("pane-rename-T1"));
- fireEvent.keyDown(screen.getByTestId("pane-rename-input-T1"), {
- key: "Escape",
- });
-
- await act(async () => undefined);
- expect(onRename).not.toHaveBeenCalled();
- expect(screen.queryByTestId("pane-rename-input-T1")).toBeNull();
- });
-
- it("does not call the backend when the name was not changed", async () => {
- const onRename = vi.fn(async () => true);
- render(
- <AgenticTerminal
- name="T1"
- displayName="Claude Code"
- appearance="dark"
- fontSize={13}
- onRename={onRename}
- />,
- );
-
- fireEvent.click(screen.getByTestId("pane-rename-T1"));
- fireEvent.click(screen.getByTestId("pane-rename-save-T1"));
-
- await act(async () => undefined);
- expect(onRename).not.toHaveBeenCalled();
- expect(screen.queryByTestId("pane-rename-input-T1")).toBeNull();
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index f8704ceffa..ebfd071fac 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -9,9 +9,8 @@
* 2. Appearance and font size are applied to the LIVE instance in their own
* effects. Rebuilding the terminal when the user flips to dark mode would
* tear down the WebSocket, which kills the agent running behind it and
- * loses the whole session. So the connect effect depends on pane identity,
- * restart intent and one-way initial geometry readiness — never live
- * appearance state.
+ * loses the whole session. So the connect effect depends on the pane key
+ * alone.
*
* ## Why this pane is configured the way it is
*
@@ -50,14 +49,12 @@ import { Unicode11Addon } from "@xterm/addon-unicode11";
import "@xterm/xterm/css/xterm.css";
import {
AlertCircle,
- Check,
Circle,
Columns2,
Loader2,
Maximize2,
Minimize2,
Paperclip,
- Pencil,
Rows2,
RotateCcw,
X,
@@ -117,13 +114,6 @@ import { PromptHistoryButton } from "./PromptHistoryButton";
*/
const RECEIPT_MAX_AGE_MS = 30 * 60 * 1000;
-/**
- * How long a call-sign may be — the same cap the backend enforces
- * (`MAX_TERMINAL_NAME`), so the field stops where the save would have failed
- * rather than letting somebody type a name that comes back rejected.
- */
-const MAX_TERMINAL_NAME = 40;
-
export type PaneStatus = "connecting" | "live" | "exited" | "error";
/**
@@ -215,21 +205,12 @@ interface AgenticTerminalProps {
* Which subscription this pane runs on ("Work seat"), when that is worth
* saying. Undefined for everyone with a single login — the header must not
* grow a badge that answers a question the user does not have.
- */
+ */
accountLabel?: string | null;
/** Number shown beside the pane header's prompt-history icon. */
promptCount?: number;
appearance: TerminalAppearance;
fontSize: number;
- /**
- * Has the grid measured the pane's final opening geometry?
- *
- * Area-aware layouts cannot know their band count until the container has a
- * height. Opening the PTY during the width-only first pass attaches it at one
- * size and immediately moves it to another, while its replay is still being
- * parsed. Omitted for standalone uses, which already render at a fixed size.
- */
- geometryReady?: boolean;
/** Highlight this pane as the prompt target. */
focused?: boolean;
onFocus?: () => void;
@@ -249,15 +230,6 @@ interface AgenticTerminalProps {
* choose, so the split buttons act immediately instead of opening a menu.
*/
agents?: SplitAgentChoice[];
- /**
- * Give this pane another call-sign.
- *
- * Answers whether the name was accepted, so the editor can stay open with the
- * text still in it when the workspace already has a pane by that name.
- * Omitted, the header shows no rename control at all rather than one that
- * would do nothing.
- */
- onRename?: (name: string) => Promise<boolean>;
/** Close this pane (the caller asks for confirmation first). */
onClose?: () => void;
/** Disable the split buttons — the workspace is at its terminal limit. */
@@ -308,13 +280,10 @@ export function AgenticTerminal({
displayName,
recap,
recapDetail,
- recapMeta,
- recapActions,
accountLabel,
promptCount = 0,
appearance,
fontSize,
- geometryReady = true,
focused = false,
onFocus,
onStatus,
@@ -322,7 +291,6 @@ export function AgenticTerminal({
onToggleMaximize,
onSplit,
agents,
- onRename,
onClose,
splitDisabled = false,
onAttachError,
@@ -400,7 +368,6 @@ export function AgenticTerminal({
layoutBusyRef.current = layoutBusy;
useEffect(() => {
- if (!geometryReady) return;
const container = containerRef.current;
if (!container) return;
@@ -966,7 +933,7 @@ export function AgenticTerminal({
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:
// appearance/fontSize must NOT rebuild the pane (it would kill the agent).
- }, [name, restartToken, geometryReady]);
+ }, [name, restartToken]);
// Live restyle — no reconnect, so the running agent is untouched. The canvas
// renderer caches rendered glyphs per colour in a texture atlas, so a theme
@@ -1155,8 +1122,6 @@ export function AgenticTerminal({
displayName={displayName}
recap={recap}
recapDetail={recapDetail}
- recapMeta={recapMeta}
- recapActions={recapActions}
accountLabel={accountLabel}
promptCount={promptCount}
appearance={appearance}
@@ -1165,7 +1130,6 @@ export function AgenticTerminal({
onToggleMaximize={onToggleMaximize}
onSplit={onSplit}
agents={agents}
- onRename={onRename}
onClose={onClose}
splitDisabled={splitDisabled}
/>
@@ -1289,7 +1253,6 @@ function PaneHeader({
onToggleMaximize,
onSplit,
agents,
- onRename,
onClose,
splitDisabled,
dead,
@@ -1312,7 +1275,6 @@ function PaneHeader({
onToggleMaximize?: () => void;
onSplit?: (direction: SplitDirection, agent?: string) => void;
agents?: SplitAgentChoice[];
- onRename?: (name: string) => Promise<boolean>;
onClose?: () => void;
splitDisabled: boolean;
/** The agent in this pane has exited or failed — offer to start it again. */
@@ -1325,26 +1287,6 @@ function PaneHeader({
const light = appearance === "light";
// Which split button opened the CLI picker, if any.
const [picking, setPicking] = useState<SplitDirection | null>(null);
- // The call-sign editor: null while the badge is just a badge, otherwise the
- // text being typed. Empty string is a real state (the field was cleared), so
- // "is it open" cannot be read off the text — hence null rather than "".
- const [draft, setDraft] = useState<string | null>(null);
- const [saving, setSaving] = useState(false);
-
- const commitRename = async () => {
- const wanted = (draft ?? "").trim();
- if (!wanted || wanted === name) {
- setDraft(null);
- return;
- }
- setSaving(true);
- // Kept open on a refusal — a duplicate call-sign is a name to CHANGE, and
- // throwing the typing away would make the user retype the part that was
- // fine. The grid says what went wrong.
- const accepted = await onRename?.(wanted);
- setSaving(false);
- if (accepted !== false) setDraft(null);
- };
// With one installed CLI there is nothing to pick, so the button splits
// straight away — a menu with a single entry is a click tax, not a choice.
@@ -1397,115 +1339,24 @@ function PaneHeader({
}}
>
<div className="flex min-w-0 flex-1 items-center gap-2">
- {draft !== null ? (
- /*
- * The call-sign, being typed.
- *
- * A form rather than a bare input so Enter saves the way it does in
- * every other name field in the app, and Escape closes it — the two
- * keys somebody renaming a pane will reach for without looking.
- */
- <form
- className="flex shrink-0 items-center gap-1"
- onSubmit={(event) => {
- event.preventDefault();
- void commitRename();
- }}
- >
- <input
- autoFocus
- value={draft}
- maxLength={MAX_TERMINAL_NAME}
- disabled={saving}
- aria-label={`Rename ${name}`}
- data-testid={`pane-rename-input-${name}`}
- onFocus={(event) => event.currentTarget.select()}
- onChange={(event) => setDraft(event.target.value)}
- onKeyDown={(event) => {
- if (event.key === "Escape") setDraft(null);
- // The pane underneath is a live terminal listening for keys.
- // Without this, typing a name also types into the agent.
- event.stopPropagation();
- }}
- className={cn(
- "w-32 rounded-md px-2 py-0.5 font-display text-[13px] font-semibold tracking-tight outline-none",
- "border border-primary/50 focus:border-primary disabled:opacity-60",
- )}
- style={{
- color: light ? "#2b2b33" : "#e8e8ec",
- background: light ? "rgba(0,0,0,0.04)" : "rgba(255,255,255,0.06)",
- }}
- />
- <button
- type="submit"
- disabled={saving || !draft.trim()}
- aria-label={`Save name for ${name}`}
- data-testid={`pane-rename-save-${name}`}
- className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-primary hover:bg-primary/15 disabled:opacity-40"
- >
- {saving ? (
- <Loader2 className="h-3 w-3 animate-spin" />
- ) : (
- <Check className="h-3 w-3" />
- )}
- </button>
- <button
- type="button"
- disabled={saving}
- aria-label={`Cancel renaming ${name}`}
- onClick={() => setDraft(null)}
- className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted"
- >
- <X className="h-3 w-3" />
- </button>
- </form>
- ) : (
- <>
- <span
- // Double-click is the gesture every tab strip and file manager
- // already uses for "rename this", so it is offered here too — but
- // it is never the only way in, because nothing on screen advertises
- // it. The pencil beside it is what makes the feature findable.
- onDoubleClick={onRename ? () => setDraft(name) : undefined}
- title={onRename ? `${name} — double-click to rename` : undefined}
- className={cn(
- "shrink-0 rounded-md px-2 py-0.5 font-display text-[13px] font-semibold tracking-tight",
- focused ? "bg-primary/20 text-primary" : "",
- )}
- style={
- focused
- ? undefined
- : {
- color: light ? "#2b2b33" : "#e8e8ec",
- background: light
- ? "rgba(0,0,0,0.05)"
- : "rgba(255,255,255,0.06)",
- }
- }
- >
- {name}
- </span>
- {onRename && (
- <button
- type="button"
- aria-label={`Rename ${name}`}
- title={`Rename ${name}`}
- data-testid={`pane-rename-${name}`}
- onClick={() => setDraft(name)}
- onMouseDown={(event) => event.stopPropagation()}
- className={cn(
- "flex h-5 w-5 shrink-0 items-center justify-center rounded transition-opacity",
- "opacity-0 focus-visible:opacity-100 group-hover/header:opacity-100",
- light
- ? "text-[#6b6b73] hover:bg-black/10"
- : "text-[#9a9aa5] hover:bg-white/10",
- )}
- >
- <Pencil className="h-3 w-3" />
- </button>
- )}
- </>
- )}
+ <span
+ className={cn(
+ "shrink-0 rounded-md px-2 py-0.5 font-display text-[13px] font-semibold tracking-tight",
+ focused ? "bg-primary/20 text-primary" : "",
+ )}
+ style={
+ focused
+ ? undefined
+ : {
+ color: light ? "#2b2b33" : "#e8e8ec",
+ background: light
+ ? "rgba(0,0,0,0.05)"
+ : "rgba(255,255,255,0.06)",
+ }
+ }
+ >
+ {name}
+ </span>
<PaneRecap
name={name}
displayName={displayName}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx
deleted file mode 100644
index f8c12351da..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx
+++ /dev/null
@@ -1,484 +0,0 @@
-import { useCallback, useRef } from "react";
-import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { Terminal } from "@xterm/xterm";
-import { PaneScrollbar } from "./PaneScrollbar";
-import { ASSUMED_SCREENS, LINES_PER_NOTCH, SETTLE_MS } from "./scrollbarModel";
-
-const REGION = { top: 0, bottom: 300, left: 0, right: 400 };
-const TRACK_PX = 300;
-
-/**
- * A fake terminal over a mutable state object, so a test can grow the buffer
- * underneath the bar the way a live agent does, and captured subscriptions so
- * it can fire the events xterm would.
- */
-interface TermState {
- type: "normal" | "alternate";
- length: number;
- rows: number;
- viewportY: number;
- baseY: number;
- mouseTrackingMode: string;
- /** What the screen shows, for the movement fingerprint; row index → text. */
- lines: string[];
-}
-
-function fakeTerminal(overrides: Partial<TermState> = {}) {
- const state: TermState = {
- type: "normal",
- length: 1000,
- rows: 24,
- viewportY: 976,
- baseY: 976,
- mouseTrackingMode: "none",
- lines: [],
- ...overrides,
- };
- const listeners: Record<string, (() => void)[]> = {};
- const on = (event: string) => (handler: () => void) => {
- (listeners[event] ??= []).push(handler);
- return { dispose() {} };
- };
- const term = {
- get rows() {
- return state.rows;
- },
- modes: {
- get mouseTrackingMode() {
- return state.mouseTrackingMode;
- },
- },
- buffer: {
- active: {
- get type() {
- return state.type;
- },
- get length() {
- return state.length;
- },
- get viewportY() {
- return state.viewportY;
- },
- get baseY() {
- return state.baseY;
- },
- getLine(y: number) {
- return { translateToString: () => state.lines[y] ?? "" };
- },
- },
- onBufferChange: on("bufferChange"),
- },
- onRender: on("render"),
- onResize: on("resize"),
- onScroll: on("scroll"),
- scrollToLine: vi.fn(),
- scrollLines: vi.fn(),
- } as unknown as Terminal;
- const fire = (event: string) => {
- for (const handler of listeners[event] ?? []) handler();
- };
- return { term, state, fire };
-}
-
-/** A Claude-Code-style pane: the CLI owns the screen and the wheel. */
-function appTerminal(rows = 24) {
- return fakeTerminal({
- type: "alternate",
- length: rows,
- rows,
- viewportY: 0,
- baseY: 0,
- mouseTrackingMode: "any",
- });
-}
-
-function Harness({ term, epoch = 1 }: { term: Terminal; epoch?: number }) {
- const regionRef = useRef<HTMLDivElement | null>(null);
- const hostRef = useRef<HTMLDivElement | null>(null);
- const getTerminal = useCallback(() => term, [term]);
- return (
- <div ref={regionRef} data-testid="region">
- <div ref={hostRef} className="agentic-terminal-host">
- <div className="xterm-screen" />
- </div>
- <PaneScrollbar
- name="Kite"
- regionRef={regionRef}
- hostRef={hostRef}
- getTerminal={getTerminal}
- epoch={epoch}
- appearance="dark"
- />
- </div>
- );
-}
-
-/**
- * A pointer move with coordinates on it. jsdom ships no `PointerEvent`, and
- * the synthetic one Testing Library falls back to carries no `clientY` — a
- * `MouseEvent` of the same name does.
- */
-function dragTo(element: Element, clientY: number) {
- fireEvent(element, new MouseEvent("pointermove", { clientY, bubbles: true }));
-}
-
-const bar = () => screen.queryByTestId("pane-scrollbar-Kite");
-const thumb = () => screen.getByTestId("pane-scrollbar-thumb-Kite");
-const thumbTop = () => parseFloat(thumb().style.top || "0");
-const thumbHeight = () => parseFloat(thumb().style.height || "0");
-const host = () => document.querySelector(".agentic-terminal-host")!;
-
-function reachThePane() {
- fireEvent.mouseEnter(screen.getByTestId("region"));
-}
-
-function leaveThePane() {
- fireEvent.mouseLeave(screen.getByTestId("region"));
-}
-
-/** Every wheel event that reaches the CLI's screen, by deltaY. */
-function watchScreen(): number[] {
- const seen: number[] = [];
- document
- .querySelector(".xterm-screen")!
- .addEventListener("wheel", (event) => {
- seen.push((event as WheelEvent).deltaY);
- });
- return seen;
-}
-
-describe("PaneScrollbar", () => {
- beforeEach(() => {
- // jsdom measures nothing; the two boxes the component reads are staged.
- Object.defineProperty(HTMLElement.prototype, "clientHeight", {
- configurable: true,
- value: TRACK_PX,
- });
- HTMLElement.prototype.getBoundingClientRect = () =>
- ({
- ...REGION,
- width: REGION.right - REGION.left,
- height: REGION.bottom - REGION.top,
- x: REGION.left,
- y: REGION.top,
- toJSON: () => REGION,
- }) as DOMRect;
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it("stays out of the way until the pointer arrives", () => {
- render(<Harness term={fakeTerminal().term} />);
- expect(bar()).toBeNull();
-
- reachThePane();
-
- expect(bar()!.dataset.shown).toBe("true");
- });
-
- it("becomes intangible again after the pointer leaves", () => {
- vi.useFakeTimers();
- try {
- render(<Harness term={fakeTerminal().term} />);
- reachThePane();
- leaveThePane();
- act(() => vi.advanceTimersByTime(1000));
- } finally {
- vi.useRealTimers();
- }
-
- expect(bar()!.dataset.shown).toBe("false");
- // Invisible AND untouchable: a transparent strip that still swallowed
- // pointer events would break selecting text at the pane's right edge.
- expect(bar()!.className).toContain("pointer-events-none");
- });
-
- it("shows nothing on a pane with nothing to scroll", () => {
- render(<Harness term={fakeTerminal({ length: 24 }).term} />);
-
- reachThePane();
-
- expect(bar()).toBeNull();
- });
-
- it("gives a full-screen CLI's pane a bar with nothing measured at all", () => {
- render(<Harness term={appTerminal().term} />);
-
- reachThePane();
-
- expect(bar()!.dataset.kind).toBe("travel");
- // Standing at the newest output: the thumb rests on the bottom.
- expect(thumbTop() + thumbHeight()).toBe(TRACK_PX);
- });
-
- it("draws a scrolled-back terminal's thumb where it really stands", () => {
- render(<Harness term={fakeTerminal({ viewportY: 0 }).term} />);
-
- reachThePane();
-
- expect(bar()!.dataset.kind).toBe("exact");
- expect(thumbTop()).toBe(0);
- });
-
- it("keeps the thumb honest while the agent keeps talking", async () => {
- const { term, state, fire } = fakeTerminal();
- render(<Harness term={term} />);
- reachThePane();
- expect(bar()!.getAttribute("aria-valuemax")).toBe("976");
-
- // The agent prints another thousand lines while the bar is up.
- state.length = 2000;
- state.baseY = 1976;
- fire("scroll");
-
- await waitFor(() =>
- expect(bar()!.getAttribute("aria-valuemax")).toBe("1976"),
- );
- });
-
- it("takes a dragged thumb straight to the line it was dropped on", () => {
- const { term } = fakeTerminal();
- render(<Harness term={term} />);
- reachThePane();
- const grabbed = thumbTop();
-
- fireEvent.pointerDown(thumb(), { clientY: 200, pointerId: 1 });
- dragTo(thumb(), 200 - grabbed);
-
- // Dropped at the very top of the track: the top of the scrollback.
- expect(term.scrollToLine).toHaveBeenLastCalledWith(0);
-
- fireEvent.pointerUp(thumb(), { pointerId: 1 });
- });
-
- it("drags a full-screen CLI by relaying wheel notches to its screen", () => {
- render(<Harness term={appTerminal(24).term} />);
- reachThePane();
- const seen = watchScreen();
- const grabbed = thumbTop();
-
- fireEvent.pointerDown(thumb(), { clientY: 200, pointerId: 1 });
- dragTo(thumb(), 200 - grabbed);
- fireEvent.pointerUp(thumb(), { pointerId: 1 });
-
- // A full pull up asks for the whole assumed span, in notches — more than
- // one step may relay, so the release has to carry the remainder.
- expect(seen.length).toBe(
- Math.trunc((24 * ASSUMED_SCREENS) / LINES_PER_NOTCH),
- );
- expect(new Set(seen)).toEqual(new Set([-1]));
- });
-
- it("counts a real wheel turn by the rows it covers, not by the event", async () => {
- // One turn of a physical wheel is ~100 px, which xterm hands the CLI as
- // one report PER ROW. Counting the turn as a single notch under-counted
- // every real scroll and parked the thumb near a bottom it had left.
- render(<Harness term={appTerminal(24).term} />);
- reachThePane();
-
- // The staged pane is 300 px over 24 rows: 100 px is eight rows.
- fireEvent.wheel(host(), { deltaY: -100, deltaMode: 0 });
-
- await waitFor(() =>
- expect(bar()!.getAttribute("aria-valuemax")).toBe(
- String(8 * LINES_PER_NOTCH + 24 * ASSUMED_SCREENS),
- ),
- );
- });
-
- it("pages towards a press on the empty part of the track", () => {
- const { term } = fakeTerminal();
- render(<Harness term={term} />);
- reachThePane();
-
- // The thumb rests at the bottom, so a press at the top pages backwards.
- fireEvent.pointerDown(bar()!, { clientY: REGION.top + 4 });
-
- expect(term.scrollLines).toHaveBeenCalledWith(-23);
- });
-
- it("forwards a wheel over the bar to the terminal, untouched", () => {
- render(<Harness term={fakeTerminal().term} />);
- reachThePane();
- const seen = watchScreen();
-
- const notCancelled = fireEvent.wheel(bar()!, {
- deltaY: 120,
- deltaMode: 0,
- });
-
- expect(seen).toEqual([120]);
- // The bar has no wheel behaviour of its own and never cancels the event.
- expect(notCancelled).toBe(true);
- });
-
- it("never lays a hand on a wheel turned over the terminal", () => {
- render(<Harness term={appTerminal().term} />);
-
- let untouched = false;
- act(() => {
- untouched = host().dispatchEvent(
- new WheelEvent("wheel", {
- deltaY: -1,
- bubbles: true,
- cancelable: true,
- }),
- );
- });
-
- expect(untouched).toBe(true);
- });
-
- it("counts a CLI-held pane's travel and re-anchors at the live end", async () => {
- render(<Harness term={appTerminal(24).term} />);
-
- // Four notches back, before the bar was ever shown.
- for (let i = 0; i < 4; i += 1) fireEvent.wheel(host(), { deltaY: -1 });
- reachThePane();
- expect(thumbTop() + thumbHeight()).toBeLessThan(TRACK_PX);
-
- // Forward far past the live end: the count clamps, the thumb comes home.
- for (let i = 0; i < 8; i += 1) fireEvent.wheel(host(), { deltaY: 1 });
- await waitFor(() => expect(thumbTop() + thumbHeight()).toBe(TRACK_PX));
- });
-
- /*
- * The reported bug, at the level the user met it (2026-07-29): the pane
- * showed the very TOP of a long transcript while the thumb sat pinned at
- * the very bottom of the track, and the bar could only ever scroll up.
- *
- * The count was being snapped to zero on every repaint that carried no
- * `Jump to bottom` — a string this CLI replaces with `N new messages` the
- * moment output arrives while the view is parked, and one no other CLI
- * paints at all. Nothing the screen SAYS may move the count now.
- */
- it("holds its ground while a scrolled-back CLI keeps repainting", async () => {
- const { state, term, fire } = appTerminal(24);
- state.lines = Array.from({ length: 24 }, (_, i) => `transcript row ${i}`);
- render(<Harness term={term} />);
-
- for (let i = 0; i < 10; i += 1) fireEvent.wheel(host(), { deltaY: -1 });
- reachThePane();
- // The reads are coalesced into frames, so let one pass before taking the
- // position this test is about to hold the bar to.
- await act(
- () =>
- new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),
- );
- const parked = thumbTop();
- expect(parked + thumbHeight()).toBeLessThan(TRACK_PX);
-
- // The agent talks on while the user reads: twenty repaints, including the
- // overlay swap that used to be read as "you are at the newest output".
- for (let i = 0; i < 20; i += 1) {
- state.lines[3] = `agent still talking ${i}`;
- state.lines[20] = i % 2 ? " 1 new message (ctrl+End) ↓" : "";
- fire("render");
- // eslint-disable-next-line no-await-in-loop
- await act(
- () =>
- new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),
- );
- }
-
- expect(thumbTop()).toBe(parked);
- });
-
- /*
- * The live-end anchor that replaced the English string: a down the CLI has
- * nothing left to answer with means the newest output is already on screen.
- * Works for a CLI in any language, and for CLIs that paint no overlay.
- */
- it("comes home when downs stop changing the screen", async () => {
- let clock = 2_000_000;
- vi.spyOn(Date, "now").mockImplementation(() => clock);
- const { state, term, fire } = appTerminal(24);
- state.lines = Array.from({ length: 24 }, (_, i) => `transcript row ${i}`);
- render(<Harness term={term} />);
- reachThePane();
-
- // Ten notches back, and the screen visibly follows: the episode moved.
- for (let i = 0; i < 10; i += 1) fireEvent.wheel(host(), { deltaY: -1 });
- state.lines[0] = "transcript moved";
- fire("render");
- await act(
- () =>
- new Promise<void>((resolve) =>
- requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
- ),
- );
- expect(thumbTop() + thumbHeight()).toBeLessThan(TRACK_PX);
-
- // Two notches forward that change nothing: the CLI is already showing its
- // newest output, however far the count still claims to be from it.
- for (let i = 0; i < 2; i += 1) fireEvent.wheel(host(), { deltaY: 1 });
- clock += SETTLE_MS + 100;
- fire("render");
-
- await waitFor(() => expect(thumbTop() + thumbHeight()).toBe(TRACK_PX));
- });
-
- /*
- * The pinned-pane deadlock, end to end: the brake engages MID-DRAG (the
- * CLI stopped answering), and the rest of the drag must still send one
- * probe notch per step instead of going dead — the escape hatch that lets
- * a wrongly-braked pane free itself.
- */
- it("keeps probing upward while the brake holds", async () => {
- let clock = 1_000_000;
- vi.spyOn(Date, "now").mockImplementation(() => clock);
- const { state, term, fire } = appTerminal(24);
- state.lines = Array.from({ length: 24 }, (_, i) => `transcript row ${i}`);
- render(<Harness term={term} />);
- reachThePane();
-
- // Prove movement once — a brake without proven movement must not engage.
- // Then WAIT for the frame that carries the sync: the change must be on
- // record before the drag below piles up unconfirmed notches.
- state.lines[0] = "transcript moved";
- fire("render");
- await act(
- () =>
- new Promise<void>((resolve) =>
- requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
- ),
- );
- expect(bar()!.dataset.kind).toBe("travel");
-
- // Grab the thumb and pull: the burst is relayed, the screen stays still.
- const seen = watchScreen();
- fireEvent.pointerDown(thumb(), { clientY: 250, pointerId: 1 });
- dragTo(thumb(), 220);
- expect(seen.length).toBeGreaterThan(0);
-
- // The pty stays silent past the settle window: the brake engages.
- clock += SETTLE_MS + 100;
- fire("render");
- await waitFor(() =>
- expect(bar()!.getAttribute("aria-valuemax")).toBe("3"),
- );
-
- // Further pulling probes with exactly one notch per step, never a burst.
- const before = seen.length;
- dragTo(thumb(), 100);
- fireEvent.pointerUp(thumb(), { pointerId: 1 });
- expect(seen.length - before).toBe(1);
- expect(seen[seen.length - 1]).toBe(-1);
- });
-
- it("starts a fresh terminal's count from zero", async () => {
- const first = appTerminal(24).term;
- const { rerender } = render(<Harness term={first} epoch={1} />);
- for (let i = 0; i < 4; i += 1) fireEvent.wheel(host(), { deltaY: -1 });
- reachThePane();
- expect(thumbTop() + thumbHeight()).toBeLessThan(TRACK_PX);
-
- // The pane restarted its agent: same component, replaced terminal.
- rerender(<Harness term={appTerminal(24).term} epoch={2} />);
-
- await waitFor(() => 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.tsx
deleted file mode 100644
index 19602fd89f..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx
+++ /dev/null
@@ -1,633 +0,0 @@
-/**
- * A pane's drag scrollbar: a thin overlay on the right edge, driven by the
- * mouse and by nothing else.
- *
- * ## The one hard rule — the wheel is not this component's business
- *
- * A predecessor of this bar is remembered as "it broke scrolling in the
- * terminal". The root cause was elsewhere (a replay buffer dropping the CLI's
- * mouse negotiation), but the lesson stands, so this build makes it a law:
- * nothing here ever calls `preventDefault` on a wheel event, reinterprets one,
- * or stands between the wheel and xterm. The two places wheel events appear
- * at all are (a) a **passive** observer that only counts them, and (b) the
- * track forwarding a clone of any wheel it happens to catch to the terminal's
- * screen, so that scrolling over the bar behaves exactly like scrolling next
- * to it. Everything the bar does itself is done by dragging its thumb or
- * clicking its track — mouse only, by design.
- *
- * ## Why the pane draws its own bar instead of styling the browser's
- *
- * Half the panes have nothing a browser scrollbar could move. A line-printing
- * CLI (Codex, a shell) keeps its history in xterm's scrollback and could use
- * the native bar — but a full-screen CLI (Claude Code) runs on the alternate
- * buffer, where the terminal holds no scrollback at all and the transcript
- * lives inside the application. For those panes the thumb is dragged in
- * relayed wheel notches, and where it stands is COUNTED from the wheel
- * traffic rather than measured from a screen that cannot be read — see
- * ./scrollbarModel for what that claim means and why it re-anchors at the
- * live end. The synthetic notches are dispatched as real wheel events on
- * xterm's screen, because xterm already knows which mouse protocol the
- * application negotiated and encodes the report accordingly; guessing those
- * bytes here would put junk in the CLI's prompt.
- *
- * ## Cost discipline
- *
- * A grid holds a dozen live terminals. While the pointer is elsewhere this
- * component owns two hover listeners and one passive wheel observer, and
- * reads nothing. Terminal state is read only while the bar is on screen, all
- * reads are coalesced into animation frames, and hover is enter/leave rather
- * than per-move tracking.
- */
-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 {
- backAtThumbTop,
- exactView,
- freshTravel,
- hasScroll,
- notchesFor,
- screenTravel,
- SETTLE_MS,
- thumbBox,
- travelView,
- wheelTravel,
- type ScreenGlance,
- type ScrollView,
- type Travel,
-} from "./scrollbarModel";
-
-/** 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 visible as a position readout. */
-const FLASH_MS = 800;
-
-/**
- * Rows at the bottom of a full-screen CLI's screen that repaint on their own:
- * the input box, the spinner, a status line, a token counter. They must stay
- * out of the fingerprint below — a spinner ticking once a frame would read as
- * "the transcript moved" and no brake could ever engage.
- *
- * A count rather than a marker on purpose. The row the chrome starts at used
- * to be found by matching one CLI's English overlay text, which is how a bar
- * that worked for Claude Code worked for nothing else and then stopped
- * working for Claude Code too (AP-27). Eight rows is generous for every CLI
- * measured, and being wrong about it costs sensitivity, never correctness.
- */
-const CHROME_ROWS = 8;
-
-/** Row height assumed when the pane cannot be measured, in px. */
-const FALLBACK_CELL_PX = 17;
-
-/** True when the running application receives wheel events itself. */
-function appOwnsScreen(term: Terminal | null): boolean {
- if (!term) return false;
- const tracking = term.modes?.mouseTrackingMode;
- if (Boolean(tracking) && tracking !== "none") return true;
- return term.buffer?.active?.type === "alternate";
-}
-
-/**
- * What this pane can scroll right now, or null when nothing is known.
- *
- * Defensive against the bundled xterm's shape on purpose: a missing field
- * must mean "no bar", never an exception inside a render.
- */
-export function readScrollView(
- term: Terminal | null,
- travel: Travel,
-): ScrollView | null {
- const buffer = term?.buffer?.active;
- const rows = term?.rows ?? 0;
- if (!term || !buffer || rows < 1) return null;
- if (appOwnsScreen(term)) {
- return travelView(travel.travelled, rows, travel.ceiling);
- }
- const view = exactView(
- buffer.length ?? rows,
- buffer.baseY ?? 0,
- buffer.viewportY ?? 0,
- rows,
- );
- return hasScroll(view) ? view : null;
-}
-
-/**
- * One look at an application-held pane's screen: what does its transcript
- * region say right now?
- *
- * Only whether this changes between two looks is ever used, so the content is
- * never interpreted — see ./scrollbarModel on why reading a CLI's words was
- * the bug rather than the fix. The bottom {@link CHROME_ROWS} rows are left
- * out because they animate on their own. Returns null when the buffer cannot
- * be read; the caller keeps its estimate rather than inventing one.
- */
-export function readScreen(term: Terminal | null): ScreenGlance | null {
- const buffer = term?.buffer?.active;
- const rows = term?.rows ?? 0;
- if (!term || !buffer || typeof buffer.getLine !== "function" || rows < 1) {
- return null;
- }
- try {
- const text: string[] = [];
- for (let y = 0; y < Math.max(1, rows - CHROME_ROWS); y += 1) {
- text.push(buffer.getLine(y)?.translateToString(true) ?? "");
- }
- return { fingerprint: text.join("\n") };
- } catch {
- return null;
- }
-}
-
-/**
- * How many mouse reports xterm will send the application for this wheel
- * event, signed the way `deltaY` is.
- *
- * The count of where a full-screen CLI's pane stands is only as good as this
- * conversion, and taking every DOM wheel event for a single notch — as this
- * did — under-counted a real mouse wheel roughly five-fold: one turn of a
- * physical wheel is ~100 px, which xterm turns into one report PER ROW it
- * covers, each of which moves the application again. The pane drifted further
- * behind the truth with every turn, and the thumb sat near the bottom of a
- * transcript the user had scrolled minutes into.
- *
- * Mirrors xterm's own `getLinesScrolled`: line and page deltas are already in
- * the terminal's units, a pixel delta is divided by the measured row height.
- */
-export function wheelNotches(
- event: WheelEvent,
- host: HTMLElement | null,
- rows: number,
-): number {
- const magnitude = Math.abs(event.deltaY);
- if (!Number.isFinite(magnitude) || magnitude === 0) return 0;
- let lines: number;
- if (event.deltaMode === 1) {
- lines = magnitude;
- } else if (event.deltaMode === 2) {
- lines = magnitude * Math.max(1, rows);
- } else {
- const screen = host?.querySelector<HTMLElement>(".xterm-screen");
- const height = screen?.clientHeight ?? 0;
- const cell = rows > 0 && height > 0 ? height / rows : FALLBACK_CELL_PX;
- lines = magnitude / Math.max(1, cell);
- }
- // A turn too small for a whole row still moved the application by one: xterm
- // carries the remainder over, and dropping it here would lose the scroll.
- const whole = Math.max(1, Math.round(lines));
- return event.deltaY < 0 ? -whole : whole;
-}
-
-/**
- * Hand `count` wheel notches to whatever runs in `host` (direction -1 is
- * towards older output, matching a wheel turned away from the hand).
- */
-export function relayNotches(
- host: HTMLElement | null,
- direction: 1 | -1,
- count: number,
-): void {
- if (!host || count <= 0 || typeof WheelEvent === "undefined") return;
- const screen = host.querySelector<HTMLElement>(".xterm-screen");
- if (!screen) return;
- const box = screen.getBoundingClientRect();
- for (let i = 0; i < count; i += 1) {
- 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,
- }),
- );
- }
-}
-
-interface PaneScrollbarProps {
- /** Pane call-sign — labels and test ids. */
- name: string;
- /**
- * The pane's terminal area, which hover is measured against. It has to be
- * the region the bar sits INSIDE — measured against the xterm host, moving
- * onto the bar itself would already count as having left.
- */
- regionRef: React.RefObject<HTMLElement | null>;
- /** The xterm host, where relayed and forwarded wheel events are aimed. */
- hostRef: React.RefObject<HTMLElement | null>;
- /** The live terminal, or null before the pane has built one. */
- getTerminal: () => Terminal | null;
- /** Bumped whenever the terminal behind `getTerminal` is replaced. */
- epoch: number;
- appearance: TerminalAppearance;
-}
-
-export function PaneScrollbar({
- name,
- regionRef,
- hostRef,
- getTerminal,
- epoch,
- appearance,
-}: PaneScrollbarProps) {
- const trackRef = useRef<HTMLDivElement | null>(null);
- const [view, setView] = useState<ScrollView | null>(null);
- const [trackPx, setTrackPx] = useState(0);
- const [hovering, setHovering] = useState(false);
- const [flashing, setFlashing] = useState(false);
- const [dragging, setDragging] = useState(false);
- // The thumb's position while it is held. A full-screen CLI answers relayed
- // notches a beat later, so a thumb drawn only from the counted position
- // would trail the pointer that is holding it.
- const [heldTopPx, setHeldTopPx] = useState<number | null>(null);
-
- // Where a full-screen CLI's pane stands, counted off the wheel traffic —
- // the user's own turns and this bar's relays alike, since both pass the
- // same observer below — and reconciled against whether the screen moved
- // (see ./scrollbarModel, "the two brakes").
- const travelRef = useRef<Travel>(freshTravel());
- // Which kind of pane the last reading saw. A CLI that enters or leaves the
- // alternate screen mid-session (a shell running `less`) starts a different
- // history, and a count carried across that line would describe the old one.
- const lastKindRef = useRef<ScrollView["kind"] | null>(null);
- // The sync scheduler, parked here so the always-on wheel observer can poke
- // the read loop that only exists while the bar is visible.
- const scheduleRef = useRef<(() => void) | null>(null);
-
- const shown = hovering || flashing || dragging;
- const viewRef = useRef(view);
- viewRef.current = view;
-
- // A replaced terminal is a fresh transcript.
- useEffect(() => {
- travelRef.current = freshTravel();
- lastKindRef.current = null;
- setView(null);
- }, [epoch]);
-
- // ------------------------------------------------------------------ hover
- // Enter and leave only: a grid of a dozen panes must not pay per pixel of
- // pointer movement to know which one is being reached for.
- useEffect(() => {
- const region = regionRef.current;
- if (!region) return;
- let timer: number | undefined;
- const enter = () => {
- if (timer !== undefined) window.clearTimeout(timer);
- timer = undefined;
- setHovering(true);
- };
- const leave = () => {
- if (timer !== undefined) window.clearTimeout(timer);
- timer = window.setTimeout(() => setHovering(false), LINGER_MS);
- };
- region.addEventListener("mouseenter", enter);
- region.addEventListener("mouseleave", leave);
- return () => {
- if (timer !== undefined) window.clearTimeout(timer);
- region.removeEventListener("mouseenter", enter);
- region.removeEventListener("mouseleave", leave);
- };
- }, [regionRef]);
-
- // -------------------------------------------------------------- observing
- // The wheel, watched but never touched. Passive so it CANNOT interfere with
- // what xterm does next, capture so it also sees the synthetic notches this
- // bar dispatches, and always on so a pane scrolled a minute ago comes up
- // already knowing how far back it stands.
- useEffect(() => {
- const host = hostRef.current;
- if (!host) return;
- let timer: number | undefined;
- const onWheel = (event: WheelEvent) => {
- if (event.deltaY === 0) return;
- const term = getTerminal();
- if (appOwnsScreen(term)) {
- travelRef.current = wheelTravel(
- travelRef.current,
- wheelNotches(event, host, term?.rows ?? 0),
- Date.now(),
- );
- }
- scheduleRef.current?.();
- 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);
- host.removeEventListener("wheel", onWheel, { capture: true });
- };
- }, [hostRef, getTerminal, epoch]);
-
- // ---------------------------------------------------------------- reading
- // Terminal state is read only while the bar is on screen, at most once per
- // animation frame — a grid of live agents cannot afford more.
- useEffect(() => {
- if (!shown) {
- scheduleRef.current = null;
- return;
- }
- const term = getTerminal();
- if (!term) return;
- let frame: number | undefined;
- let settleTimer: number | undefined;
-
- const sync = () => {
- frame = undefined;
- const appHeld = appOwnsScreen(term);
- // Crossing between a terminal-held and an application-held screen
- // resets the count: it described a history that is no longer on stage.
- const kind: ScrollView["kind"] = appHeld ? "travel" : "exact";
- if (lastKindRef.current && kind !== lastKindRef.current) {
- travelRef.current = freshTravel();
- }
- lastKindRef.current = kind;
- if (appHeld) {
- // Reconcile the count against whether the screen moved — the two
- // brakes that replaced the old overlay anchor (see ./scrollbarModel).
- travelRef.current = screenTravel(
- travelRef.current,
- readScreen(term),
- Date.now(),
- );
- // Unconfirmed notches need a second look once the pty has had its
- // say, even if no event arrives to prompt one. This is the ONLY thing
- // that ever brings a pane home again, so it must cover both
- // directions: an unanswered down is what proves the live end.
- if (settleTimer !== undefined) window.clearTimeout(settleTimer);
- if (travelRef.current.pendingUp > 0 || travelRef.current.pendingDown > 0) {
- settleTimer = window.setTimeout(schedule, SETTLE_MS + 50);
- }
- }
- const next = readScrollView(term, travelRef.current);
- setView((current) => (sameView(current, next) ? current : next));
- };
- const schedule = () => {
- if (frame === undefined) frame = requestAnimationFrame(sync);
- };
- scheduleRef.current = schedule;
-
- sync();
- const subscriptions = [
- term.onRender?.(schedule),
- term.onResize?.(schedule),
- term.onScroll?.(schedule),
- term.buffer?.onBufferChange?.(schedule),
- ];
- return () => {
- scheduleRef.current = null;
- if (frame !== undefined) cancelAnimationFrame(frame);
- if (settleTimer !== undefined) window.clearTimeout(settleTimer);
- for (const subscription of subscriptions) subscription?.dispose();
- };
- }, [shown, getTerminal, epoch]);
-
- // -------------------------------------------------------------- geometry
- // Measured outside the render, and only when the box actually changes.
- useEffect(() => {
- const track = trackRef.current;
- if (!track) return;
- const measure = () => {
- setTrackPx((current) =>
- current === track.clientHeight ? current : track.clientHeight,
- );
- };
- measure();
- if (typeof ResizeObserver === "undefined") return;
- const observer = new ResizeObserver(measure);
- observer.observe(track);
- return () => observer.disconnect();
- }, [view !== null]);
-
- // ----------------------------------------------------------------- input
- /** Scroll the pane by `lines` towards older output (negative: newer). */
- const scrollBy = useCallback(
- (lines: number) => {
- const term = getTerminal();
- if (!term || lines === 0) return;
- if (appOwnsScreen(term)) {
- // While the brake holds, an up-drag relays ONE probe notch instead
- // of a burst. At a genuine top it is ignored and costs nothing; at a
- // false one (a CLI that was merely busy) it moves the screen, the
- // fingerprint changes, and the brake releases itself — the escape
- // hatch that keeps a wrong verdict from pinning the pane for good.
- if (lines > 0 && travelRef.current.saturated) {
- relayNotches(hostRef.current, -1, 1);
- return;
- }
- const notches = notchesFor(lines);
- relayNotches(
- hostRef.current,
- notches > 0 ? -1 : 1,
- Math.abs(notches),
- );
- return;
- }
- term.scrollLines?.(-lines);
- },
- [getTerminal, hostRef],
- );
-
- /** Take the pane to `wanted` lines back from its newest output. */
- const scrollTo = useCallback(
- (wanted: number) => {
- const term = getTerminal();
- if (!term) return;
- if (appOwnsScreen(term)) {
- // Asked in notches, against what has actually been relayed so far —
- // the observer above moves the count as each notch goes past.
- scrollBy(wanted - travelRef.current.travelled);
- return;
- }
- // A terminal that owns its scrollback is told the line outright, so a
- // fast drag cannot overshoot by however far a reading lags the pointer.
- const base = term.buffer?.active?.baseY ?? 0;
- term.scrollToLine?.(Math.max(0, base - Math.max(0, wanted)));
- },
- [getTerminal, scrollBy],
- );
-
- const onThumbPointerDown = useCallback(
- (event: React.PointerEvent<HTMLDivElement>) => {
- const track = trackRef.current;
- if (!track || !getTerminal()) return;
- // A drag on the thumb must not start a text selection in the terminal
- // under it, and must not count as clicking into the pane.
- event.preventDefault();
- event.stopPropagation();
-
- const height = track.clientHeight;
- // The mapping is frozen at the grab. A travel-counted pane's claimed
- // span grows while it is scrolled back, and a thumb measured against a
- // span that moves underneath slides away from the hand holding it.
- const grabbed = viewRef.current;
- const box = thumbBox(grabbed, height);
- const startTop = box?.topPx ?? 0;
- const startY = event.clientY;
- const travel = Math.max(0, height - (box?.heightPx ?? 0));
-
- const target = event.currentTarget;
- // Capture keeps the drag alive when the pointer leaves the thin bar —
- // but a build without it (some test environments) still gets a working
- // thumb from the listeners below.
- try {
- target.setPointerCapture(event.pointerId);
- } catch {
- /* no capture here — the drag survives on the listeners alone */
- }
- setDragging(true);
- setHeldTopPx(startTop);
-
- let lastTopPx = startTop;
- const onMove = (move: PointerEvent) => {
- if (!Number.isFinite(move.clientY)) return;
- const topPx = Math.min(
- Math.max(startTop + (move.clientY - startY), 0),
- travel,
- );
- lastTopPx = topPx;
- // A coordinate that cannot be worked with leaves the thumb where the
- // count says it is, rather than writing NaN into the layout.
- setHeldTopPx(Number.isFinite(topPx) ? topPx : null);
- scrollTo(backAtThumbTop(topPx, height, grabbed));
- };
- const finish = () => {
- // One last ask at the position the thumb was let go of. A fast pull
- // across a long history wants more notches than a single step may
- // relay (MAX_NOTCHES_PER_STEP), and the remainder normally rides on
- // the next pointer move — a hand that stops at the end of the track
- // never sends one, and the pane used to stay short of where it was
- // dropped with no way to tell why. Not while the top brake holds:
- // there a step means one probe notch, and this would be a second.
- if (!travelRef.current.saturated) {
- scrollTo(backAtThumbTop(lastTopPx, height, grabbed));
- }
- try {
- target.releasePointerCapture(event.pointerId);
- } catch {
- /* never captured */
- }
- target.removeEventListener("pointermove", onMove);
- target.removeEventListener("pointerup", finish);
- target.removeEventListener("pointercancel", finish);
- setDragging(false);
- setHeldTopPx(null);
- };
- target.addEventListener("pointermove", onMove);
- target.addEventListener("pointerup", finish);
- target.addEventListener("pointercancel", finish);
- },
- [getTerminal, scrollTo],
- );
-
- // A press on the empty track pages towards the pointer, like every other
- // scrollbar.
- const onTrackPointerDown = useCallback(
- (event: React.PointerEvent<HTMLDivElement>) => {
- const track = trackRef.current;
- const current = viewRef.current;
- if (!track || !current) return;
- event.preventDefault();
- event.stopPropagation();
- const box = track.getBoundingClientRect();
- const geometry = thumbBox(current, box.height);
- if (!geometry) return;
- const page = Math.max(1, current.rows - 1);
- const towardsNewer = event.clientY - box.top > geometry.topPx;
- scrollBy(towardsNewer ? -page : page);
- },
- [scrollBy],
- );
-
- // Wheel over the bar: forwarded to the terminal untouched, so the strip of
- // pixels the bar occupies scrolls exactly like every other part of the
- // pane. The bar itself has no wheel behaviour at all.
- const onTrackWheel = useCallback(
- (event: React.WheelEvent<HTMLDivElement>) => {
- const screen =
- hostRef.current?.querySelector<HTMLElement>(".xterm-screen");
- if (!screen || typeof WheelEvent === "undefined") return;
- screen.dispatchEvent(
- new WheelEvent("wheel", {
- bubbles: true,
- cancelable: true,
- clientX: event.clientX,
- clientY: event.clientY,
- deltaMode: event.deltaMode,
- deltaY: event.deltaY,
- deltaX: event.deltaX,
- }),
- );
- },
- [hostRef],
- );
-
- // ---------------------------------------------------------------- render
- const box = useMemo(() => thumbBox(view, trackPx), [view, trackPx]);
- if (!hasScroll(view)) return null;
-
- const light = appearance === "light";
-
- return (
- <div
- ref={trackRef}
- role="scrollbar"
- aria-orientation="vertical"
- aria-label={`Scroll ${name}`}
- aria-valuemin={0}
- aria-valuemax={view?.above ?? 0}
- aria-valuenow={(view?.above ?? 0) - (view?.back ?? 0)}
- data-testid={`pane-scrollbar-${name}`}
- data-shown={shown ? "true" : "false"}
- data-kind={view?.kind}
- onPointerDown={onTrackPointerDown}
- onWheel={onTrackWheel}
- onMouseDown={(event) => event.stopPropagation()}
- className={cn(
- "absolute bottom-1 top-1 z-10 w-[9px] rounded-full transition-opacity duration-150",
- shown ? "opacity-100" : "pointer-events-none opacity-0",
- )}
- style={{
- right: 2,
- background: shown
- ? light
- ? "rgba(0,0,0,0.06)"
- : "rgba(255,255,255,0.07)"
- : "transparent",
- }}
- >
- {box && (
- <div
- data-testid={`pane-scrollbar-thumb-${name}`}
- onPointerDown={onThumbPointerDown}
- className={cn(
- "absolute left-0 w-full rounded-full",
- dragging ? "cursor-grabbing" : "cursor-grab transition-[top]",
- )}
- style={{
- top: heldTopPx ?? box.topPx,
- height: box.heightPx,
- background: `rgb(var(--jarvis-yellow) / ${dragging ? 0.95 : 0.6})`,
- transitionDuration: dragging ? undefined : "80ms",
- }}
- />
- )}
- </div>
- );
-}
-
-function sameView(a: ScrollView | null, b: ScrollView | null): boolean {
- if (a === b) return true;
- if (!a || !b) return false;
- return (
- a.kind === b.kind &&
- a.above === b.above &&
- a.back === b.back &&
- a.rows === b.rows
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.test.ts b/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.test.ts
deleted file mode 100644
index d3c565e036..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.test.ts
+++ /dev/null
@@ -1,305 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- ASSUMED_SCREENS,
- backAtThumbTop,
- exactView,
- freshTravel,
- hasScroll,
- LINES_PER_NOTCH,
- MAX_NOTCHES_PER_STEP,
- MIN_THUMB_PX,
- notchesFor,
- screenTravel,
- SETTLE_MS,
- thumbBox,
- travelView,
- wheelTravel,
- type Travel,
-} from "./scrollbarModel";
-
-describe("exactView", () => {
- it("reads a scrolled-back terminal off its own numbers", () => {
- // 1000 lines, 24 on screen, viewport 100 lines above the newest screen.
- const view = exactView(1000, 976, 876, 24);
- expect(view).toEqual({ kind: "exact", above: 976, back: 100, rows: 24 });
- });
-
- it("clamps a viewport reading that ran past either end", () => {
- expect(exactView(1000, 976, 1200, 24).back).toBe(0);
- expect(exactView(1000, 976, -50, 24).back).toBe(976);
- });
-
- it("treats a garbage field as the safe end, not a crash", () => {
- expect(exactView(1000, Number.NaN, 0, 24).back).toBe(0);
- });
-});
-
-describe("travelView", () => {
- it("claims the travelled distance plus the assumed headroom", () => {
- expect(travelView(60, 24)).toEqual({
- kind: "travel",
- above: 60 + 24 * ASSUMED_SCREENS,
- back: 60,
- rows: 24,
- });
- });
-
- it("draws a graspable thumb, not half the track, at the live end", () => {
- // The maintainer's report: on a pane at its newest output the thumb filled
- // half the bar, which claims a two-screen history no agent ever has.
- const box = thumbBox(travelView(0, 24), 300)!;
- expect(box.heightPx).toBeLessThan(100);
- expect(box.heightPx).toBeGreaterThanOrEqual(MIN_THUMB_PX);
- expect(box.topPx + box.heightPx).toBe(300);
- });
-
- it("never stands behind the live end", () => {
- expect(travelView(-5, 24).back).toBe(0);
- });
-
- it("maps the real span once the top has been measured", () => {
- const view = travelView(90, 24, 90);
- // At the measured ceiling the thumb genuinely reaches the top.
- expect(view.above).toBe(90);
- expect(thumbBox(view, 300)!.topPx).toBe(0);
- });
-});
-
-describe("hasScroll", () => {
- it("says no for an unscrollable or missing view", () => {
- expect(hasScroll(null)).toBe(false);
- expect(hasScroll(exactView(24, 0, 0, 24))).toBe(false);
- });
-
- it("says yes the moment there is history above the screen", () => {
- expect(hasScroll(exactView(25, 1, 1, 24))).toBe(true);
- expect(hasScroll(travelView(0, 24))).toBe(true);
- });
-});
-
-describe("thumbBox", () => {
- it("rests the thumb at the very bottom on the newest output", () => {
- const box = thumbBox(exactView(1000, 976, 976, 24), 300)!;
- expect(box.topPx + box.heightPx).toBe(300);
- });
-
- it("parks the thumb at the top of a fully scrolled-back pane", () => {
- expect(thumbBox(exactView(1000, 976, 0, 24), 300)!.topPx).toBe(0);
- });
-
- it("keeps the thumb graspable however long the history grows", () => {
- expect(thumbBox(exactView(100000, 99976, 99976, 24), 300)!.heightPx).toBe(
- MIN_THUMB_PX,
- );
- });
-
- it("draws nothing without a view or a measured track", () => {
- expect(thumbBox(null, 300)).toBeNull();
- expect(thumbBox(exactView(1000, 976, 0, 24), 0)).toBeNull();
- });
-});
-
-describe("backAtThumbTop", () => {
- it("round-trips the position the thumb is drawn at", () => {
- const view = exactView(1000, 976, 776, 24);
- const box = thumbBox(view, 300)!;
- expect(backAtThumbTop(box.topPx, 300, view)).toBeCloseTo(view.back, -1);
- });
-
- it("maps the track's ends to the history's ends", () => {
- const view = exactView(1000, 976, 776, 24);
- expect(backAtThumbTop(0, 300, view)).toBe(976);
- expect(backAtThumbTop(10000, 300, view)).toBe(0);
- });
-});
-
-describe("notchesFor", () => {
- it("converts lines to whole notches", () => {
- expect(notchesFor(LINES_PER_NOTCH * 4)).toBe(4);
- expect(notchesFor(-LINES_PER_NOTCH * 4)).toBe(-4);
- expect(notchesFor(LINES_PER_NOTCH - 1)).toBe(0);
- });
-
- it("caps a single step so a fast drag cannot flood the pty", () => {
- expect(notchesFor(1000000)).toBe(MAX_NOTCHES_PER_STEP);
- expect(notchesFor(-1000000)).toBe(-MAX_NOTCHES_PER_STEP);
- });
-});
-
-describe("wheelTravel", () => {
- it("counts a turn away from the hand as travelling back", () => {
- const t = wheelTravel(freshTravel(), -1, 1000);
- expect(t.travelled).toBe(LINES_PER_NOTCH);
- expect(t.pendingUp).toBe(LINES_PER_NOTCH);
- expect(wheelTravel(t, 1, 1001).travelled).toBe(0);
- });
-
- it("counts every report of one turn, not the turn", () => {
- // A physical wheel covers several rows, and xterm sends one report per
- // row — taking the whole turn for a single notch under-counted every
- // real scroll five-fold and left the thumb near a bottom it had left.
- const t = wheelTravel(freshTravel(), -6, 1000);
- expect(t.travelled).toBe(6 * LINES_PER_NOTCH);
- expect(wheelTravel(t, 6, 1001).travelled).toBe(0);
- });
-
- it("holds a down pending, so an unanswered one can prove the live end", () => {
- const t = wheelTravel({ ...freshTravel(), travelled: 30 }, 2, 1000);
- expect(t.pendingDown).toBe(2 * LINES_PER_NOTCH);
- expect(t.lastDownAt).toBe(1000);
- // An up in the other direction retracts that claim.
- expect(wheelTravel(t, -1, 1001).pendingDown).toBe(0);
- });
-
- it("clamps at zero however far past the live end the wheel turns", () => {
- let t = wheelTravel(freshTravel(), -1, 0);
- for (let i = 0; i < 10; i += 1) t = wheelTravel(t, 1, i);
- expect(t.travelled).toBe(0);
- });
-
- it("stops counting ups while the top is saturated", () => {
- const saturated: Travel = { ...freshTravel(), travelled: 30, saturated: true };
- expect(wheelTravel(saturated, -1, 0).travelled).toBe(30);
- });
-
- it("a turn towards the live end releases the brake", () => {
- const saturated: Travel = { ...freshTravel(), travelled: 30, saturated: true };
- const t = wheelTravel(saturated, 1, 0);
- expect(t.saturated).toBe(false);
- expect(t.travelled).toBe(27);
- });
-
- it("ignores a turn that moved nothing", () => {
- const t: Travel = { ...freshTravel(), travelled: 6 };
- expect(wheelTravel(t, 0, 0)).toBe(t);
- expect(wheelTravel(t, Number.NaN, 0)).toBe(t);
- });
-});
-
-describe("screenTravel", () => {
- const standing = (travelled: number): Travel => ({
- ...freshTravel(),
- travelled,
- fingerprint: "same",
- });
-
- it("keeps the estimate when the screen cannot be read", () => {
- const t = standing(60);
- expect(screenTravel(t, null, 0)).toBe(t);
- });
-
- it("confirms pending notches when the transcript moved", () => {
- const t: Travel = {
- ...standing(60),
- pendingUp: 30,
- lastUpAt: 0,
- pendingDown: 9,
- lastDownAt: 0,
- };
- const next = screenTravel(t, { fingerprint: "moved" }, 1);
- expect(next.travelled).toBe(60);
- expect(next.pendingUp).toBe(0);
- expect(next.pendingDown).toBe(0);
- expect(next.saturated).toBe(false);
- });
-
- it("un-counts ups the application ignored at the top, and measures it", () => {
- // Scrolling past a top nobody can see: the notches emit no bytes at all,
- // so only the unchanged screen can tell.
- const t: Travel = {
- ...standing(90),
- pendingUp: 30,
- lastUpAt: 0,
- moved: true,
- };
- const next = screenTravel(t, { fingerprint: "same" }, SETTLE_MS);
- expect(next.travelled).toBe(60);
- expect(next.saturated).toBe(true);
- expect(next.ceiling).toBe(60);
- });
-
- it("re-anchors at the live end when downs stop changing the screen", () => {
- // The word-agnostic replacement for one CLI's English overlay: a down the
- // application had nothing left to answer with means the newest output is
- // already on screen, in whatever language it happens to be printed.
- const t: Travel = {
- ...standing(42),
- pendingDown: 9,
- lastDownAt: 0,
- moved: true,
- };
- const next = screenTravel(t, { fingerprint: "same" }, SETTLE_MS);
- expect(next.travelled).toBe(0);
- expect(next.pendingDown).toBe(0);
- // The episode closes: the next one has to prove movement afresh.
- expect(next.moved).toBe(false);
- });
-
- it("waits for the pty before judging an unmoved screen", () => {
- const up: Travel = {
- ...standing(90),
- pendingUp: 30,
- lastUpAt: 0,
- moved: true,
- };
- expect(screenTravel(up, { fingerprint: "same" }, SETTLE_MS - 1)).toBe(up);
- const down: Travel = {
- ...standing(90),
- pendingDown: 9,
- lastDownAt: 0,
- moved: true,
- };
- expect(screenTravel(down, { fingerprint: "same" }, SETTLE_MS - 1)).toBe(
- down,
- );
- });
-
- it("never calls an episode that has not moved a top", () => {
- // The pinned-thumb deadlock: a busy CLI leaves the screen unchanged far
- // past the settle window without a single notch having reached the top.
- // The ups still leave the count, but no brake and no false ceiling.
- const t: Travel = { ...standing(30), pendingUp: 30, lastUpAt: 0 };
- const next = screenTravel(t, { fingerprint: "same" }, SETTLE_MS);
- expect(next.travelled).toBe(0);
- expect(next.saturated).toBe(false);
- expect(next.ceiling).toBeNull();
- });
-
- it("never calls an episode that has not moved the live end either", () => {
- // Same deadlock, mirrored: a busy CLI must not be able to claim the pane
- // is at its newest output while the user is reading its history.
- const t: Travel = { ...standing(60), pendingDown: 9, lastDownAt: 0 };
- const next = screenTravel(t, { fingerprint: "same" }, SETTLE_MS);
- expect(next.travelled).toBe(60);
- expect(next.pendingDown).toBe(0);
- });
-
- it("a fingerprint CHANGE proves movement; the first look only records", () => {
- const first = screenTravel(freshTravel(), { fingerprint: "a" }, 0);
- expect(first.moved).toBe(false);
- const second = screenTravel(first, { fingerprint: "b" }, 1);
- expect(second.moved).toBe(true);
- });
-
- it("holds its ground while a scrolled-back pane keeps repainting", () => {
- // The reported bug, at model level: the count used to snap to zero on
- // every repaint that carried no known overlay string, so a pane parked at
- // the TOP of its transcript drew its thumb at the very bottom.
- let t: Travel = { ...standing(300), moved: true };
- for (let i = 0; i < 20; i += 1) {
- t = screenTravel(t, { fingerprint: `agent still talking ${i}` }, i);
- }
- expect(t.travelled).toBe(300);
- });
-
- it("keeps the ceiling graspable however small the measured top", () => {
- const t: Travel = {
- ...standing(3),
- pendingUp: 3,
- lastUpAt: 0,
- moved: true,
- };
- const next = screenTravel(t, { fingerprint: "same" }, SETTLE_MS);
- expect(next.ceiling).toBeGreaterThanOrEqual(LINES_PER_NOTCH);
- });
-});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.ts b/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.ts
deleted file mode 100644
index 929b63dc42..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.ts
+++ /dev/null
@@ -1,371 +0,0 @@
-/**
- * The arithmetic behind a pane's drag scrollbar — no DOM, no xterm, no timers.
- *
- * A pane runs one of two kinds of program, and the bar has to be honest about
- * which one it is standing on:
- *
- * * **`exact`** — the terminal owns the history. A CLI that prints line by
- * line (Codex, a plain shell) leaves everything in xterm's scrollback, and
- * every number here is read straight off that buffer. The thumb is a map.
- * * **`travel`** — the application owns the screen. A full-screen CLI
- * (Claude Code, Gemini, OpenCode and Kimi all take the alternate buffer and
- * the mouse within milliseconds of starting) keeps its transcript in its own
- * process, where nothing about it can be observed from the outside. The only
- * true statements available are "you are at the live end" and "you have
- * scrolled N lines away from it", so that is all the thumb says: it rests at
- * the bottom on the newest output, climbs with the distance travelled, and
- * assumes {@link ASSUMED_SCREENS} screens of history until the top has
- * actually been measured, so there is always somewhere left to go.
- *
- * ## Nothing here reads the application's words
- *
- * An earlier generation anchored "you are at the live end" on Claude Code's
- * `Jump to bottom (ctrl+End)` overlay: absence of that string was taken as
- * proof of the live end. It broke twice over. Claude Code paints a SECOND
- * overlay once output arrives while the view is parked (`1 new message
- * (ctrl+End)`), so the regex missed and the bar snapped to the bottom on every
- * repaint of a pane that was in fact at the very top — and no other CLI ever
- * paints either string, so for all of them the count was unanchored forever.
- * That is AP-27 in a second place: a verdict gated on transcript CONTENT is a
- * verdict that fails for every wording and every language it did not foresee.
- *
- * What replaces it are two symmetric brakes that read only whether the screen
- * MOVED, never what it says:
- *
- * 1. **The top brake.** Up-notches whose repaint never arrives (the transcript
- * region unchanged once the pty had time to answer) were ignored by the
- * application: they are un-counted, and further ups are neither counted nor
- * relayed until the screen moves again. The top stops being scrollable
- * forever. The total travel is then KNOWN, so the thumb maps the real span
- * ({@link Travel.ceiling}) — top means top.
- * 2. **The bottom brake.** Down-notches that likewise change nothing mean the
- * newest output is already on screen: the count re-anchors at zero. This is
- * the live-end anchor, and it works for a CLI in any language.
- *
- * Both brakes require having SEEN the transcript move earlier in the same
- * scroll-back episode ({@link Travel.moved}): a busy CLI can leave the screen
- * unchanged long past {@link SETTLE_MS} without any boundary being involved,
- * and a verdict measured from that once pinned a pane's thumb for good.
- * Judging nothing, a brake merely keeps the old estimate — this module fails
- * open by design.
- */
-
-/** Lines one relayed wheel notch moves a full-screen CLI (measured: ~3). */
-export const LINES_PER_NOTCH = 3;
-
-/** A thumb shorter than this cannot be grabbed in a tall pane. */
-export const MIN_THUMB_PX = 24;
-
-/**
- * The most notches one drag step may relay at once.
- *
- * A fast drag across a long history asks for hundreds of lines in a single
- * pointer move. The application answers each notch individually, so a burst
- * without a ceiling floods the pty with mouse reports it will spend seconds
- * working through — long after the hand has stopped. The next move sends the
- * remainder anyway, because each step is computed against what has actually
- * been relayed so far, and the drag's release sends whatever a capped burst
- * still owes. Kept small also to bound how far a burst can overrun the
- * transcript's top before the top brake can see it.
- */
-export const MAX_NOTCHES_PER_STEP = 30;
-
-/**
- * Screens of history a `travel` pane assumes above an unmeasured transcript.
- *
- * Nothing can be read about a full-screen CLI's history until the top has been
- * hit, so this number alone decides how big the thumb looks on a pane at its
- * live end. One screen made the thumb fill HALF the track — a bar that size
- * claims the pane holds two screens in total, which no working agent ever
- * does, and it is what the maintainer reported as "far too big". Four keeps it
- * a fifth of the track: unmistakably a scrollbar, without inventing a history
- * length nobody measured. Once the top HAS been reached the real span replaces
- * it ({@link Travel.ceiling}).
- */
-export const ASSUMED_SCREENS = 4;
-
-/** What a pane can scroll right now, in lines. */
-export interface ScrollView {
- /** How the numbers were obtained — see the file header. */
- kind: "exact" | "travel";
- /** Lines of history above the current screen. */
- above: number;
- /** Lines the view stands back from the live end; 0 = newest output. */
- back: number;
- /** Lines on screen at once. */
- rows: number;
-}
-
-/** Thumb box inside a track of known height, in px from the track's top. */
-export interface ThumbBox {
- topPx: number;
- heightPx: number;
-}
-
-/**
- * Clamp with a hard rule about garbage: these values come from pointer
- * coordinates and third-party terminal fields, and a single NaN that gets
- * through moves a pane to nowhere. Anything non-finite becomes the low bound.
- */
-function clamp(value: number, low: number, high: number): number {
- if (!Number.isFinite(value)) return low;
- return value < low ? low : value > high ? high : value;
-}
-
-/**
- * The view of a pane whose terminal owns the scrollback — xterm's own numbers.
- *
- * `length` is the buffer's total line count, `baseY` the top line of the
- * newest screen, `viewportY` the top line currently shown.
- */
-export function exactView(
- length: number,
- baseY: number,
- viewportY: number,
- rows: number,
-): ScrollView {
- const above = Math.max(0, length - rows);
- return {
- kind: "exact",
- above,
- back: clamp(baseY - viewportY, 0, above),
- rows,
- };
-}
-
-/**
- * The view of a pane whose application owns the screen.
- *
- * With the top never reached, the span is the distance travelled plus the
- * assumed headroom, so there is always somewhere left to go. Once the top HAS
- * been reached the total is known ({@link Travel.ceiling}) and the span is
- * that measurement — the thumb can then genuinely say "top".
- */
-export function travelView(
- travelled: number,
- rows: number,
- ceiling: number | null = null,
-): ScrollView {
- const back = Math.max(0, Math.round(travelled));
- const above =
- ceiling === null
- ? back + Math.max(1, rows) * ASSUMED_SCREENS
- : Math.max(back, ceiling);
- return { kind: "travel", above, back, rows };
-}
-
-// ---------------------------------------------------------------- travel
-
-/**
- * How long the pty gets to answer a relayed notch before an unchanged screen
- * counts as proof the notch fell off an end. The CLI answers a notch in
- * 1–30 ms when idle (measured), but a CLI mid-task plus a loaded render
- * loop can stretch far past that — and a wrong verdict here once pinned a
- * pane's thumb to a false top (2026-07-28). Hence the generous window AND
- * the `moved` requirement in {@link screenTravel}.
- */
-export const SETTLE_MS = 500;
-
-/** What a full-screen CLI's pane knows about where it stands. */
-export interface Travel {
- /** Best estimate of lines back from the live end. */
- travelled: number;
- /** Total travel measured at the transcript's top, once reached. */
- ceiling: number | null;
- /** Up-lines counted but not yet confirmed by a repaint. */
- pendingUp: number;
- /** When the newest unconfirmed up was counted. */
- lastUpAt: number;
- /** Down-lines counted but not yet confirmed by a repaint. */
- pendingDown: number;
- /** When the newest unconfirmed down was counted. */
- lastDownAt: number;
- /** The transcript region's last known content, for the brakes. */
- fingerprint: string | null;
- /** Ups are known to be falling off the top right now. */
- saturated: boolean;
- /**
- * The transcript has been SEEN to move during this scroll-back episode.
- *
- * Both brakes' precondition, and the fix for the pinned-thumb deadlock: a
- * busy CLI can leave the screen unchanged long past {@link SETTLE_MS}
- * without a single notch having fallen off an end. Genuinely reaching a
- * boundary requires having scrolled through content first, which repaints
- * — so an episode that never moved proves latency, not a boundary, and
- * must neither saturate nor measure a ceiling nor claim the live end.
- */
- moved: boolean;
-}
-
-export function freshTravel(): Travel {
- return {
- travelled: 0,
- ceiling: null,
- pendingUp: 0,
- lastUpAt: 0,
- pendingDown: 0,
- lastDownAt: 0,
- fingerprint: null,
- saturated: false,
- moved: false,
- };
-}
-
-/** What one look at the screen saw — see {@link readScreen} in the component. */
-export interface ScreenGlance {
- /** Content of the transcript region, excluding the self-animating chrome. */
- fingerprint: string;
-}
-
-/**
- * The count after one observed wheel event, real or relayed alike.
- *
- * `notches` is signed the way a wheel's `deltaY` is — POSITIVE towards the
- * live end (the hand pulled towards itself), negative into the history — and
- * counts the mouse reports the terminal will actually send, not the DOM
- * events. One physical wheel turn is several reports, and counting it as one
- * was a systematic five-fold under-count of every real scroll.
- */
-export function wheelTravel(
- travel: Travel,
- notches: number,
- now: number,
-): Travel {
- if (!Number.isFinite(notches) || Math.trunc(notches) === 0) return travel;
- const lines = Math.abs(Math.trunc(notches)) * LINES_PER_NOTCH;
- if (notches > 0) {
- // Towards the live end: a down always has somewhere to go while the
- // count is positive, and leaving the top ends the saturation. The lines
- // stay pending until a repaint confirms them — an unanswered down is how
- // the bottom brake learns the newest output is already on screen.
- return {
- ...travel,
- travelled: Math.max(0, travel.travelled - lines),
- pendingUp: 0,
- saturated: false,
- pendingDown: travel.pendingDown + lines,
- lastDownAt: now,
- };
- }
- // Away from the live end. While saturated these are known to be ignored by
- // the application — counting them is exactly the inflation this fixes.
- if (travel.saturated) return travel;
- return {
- ...travel,
- travelled: travel.travelled + lines,
- pendingUp: travel.pendingUp + lines,
- lastUpAt: now,
- pendingDown: 0,
- };
-}
-
-/**
- * Reconcile the count with what the screen actually shows.
- *
- * `glance` is null when the screen could not be read — the estimate then
- * simply stands, which is the fail-open this module owes its history.
- */
-export function screenTravel(
- travel: Travel,
- glance: ScreenGlance | null,
- now: number,
-): Travel {
- if (!glance) return travel;
-
- if (travel.fingerprint !== glance.fingerprint) {
- // The transcript moved: whatever was pending has been answered. Only a
- // CHANGE proves movement — the episode's first look merely records.
- return {
- ...travel,
- fingerprint: glance.fingerprint,
- pendingUp: 0,
- pendingDown: 0,
- saturated: false,
- moved: travel.moved || travel.fingerprint !== null,
- };
- }
-
- // The screen stood still. Whichever direction was asked for and not
- // answered has run into that end of the transcript — provided this episode
- // has scrolled at all (see Travel.moved).
- if (travel.pendingUp > 0 && now - travel.lastUpAt >= SETTLE_MS) {
- // Counted ups, an answered pty, an unmoved screen: those notches did
- // nothing, so they leave the count either way. But they only prove a TOP
- // when this episode has scrolled before — an episode that never moved is
- // a busy CLI, and a ceiling measured from it pinned a pane's thumb to a
- // false top with every further relay refused (2026-07-28).
- const travelled = Math.max(0, travel.travelled - travel.pendingUp);
- return travel.moved
- ? {
- ...travel,
- travelled,
- pendingUp: 0,
- saturated: true,
- ceiling: Math.max(travelled, LINES_PER_NOTCH),
- }
- : { ...travel, travelled, pendingUp: 0 };
- }
-
- if (travel.pendingDown > 0 && now - travel.lastDownAt >= SETTLE_MS) {
- if (!travel.moved) return { ...travel, pendingDown: 0 };
- // Downs the application had nothing left to answer with: the newest
- // output is on screen. This is the live-end anchor — the one that used to
- // be a hardcoded English string — and it also closes the episode, so the
- // next one has to prove movement afresh.
- return {
- ...travel,
- travelled: 0,
- pendingDown: 0,
- saturated: false,
- fingerprint: null,
- moved: false,
- };
- }
-
- return travel;
-}
-
-/** Is there anywhere for this pane to go? */
-export function hasScroll(view: ScrollView | null): boolean {
- return Boolean(view && view.above > 0 && view.rows > 0);
-}
-
-/** Where the thumb sits in a `trackPx`-tall track; null when there is no bar. */
-export function thumbBox(
- view: ScrollView | null,
- trackPx: number,
-): ThumbBox | null {
- if (!view || !hasScroll(view) || trackPx <= 0) return null;
- const total = view.above + view.rows;
- const heightPx = clamp(
- Math.round((trackPx * view.rows) / total),
- Math.min(MIN_THUMB_PX, trackPx),
- trackPx,
- );
- // 0 back = live end = thumb at the very bottom of the track.
- const away = clamp(view.back / view.above, 0, 1);
- return { heightPx, topPx: Math.round((trackPx - heightPx) * (1 - away)) };
-}
-
-/** How far back a thumb whose top edge is at `topPx` is asking to be. */
-export function backAtThumbTop(
- topPx: number,
- trackPx: number,
- view: ScrollView | null,
-): number {
- const box = thumbBox(view, trackPx);
- if (!box || !view) return 0;
- const travel = trackPx - box.heightPx;
- if (travel <= 0) return view.back;
- const away = 1 - clamp(topPx / travel, 0, 1);
- return Math.round(away * view.above);
-}
-
-/**
- * Whole notches that carry an application `lines` further back (negative:
- * towards the live end), capped per step — see {@link MAX_NOTCHES_PER_STEP}.
- */
-export function notchesFor(lines: number): number {
- const whole = Math.trunc(lines / LINES_PER_NOTCH);
- return clamp(whole, -MAX_NOTCHES_PER_STEP, MAX_NOTCHES_PER_STEP);
-}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts
new file mode 100644
index 0000000000..b03ecce6c4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts
@@ -0,0 +1,91 @@
+import type { Terminal } from "@xterm/xterm";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import {
+ bindTerminalScrollSurface,
+ terminalScrollOwner,
+} from "./terminalScrollSurface";
+
+function write(term: Terminal, data: string): Promise<void> {
+ return new Promise((resolve) => term.write(data, resolve));
+}
+
+let restoreCanvasContext: (() => void) | undefined;
+
+beforeAll(() => {
+ // xterm probes canvas colour support at module load. Parsing terminal modes
+ // needs no renderer, so a null context is the faithful jsdom capability.
+ const canvasContext = vi
+ .spyOn(HTMLCanvasElement.prototype, "getContext")
+ .mockImplementation(() => null);
+ restoreCanvasContext = () => canvasContext.mockRestore();
+});
+
+afterAll(() => restoreCanvasContext?.());
+
+async function newTerminal(): Promise<Terminal> {
+ const { Terminal: XtermTerminal } = await import("@xterm/xterm");
+ return new XtermTerminal({ allowProposedApi: true });
+}
+
+describe("terminalScrollSurface", () => {
+ it("uses the real xterm parser to distinguish scrollback from a TUI", async () => {
+ const term = await newTerminal();
+ const host = document.createElement("div");
+ const dispose = bindTerminalScrollSurface(host, term);
+ try {
+ expect(terminalScrollOwner(term)).toBe("terminal");
+ expect(host.dataset.scrollOwner).toBe("terminal");
+
+ await write(
+ term,
+ "\x1b[?1049h\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h",
+ );
+
+ expect(term.buffer.active.type).toBe("alternate");
+ expect(term.modes.mouseTrackingMode).toBe("any");
+ expect(host.dataset.scrollOwner).toBe("application");
+
+ await write(
+ term,
+ "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1049l",
+ );
+
+ expect(term.buffer.active.type).toBe("normal");
+ expect(term.modes.mouseTrackingMode).toBe("none");
+ expect(host.dataset.scrollOwner).toBe("terminal");
+ } finally {
+ dispose();
+ term.dispose();
+ }
+ });
+
+ it("lets the terminal receive a wheel but contains the workspace scroll", async () => {
+ const parent = document.createElement("div");
+ const host = document.createElement("div");
+ const xterm = document.createElement("div");
+ parent.append(host);
+ host.append(xterm);
+ const term = await newTerminal();
+ const xtermWheel = vi.fn();
+ const workspaceWheel = vi.fn();
+ xterm.addEventListener("wheel", xtermWheel);
+ parent.addEventListener("wheel", workspaceWheel);
+ const dispose = bindTerminalScrollSurface(host, term);
+ try {
+ const accepted = xterm.dispatchEvent(
+ new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ deltaY: 120,
+ }),
+ );
+
+ expect(xtermWheel).toHaveBeenCalledOnce();
+ expect(workspaceWheel).not.toHaveBeenCalled();
+ expect(accepted).toBe(false);
+ } finally {
+ dispose();
+ term.dispose();
+ }
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts
new file mode 100644
index 0000000000..c957d504ea
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts
@@ -0,0 +1,60 @@
+/**
+ * Keep terminal scrolling on the side that actually owns it.
+ *
+ * A normal xterm buffer has exact, browser-scrollable history. A full-screen
+ * application takes the alternate buffer and/or mouse reporting, so xterm must
+ * relay the wheel to that application and an xterm scrollbar would be inert.
+ * The host's `data-scroll-owner` lets CSS expose the native bar only for the
+ * first case. No position is guessed for the second case.
+ */
+import type { Terminal } from "@xterm/xterm";
+
+export type TerminalScrollOwner = "terminal" | "application";
+
+export function terminalScrollOwner(term: Terminal): TerminalScrollOwner {
+ // The public fields exist in xterm 5.5. Optional reads keep older test
+ // doubles and a partially constructed terminal on the safe native path.
+ const tracking = term.modes?.mouseTrackingMode ?? "none";
+ const bufferType = term.buffer?.active?.type ?? "normal";
+ return bufferType === "alternate" || tracking !== "none"
+ ? "application"
+ : "terminal";
+}
+
+/**
+ * Synchronize the host marker and keep a terminal wheel from falling through
+ * to the workspace scroller after xterm has had its chance to handle it.
+ */
+export function bindTerminalScrollSurface(
+ host: HTMLElement,
+ term: Terminal,
+): () => void {
+ let owner: TerminalScrollOwner | null = null;
+ const syncOwner = () => {
+ const next = terminalScrollOwner(term);
+ if (next === owner) return;
+ owner = next;
+ host.dataset.scrollOwner = next;
+ };
+
+ // This listener is on xterm's PARENT. The event reaches xterm first; only
+ // afterwards is its unused browser default contained here, so the terminal
+ // keeps every native wheel/mouse behavior and the workspace does not move too.
+ const containWheel = (event: WheelEvent) => {
+ event.stopPropagation();
+ if (!event.defaultPrevented) event.preventDefault();
+ };
+
+ syncOwner();
+ host.addEventListener("wheel", containWheel, { passive: false });
+ const subscriptions = [
+ term.onWriteParsed?.(syncOwner),
+ term.buffer?.onBufferChange?.(syncOwner),
+ ];
+
+ return () => {
+ host.removeEventListener("wheel", containWheel);
+ for (const subscription of subscriptions) subscription?.dispose();
+ delete host.dataset.scrollOwner;
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.css
index f50c1afee0..db4458fb4c 100644
--- a/jarvis/ui/web/frontend/src/index.css
+++ b/jarvis/ui/web/frontend/src/index.css
@@ -11,8 +11,7 @@
it reads as somebody else's chrome bolted onto a matte-black app, and it
was the single loudest non-theme surface left on screen. This makes every
scroll container in the app agree: a thin dark thumb floating on the
- content, no track, no buttons. Individual surfaces still opt out
- (.agentic-terminal-host below, PaneScrollbar) — a class beats `*`. */
+ content, no track, no buttons. */
* {
scrollbar-width: thin;
scrollbar-color: hsl(var(--border)) transparent;
@@ -66,23 +65,22 @@
display: none;
}
-/* Agentic IDE panes never show the BROWSER's scroll track. It is permanently
- on screen down the side of every pane in the grid, and it is powered by the
- xterm viewport, which a full-screen CLI like Claude Code leaves empty
- because it runs on the alternate screen and keeps its history in its own
- process. The pane draws its own hover-only bar instead (PaneScrollbar),
- which can also drive a full-screen CLI; the wheel keeps reaching whichever
- side owns the screen either way.
-
- Hiding it here rather than switching the viewport to `overflow: hidden` is
- deliberate: xterm still needs a scrollable viewport for the wheel itself.
- Keep this top-level — xterm creates the viewport at runtime, so Tailwind
- would purge a rule for it out of an @layer. */
+/* Agentic IDE scroll ownership is explicit. A normal xterm buffer exposes its
+ exact native scrollback. A full-screen application owns the alternate
+ buffer and mouse wheel, so its inert browser track is hidden while xterm
+ continues relaying wheel reports to the application. `data-scroll-owner`
+ is synchronized in terminalScrollSurface.ts from xterm's real parser state.
+ Keep these rules top-level because xterm creates the viewport at runtime. */
.agentic-terminal-host .xterm-viewport {
+ overscroll-behavior: contain;
+}
+
+.agentic-terminal-host[data-scroll-owner="application"] .xterm-viewport {
scrollbar-width: none;
}
-.agentic-terminal-host .xterm-viewport::-webkit-scrollbar {
+.agentic-terminal-host[data-scroll-owner="application"]
+ .xterm-viewport::-webkit-scrollbar {
width: 0;
height: 0;
}
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 3eaa30bf51..a69c0a85b6 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -842,32 +842,6 @@ export async function moveTerminal(
return body.state.session;
}
-/**
- * Give one pane another call-sign.
- *
- * Nothing is started or stopped — the agent keeps working and keeps its
- * conversation. The pane simply answers to a different name afterwards, in the
- * header, in a spoken instruction, and in every route that takes a name.
- */
-export async function renameTerminal(
- name: string,
- newName: string,
-): Promise<SessionState> {
- const res = await fetch(
- `/api/agentic-ide/terminals/${encodeURIComponent(name)}`,
- {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: newName }),
- },
- );
- if (!res.ok) throw new Error(await detail(res));
- const body = (await res.json()) as { state: IdeState };
- if (!body.state.session)
- throw new Error("The workspace closed while renaming a terminal.");
- return body.state.session;
-}
-
/** Stop one terminal's agent and remove its pane. Returns the updated workspace. */
export async function closeTerminal(name: string): Promise<SessionState> {
const res = await fetch(
diff --git a/tests/unit/agentic_ide/test_pane_notifications.py b/tests/unit/agentic_ide/test_pane_notifications.py
index 8679b0fe10..77a1dbea9e 100644
--- a/tests/unit/agentic_ide/test_pane_notifications.py
+++ b/tests/unit/agentic_ide/test_pane_notifications.py
@@ -312,16 +312,13 @@ async def test_a_real_pane_finishing_files_one_entry(registry: Registry, tmp_pat
# ------------------------------------------------------------------- reading
-async def test_the_interrupt_hint_is_what_marks_a_pane_busy(
- registry: Registry, tmp_path: Path
-) -> None:
- """The one signal every coding TUI draws while — and only while — it works."""
- _session, term = await _pane(registry, tmp_path)
-
- _draw(term, BUSY_SCREEN)
- assert read_activity(term) == "working"
-
-
+# There is deliberately no test here that a BUSY-looking screen reads as
+# working: that is the rule the rewrite removed, and it is pinned the other way
+# round by `test_movement_is_the_only_thing_that_counts` above. The one that
+# used to sit here asserted it, and passed for a reason that had nothing to do
+# with its name — attaching a pane stamped `last_output_at` with the wall clock,
+# so the fallback in `_moving` called every freshly-attached pane busy no matter
+# what was on its screen. Fixing that stamp is what exposed it.
async def test_a_pane_at_its_prompt_reads_as_waiting(registry: Registry, tmp_path: Path) -> None:
_session, term = await _pane(registry, tmp_path)
diff --git a/tests/unit/agentic_ide/test_pane_rename.py b/tests/unit/agentic_ide/test_pane_rename.py
deleted file mode 100644
index 7ae248b4f4..0000000000
--- a/tests/unit/agentic_ide/test_pane_rename.py
+++ /dev/null
@@ -1,190 +0,0 @@
-"""Giving a running pane another call-sign.
-
-A rename touches one string and must touch nothing else — that is the entire
-contract, and every test here is a way of failing it. The pane's key is what
-its running pseudo-terminal is filed under, so a rename that moved the key
-would take the agent away from the viewer; the call-sign is what a spoken
-instruction resolves against, so a rename that left the OLD name answering
-would silently split one pane into two addresses.
-"""
-from __future__ import annotations
-
-from pathlib import Path
-
-import pytest
-
-from jarvis.agentic_ide import resume_store
-from jarvis.agentic_ide import session as session_mod
-from jarvis.agentic_ide.session import MAX_TERMINAL_NAME, Registry, SessionError
-from tests.fakes.fake_pty_manager import FakePtyManager
-
-
[email protected](autouse=True)
-def _isolated_recents(
- tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """Keep the recents file out of the developer's real data directory."""
- from jarvis.agentic_ide import recents
-
- store = tmp_path_factory.mktemp("recents") / "recents.json"
- monkeypatch.setattr(recents, "_store_path", lambda: store)
-
-
-def fake_pty() -> FakePtyManager:
- return FakePtyManager()
-
-
-def registry(fake_pty: FakePtyManager, monkeypatch: pytest.MonkeyPatch) -> Registry:
- monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))
- return Registry(pty_manager=fake_pty)
-
-
-async def _open(registry: Registry, folder: Path, count: int = 2):
- return await registry.start(str(folder), [{"agent": "claude"} for _ in range(count)])
-
-
-# ------------------------------------------------------------------ the rename
-async def test_renaming_changes_the_call_sign_and_nothing_else(
- registry: Registry, tmp_path: Path
-) -> None:
- """The label moves; the pane's identity, place and agent stay put."""
- await _open(registry, tmp_path, 2)
- before = registry.session.terminals[0]
- key, column, slot, agent = before.key, before.column, before.slot, before.agent
-
- _, term = await registry.rename_terminal("T1", "Frontend")
-
- assert term.name == "Frontend"
- assert (term.key, term.column, term.slot, term.agent) == (key, column, slot, agent)
- assert [t.name for t in registry.session.terminals] == ["Frontend", "T2"]
-
-
-async def test_the_pane_answers_to_its_new_name(
- registry: Registry, tmp_path: Path
-) -> None:
- """A rename is only real if the next instruction reaches the pane by it."""
- await _open(registry, tmp_path, 2)
- await registry.rename_terminal("T1", "Frontend")
-
- found = registry.find_terminal("Frontend")
- assert found is not None
- assert found[1].key == registry.session.terminals[0].key
-
-
-async def test_a_freed_call_sign_goes_to_the_next_pane_that_asks_for_it(
- registry: Registry, tmp_path: Path
-) -> None:
- """T1 renamed frees T1 — and the pane that takes it is the one T1 means.
-
- The renamed pane keeps the key ``t1`` (its pseudo-terminal is filed under
- it), so this is precisely where a key-first lookup would hand "T1" back to
- the pane the user renamed to stop it being T1.
- """
- await _open(registry, tmp_path, 1)
- await registry.rename_terminal("T1", "Frontend")
- fresh = await registry.add_terminal(direction="right")
-
- assert fresh.name == "T1"
- found = registry.find_terminal("T1")
- assert found is not None
- assert found[1].key == fresh.key
-
-
-async def test_renaming_never_touches_the_running_agent(
- registry: Registry, tmp_path: Path, fake_pty: FakePtyManager
-) -> None:
- """No pane is closed, no process is spawned — that is what makes it safe."""
- await _open(registry, tmp_path, 2)
- spawns = len(fake_pty.spawns)
- closed = len(fake_pty.closed)
-
- await registry.rename_terminal("T2", "Tests")
-
- assert len(fake_pty.spawns) == spawns
- assert len(fake_pty.closed) == closed
-
-
-async def test_renaming_to_the_same_name_is_a_no_op(
- registry: Registry, tmp_path: Path
-) -> None:
- """Opening the editor and pressing Save unchanged is not an error."""
- await _open(registry, tmp_path, 1)
- _, term = await registry.rename_terminal("T1", "T1")
- assert term.name == "T1"
-
-
-async def test_surrounding_whitespace_is_cleaned_up(
- registry: Registry, tmp_path: Path
-) -> None:
- """A pasted name arrives with spaces; the pane must not be called ' Api '."""
- await _open(registry, tmp_path, 1)
- _, term = await registry.rename_terminal("T1", " Api layer ")
- assert term.name == "Api layer"
-
-
-# ------------------------------------------------------------------- refusals
-async def test_a_name_another_pane_already_carries_is_refused(
- registry: Registry, tmp_path: Path
-) -> None:
- """Two panes on one call-sign make every spoken instruction a coin flip."""
- await _open(registry, tmp_path, 2)
- await registry.rename_terminal("T1", "Frontend")
-
- with pytest.raises(SessionError, match="already called"):
- await registry.rename_terminal("T2", "frontend")
-
- assert [t.name for t in registry.session.terminals] == ["Frontend", "T2"]
-
-
-async def test_an_empty_name_is_refused(registry: Registry, tmp_path: Path) -> None:
- await _open(registry, tmp_path, 1)
- with pytest.raises(SessionError, match="Give the terminal a name"):
- await registry.rename_terminal("T1", " ")
-
-
-async def test_a_name_with_nothing_to_match_on_is_refused(
- registry: Registry, tmp_path: Path
-) -> None:
- """Punctuation normalizes to nothing, leaving a pane nobody can address."""
- await _open(registry, tmp_path, 1)
- with pytest.raises(SessionError, match="letters or numbers"):
- await registry.rename_terminal("T1", "!!! ---")
- assert registry.session.terminals[0].name == "T1"
-
-
-async def test_an_overlong_name_is_refused(registry: Registry, tmp_path: Path) -> None:
- await _open(registry, tmp_path, 1)
- with pytest.raises(SessionError, match="at most"):
- await registry.rename_terminal("T1", "x" * (MAX_TERMINAL_NAME + 1))
-
-
-async def test_an_unknown_pane_says_which_ones_exist(
- registry: Registry, tmp_path: Path
-) -> None:
- """The error names the running panes — the answer to the question asked."""
- await _open(registry, tmp_path, 2)
- with pytest.raises(SessionError, match="T1, T2"):
- await registry.rename_terminal("T7", "Frontend")
-
-
-# ---------------------------------------------------------------- persistence
-async def test_the_new_name_survives_a_reopen(
- registry: Registry, tmp_path: Path
-) -> None:
- """A pane called "Frontend" today is still Frontend after a restart.
-
- Through the restore snapshot rather than an in-memory copy: the name is
- written where the workspace is remembered, or a rename lasts exactly until
- the app is closed.
- """
- await _open(registry, tmp_path, 2)
- await registry.rename_terminal("T1", "Frontend")
-
- stored = resume_store.load()
- assert stored is not None
- fresh = Registry(pty_manager=FakePtyManager())
- result = await fresh.restore(stored)
-
- assert [t.name for s in result.sessions for t in s.terminals] == ["Frontend", "T2"]
diff --git a/tests/unit/agentic_ide/test_session.py b/tests/unit/agentic_ide/test_session.py
index a6ebc8ac87..8050649266 100644
--- a/tests/unit/agentic_ide/test_session.py
+++ b/tests/unit/agentic_ide/test_session.py
@@ -281,14 +281,12 @@ async def test_coming_back_rejoins_the_running_agent_and_replays_its_screen(
async def _capture(text: str) -> None:
seen.append(text)
- fake_pty.resizes.clear()
- back = await registry.attach(term.name, 80, 24, _capture, _noop_exit)
+ back = await registry.attach(term.name, 100, 30, _capture, _noop_exit)
assert back.pty_id == original_pty, "the same agent process must be re-joined"
assert len(fake_pty.spawns) == spawns_before, "nothing may be respawned"
assert back.reattached is True
assert "building…" in "".join(seen), "the screen must come back with the pane"
- assert fake_pty.resizes == [], "re-joining at the current size must not redraw it"
async def test_a_pane_whose_replay_lost_its_start_asks_the_agent_to_repaint(
@@ -321,37 +319,27 @@ async def test_a_pane_whose_replay_lost_its_start_asks_the_agent_to_repaint(
assert sizes[-1] == (100, 30), "the pane must be left at the size it really is"
-async def test_a_geometry_change_rebases_an_intact_replay_and_repaints(
+async def test_an_intact_replay_leaves_the_agent_alone(
registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
) -> None:
- """Cursor moves recorded at one size must never be replayed at another."""
+ """No nudge when the tail is whole — it already rebuilds the screen.
+
+ The redraw is cheap but not free, and it is the common case that must stay
+ untouched: a pane that printed less than its replay budget comes back from
+ its own bytes.
+ """
session = await _open(registry, tmp_path, [{"agent": "claude"}])
term = session.terminals[0]
await registry.attach(term.name, 80, 24, _noop_output, _noop_exit)
pty = term.pty_id
- await fake_pty.emit(pty, "\x1b[?1049h\x1b[32mOLD STATUS ROW\x1b[0m")
+ await fake_pty.emit(pty, "\x1b[32mbuilding…\x1b[0m")
registry.detach(term.key, session.id)
- replayed: list[str] = []
-
- async def _capture_replay(text: str) -> None:
- replayed.append(text)
-
fake_pty.resizes.clear()
- await registry.attach(
- term.name,
- 100,
- 30,
- _noop_output,
- _noop_exit,
- on_replay=_capture_replay,
- )
+ await registry.attach(term.name, 100, 30, _noop_output, _noop_exit)
sizes = [(cols, rows) for tid, cols, rows in fake_pty.resizes if tid == pty]
- restored = "".join(replayed)
- assert "OLD STATUS ROW" not in restored
- assert "\x1b[?1049h" in restored, "alternate-screen ownership must survive"
- assert sizes == [(100, 30), (100, 29), (100, 30)]
+ assert sizes == [(100, 30)], "an intact replay must not cost a repaint"
async def test_closing_a_workspace_stops_only_its_own_agents(
@@ -548,8 +536,8 @@ async def test_a_displaced_viewer_cannot_resize_the_pane_it_lost(
assert fake_pty.resizes == [], "a displaced viewer must not move the agent's screen"
# The viewer that actually holds the pane still can.
- assert registry.resize(term.key, 201, 50, viewer=second_viewer) is True
- assert fake_pty.resizes == [(term.pty_id, 201, 50)]
+ assert registry.resize(term.key, 200, 50, viewer=second_viewer) is True
+ assert fake_pty.resizes == [(term.pty_id, 200, 50)]
async def test_an_internal_resize_needs_no_viewer(
@@ -566,16 +554,3 @@ async def test_an_internal_resize_needs_no_viewer(
assert registry.resize(term.key, 120, 40) is True
assert fake_pty.resizes == [(term.pty_id, 120, 40)]
-
-
-async def test_a_duplicate_resize_does_not_make_the_tui_repaint(
- registry: Registry, fake_pty: FakePtyManager, tmp_path: Path
-) -> None:
- """The socket handshake already applied this size; its echo is a no-op."""
- await _open(registry, tmp_path, [{"agent": "claude"}])
- await registry.attach("T1", 80, 24, _noop_output, _noop_exit)
- term = registry.session.terminals[0]
- fake_pty.resizes.clear()
-
- assert registry.resize(term.key, 80, 24) is True
- assert fake_pty.resizes == []
diff --git a/tests/unit/agentic_ide/test_transcript.py b/tests/unit/agentic_ide/test_transcript.py
index cf81252585..f050c1f2a9 100644
--- a/tests/unit/agentic_ide/test_transcript.py
+++ b/tests/unit/agentic_ide/test_transcript.py
@@ -264,24 +264,6 @@ def test_an_untruncated_replay_is_still_verbatim() -> None:
assert buffer.text() == stream
-def test_rebasing_for_a_resize_drops_old_drawing_but_preserves_modes() -> None:
- """A TUI stream is geometry-bound; its negotiated terminal state is not."""
- buffer = ReplayBuffer()
- buffer.feed("\x1b[?1049h\x1b[?1006hOLD STATUS ROW")
-
- prologue = buffer.rebase_for_resize()
-
- assert "OLD STATUS ROW" not in prologue
- assert "OLD STATUS ROW" not in buffer.text()
- assert "\x1b[?1049h" in prologue
- assert "\x1b[?1006h" in prologue
- assert prologue.endswith("\x1b[0m")
- assert buffer.truncated is False
-
- buffer.feed("NEW SCREEN")
- assert buffer.text() == prologue + "NEW SCREEN"
-
-
def test_a_replay_forgets_the_modes_when_it_is_cleared() -> None:
buffer = ReplayBuffer(limit=32)
buffer.feed("\x1b[?1049h" + "z" * 100)
diff --git a/tests/unit/web/test_agentic_ide_rename_terminal_route.py b/tests/unit/web/test_agentic_ide_rename_terminal_route.py
deleted file mode 100644
index edcc4b68e4..0000000000
--- a/tests/unit/web/test_agentic_ide_rename_terminal_route.py
+++ /dev/null
@@ -1,89 +0,0 @@
-"""The endpoint behind renaming a pane.
-
-The route itself is thin — the rules live in the registry — so what is pinned
-here is the part a caller depends on: the answer says which pane was renamed
-and what it used to be called, and the two ways it can fail are told apart by
-status code. A duplicate call-sign is something the caller fixes by typing a
-different name (409); a call-sign nobody answers to is a different mistake
-entirely (404), and a UI that cannot distinguish them can only say "it didn't
-work".
-"""
-from __future__ import annotations
-
-from types import SimpleNamespace
-
-import pytest
-from fastapi import HTTPException
-
-from jarvis.agentic_ide.session import SessionError
-from jarvis.ui.web import agentic_ide_routes as routes
-
-
-def _terminal(name: str) -> SimpleNamespace:
- return SimpleNamespace(name=name, to_dict=lambda: {"name": name, "key": "t1"})
-
-
-class FakeRegistry:
- """Registry stand-in: records the call, returns or raises what was scripted."""
-
- def __init__(self, *, result=None, error: SessionError | None = None) -> None:
- self._result = result
- self._error = error
- self.calls: list[tuple[str, str]] = []
-
- async def rename_terminal(self, wanted: str, name: str):
- self.calls.append((wanted, name))
- if self._error is not None:
- raise self._error
- return self._result
-
- def state(self) -> dict:
- return {"active": True}
-
-
-async def test_a_rename_answers_with_both_names(monkeypatch: pytest.MonkeyPatch) -> None:
- """Both, because the caller has UI filed under the OLD one to move across."""
- session = SimpleNamespace(id="ide_test")
- registry = FakeRegistry(result=(session, _terminal("Frontend")))
- monkeypatch.setattr(routes, "get_registry", lambda: registry)
-
- result = await routes.rename_terminal(
- "T1", routes.RenameTerminalRequest(name="Frontend")
- )
-
- assert registry.calls == [("T1", "Frontend")]
- assert result["ok"] is True
- assert result["renamed"] == "Frontend"
- assert result["previous"] == "T1"
- assert result["workspace_id"] == "ide_test"
- assert result["terminal"]["name"] == "Frontend"
- # The whole state travels back, so the grid redraws from this one answer
- # instead of polling for the change it just made.
- assert result["state"] == {"active": True}
-
-
-async def test_a_name_another_pane_carries_is_a_conflict(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- registry = FakeRegistry(
- error=SessionError("Another terminal in this workspace is already called 'Api'.")
- )
- monkeypatch.setattr(routes, "get_registry", lambda: registry)
-
- with pytest.raises(HTTPException) as caught:
- await routes.rename_terminal("T2", routes.RenameTerminalRequest(name="Api"))
-
- assert caught.value.status_code == 409
- assert "already called" in caught.value.detail
-
-
-async def test_an_unknown_pane_is_a_not_found(monkeypatch: pytest.MonkeyPatch) -> None:
- registry = FakeRegistry(error=SessionError("No terminal called 'T7'. Running: T1."))
- monkeypatch.setattr(routes, "get_registry", lambda: registry)
-
- with pytest.raises(HTTPException) as caught:
- await routes.rename_terminal("T7", routes.RenameTerminalRequest(name="Api"))
-
- assert caught.value.status_code == 404
- # The panes that DO exist travel with it — the answer to the question asked.
- assert "Running: T1" in caught.value.detail