Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
refactor(agentic-ide)!: one scrollbar, one truth — xterm owns scrolling everywhere
rubenluetke10-beepef8e4bcbd48b
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsxindex 584aab061b..29a3e80d13 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.test.tsx@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const terminalHarness = vi.hoisted(() => ({open: vi.fn(),+ host: { current: null as HTMLElement | null },observe: vi.fn(),fit: vi.fn(),/** What the terminal reports after a fit — a test moves it to grow the pane. */@@ -15,8 +16,12 @@ const terminalHarness = vi.hoisted(() => ({input: vi.fn<(data: string) => void>(),/** xterm's single custom key handler, so a test can press a key. */keys: { current: null as ((event: KeyboardEvent) => boolean) | null },- /** xterm's wheel arbiter, which bridges a live inline TUI at its tail. */+ /** xterm's wheel arbiter, which keeps the wheel on terminal history. */wheel: { current: null as ((event: WheelEvent) => boolean) | null },+ /** Parser state the wheel arbiter reads — a test flips these directly. */+ modes: { mouseTrackingMode: "none" as "none" | "any" },+ bufferType: "normal" as "normal" | "alternate",+ scrollLines: vi.fn<(amount: number) => void>(),/** Custom CSI observers installed on xterm's parser. */csiHandlers: [] as {id: { prefix?: string; final: string };@@ -25,6 +30,7 @@ const terminalHarness = vi.hoisted(() => ({focus: vi.fn(),scrollToBottom: vi.fn(),write: vi.fn(),+ visibilityAtWrite: [] as string[],deferWrite: false,writeCallbacks: [] as (() => void)[],/**@@ -47,6 +53,17 @@ vi.mock("@xterm/xterm", () => ({get rows() {return terminalHarness.size.rows;}+ get modes() {+ return terminalHarness.modes;+ }+ get buffer() {+ return {+ active: { type: terminalHarness.bufferType, baseY: 0, viewportY: 0 },+ };+ }+ scrollLines(amount: number) {+ terminalHarness.scrollLines(amount);+ }options: Record<string, unknown>;unicode = { activeVersion: "" };@@ -78,6 +95,7 @@ vi.mock("@xterm/xterm", () => ({loadAddon() {}open(host: HTMLElement) {terminalHarness.open(host);+ terminalHarness.host.current = host;}focus() {terminalHarness.focus();@@ -100,6 +118,9 @@ vi.mock("@xterm/xterm", () => ({}write(text: string, callback?: () => void) {terminalHarness.write(text);+ terminalHarness.visibilityAtWrite.push(+ terminalHarness.host.current?.style.visibility ?? "",+ );if (!callback) return;if (terminalHarness.deferWrite) terminalHarness.writeCallbacks.push(callback);else callback();@@ -164,10 +185,15 @@ describe("AgenticTerminal layout", () => {terminalHarness.fit.mockClear();terminalHarness.scrollToBottom.mockClear();terminalHarness.write.mockClear();+ terminalHarness.host.current = null;+ terminalHarness.visibilityAtWrite = [];terminalHarness.deferWrite = false;terminalHarness.writeCallbacks = [];terminalHarness.wheel.current = null;terminalHarness.csiHandlers = [];+ terminalHarness.modes.mouseTrackingMode = "none";+ terminalHarness.bufferType = "normal";+ terminalHarness.scrollLines.mockClear();globalThis.ResizeObserver = ResizeObserverHarness;});@@ -206,7 +232,7 @@ describe("AgenticTerminal layout", () => {expect(terminalHarness.wheel.current).not.toBeNull();});- it("requires explicit live-view activation and revokes it on exit", () => {+ it("keeps the wheel on terminal history even while the CLI tracks the mouse", () => {render(<AgenticTerminalname="Dana"@@ -215,50 +241,30 @@ describe("AgenticTerminal layout", () => {fontSize={13}/>,);- const host = screen.getByTestId("agentic-terminal-host-Dana");- const hide = terminalHarness.csiHandlers.find(- ({ id }) => id.prefix === "?" && id.final === "l",- );- const show = terminalHarness.csiHandlers.find(- ({ id }) => id.prefix === "?" && id.final === "h",- );- expect(host.dataset.liveTuiCandidate).toBe("false");- expect(host.dataset.liveTuiNavigation).toBe("false");- expect(hide?.callback([25])).toBe(false);- expect(host.dataset.liveTuiCandidate).toBe("true");- expect(host.dataset.liveTuiNavigation).toBe("false");+ // Plain pane: xterm's native wheel behaviour is already right.expect(- terminalHarness.wheel.current?.(- new WheelEvent("wheel", { deltaY: 120 }),- ),+ terminalHarness.wheel.current?.(new WheelEvent("wheel", { deltaY: 120 })),).toBe(true);- expect(terminalHarness.input).not.toHaveBeenCalled();+ expect(terminalHarness.scrollLines).not.toHaveBeenCalled();- host.dataset.liveTuiNavigation = "true";+ // A normal-buffer CLI that negotiates mouse tracking must NOT receive the+ // wheel as mouse reports — the wheel keeps scrolling xterm's history, so+ // scrolling behaves identically in every provider and every CLI mode.+ terminalHarness.modes.mouseTrackingMode = "any";expect(- terminalHarness.wheel.current?.(- new WheelEvent("wheel", { deltaY: 120 }),- ),+ terminalHarness.wheel.current?.(new WheelEvent("wheel", { deltaY: 120 })),).toBe(false);- expect(terminalHarness.input).toHaveBeenCalledWith("\x1b[B".repeat(3));- expect(show?.callback([25])).toBe(false);- expect(host.dataset.liveTuiCandidate).toBe("false");- expect(host.dataset.liveTuiNavigation).toBe("false");-- expect(hide?.callback([25])).toBe(false);- host.dataset.liveTuiNavigation = "true";- terminalHarness.input.mockClear();- act(() => terminalHarness.handlers.current?.onExit?.(1 as never));- expect(host.dataset.liveTuiCandidate).toBe("false");- expect(host.dataset.liveTuiNavigation).toBe("false");- expect(terminalHarness.write).toHaveBeenLastCalledWith(- expect.stringContaining("\x1b[?25h"),- );- expect(terminalHarness.wheel.current?.(new WheelEvent("wheel", { deltaY: 120 }))).toBe(- true,- );+ expect(terminalHarness.scrollLines).toHaveBeenCalledWith(3);expect(terminalHarness.input).not.toHaveBeenCalled();++ // A true alternate-screen app (vim, less) keeps its negotiated protocols.+ terminalHarness.bufferType = "alternate";+ terminalHarness.scrollLines.mockClear();+ expect(+ terminalHarness.wheel.current?.(new WheelEvent("wheel", { deltaY: 120 })),+ ).toBe(true);+ expect(terminalHarness.scrollLines).not.toHaveBeenCalled();});it("waits for the area-aware grid measurement before opening the PTY", () => {@@ -426,6 +432,13 @@ describe("AgenticTerminal layout", () => {"the whole recorded session" as never,);});+ // Captured INSIDE `term.write`, before React gets another render. This is+ // the timing the real WebView exposed: a state-only curtain arrived after+ // xterm had already begun painting the replay.+ expect(terminalHarness.visibilityAtWrite.at(-1)).toBe("hidden");+ expect(screen.getByTestId("agentic-terminal-host-Dana").style.visibility).toBe(+ "hidden",+ );expect(region?.className).toContain("invisible");expect(terminalHarness.writeCallbacks).toHaveLength(1);@@ -435,6 +448,7 @@ describe("AgenticTerminal layout", () => {});expect(terminalHarness.scrollToBottom).toHaveBeenCalled();+ expect(screen.getByTestId("agentic-terminal-host-Dana").style.visibility).toBe("");expect(region?.className).not.toContain("invisible");});diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex 1d95b5bf49..28422cadc8 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -116,10 +116,7 @@ import {} from "./offscreenBuffer";import { installQuerySuppression } from "./terminalQueries";import { PaneScrollRail } from "./PaneScrollRail";-import {- createLiveTuiWheelHandler,- installLiveTuiCursorTracking,-} from "./terminalScrollSurface";+import { captureWheelForTerminalHistory } from "./terminalScrollSurface";import {openPaneSocket,type PaneSocket,@@ -556,21 +553,6 @@ export function AgenticTerminal({// before reaching it — too late, and then visible as junk in its prompt.// The backend answers those instead. See ./terminalQueries.const disposeQuerySuppression = installQuerySuppression(term.parser);- // A hidden cursor is only a CANDIDATE for a keyboard-owned live drawing:- // progress spinners use the same terminal mode. The rail exposes an- // explicit activation control for that candidate; only that user choice- // may turn wheel/drag input into cursor keys.- let cursorHidden = false;- const setCursorHidden = (hidden: boolean) => {- cursorHidden = hidden;- container.dataset.liveTuiCandidate = hidden ? "true" : "false";- if (!hidden) container.dataset.liveTuiNavigation = "false";- };- setCursorHidden(false);- const liveTuiTracking = installLiveTuiCursorTracking(- term.parser,- setCursorHidden,- );const fit = new FitAddon();term.loadAddon(fit);term.loadAddon(new WebLinksAddon(activateLink));@@ -589,19 +571,11 @@ export function AgenticTerminal({/* proposed API unavailable in this build — widths stay at Unicode 6 */}term.open(container);- // A normal-buffer coding CLI can draw a windowed live block inside ordinary- // terminal history. xterm can scroll that history, but rows omitted by the- // live block only exist in the CLI and need cursor navigation. The handler- // is active only after the rail's explicit live-view activation, and that- // opt-in is revoked as soon as the CLI restores the cursor.- term.attachCustomWheelEventHandler(- createLiveTuiWheelHandler(- term,- () =>- cursorHidden &&- container.dataset.liveTuiNavigation === "true",- ),- );+ // The wheel always moves xterm's own history, even while a normal-buffer+ // CLI has negotiated mouse tracking — otherwise scrolling only "works"+ // when the CLI feels like it, which is the per-provider inconsistency the+ // scroll rebuild removed. See captureWheelForTerminalHistory.+ term.attachCustomWheelEventHandler(captureWheelForTerminalHistory(term));// Canvas rather than the DOM renderer: a coding agent's TUI redraws its// prompt box on every keystroke, and per-cell DOM elements both lag and// land on fractional pixel offsets. Loaded AFTER open() because it needs@@ -883,7 +857,16 @@ export function AgenticTerminal({// screen this replay just replaced.cancelHoldTimer();offscreen.drain();- liveTuiTracking.reset();+ // React state is not a synchronous paint barrier. In a real WebSocket+ // callback, `setTailReady(false)` may not reach the DOM before xterm's+ // write queue starts parsing. Hide the canvas host imperatively BEFORE+ // reset/write; React still mirrors the curtain below for later renders.+ const curtain = paneVisible && activeRef.current;+ if (curtain) {+ container.style.visibility = "hidden";+ replayCurtainRef.current = true;+ setTailReady(false);+ }term.reset();// A normal-buffer CLI's replay is its whole scrollback — up to the// server's 128 KB (see `ReplayBuffer`) — and xterm parses it in time@@ -895,11 +878,6 @@ export function AgenticTerminal({// it. So the surface is hidden for the length of the rebuild — the same// curtain a chat-stage switch drops — and lifted one settled frame// after the tail scroll has landed.- const curtain = paneVisible && activeRef.current;- if (curtain) {- replayCurtainRef.current = true;- setTailReady(false);- }// Through the ordinary path, so a replay arriving while nobody is looking// is parked and un-parked by the same rules as anything else — and so it// counts as the pane having painted.@@ -925,6 +903,7 @@ export function AgenticTerminal({}term.scrollToBottom?.();setTailReady(true);+ container.style.removeProperty("visibility");});});};@@ -1095,9 +1074,6 @@ export function AgenticTerminal({}},onExit: (code) => {- // A crash cannot be trusted to restore cursor visibility. End live- // TUI ownership before drawing the terminal's definitive exit row.- liveTuiTracking.reset();report("exited", explainExit(code));writeToPane(`\r\n\x1b[?25h\x1b[33m${describeExit(displayName, code)}\x1b[0m\r\n`,@@ -1234,6 +1210,7 @@ export function AgenticTerminal({cancelAnimationFrame(replayRevealFrameRef.current);replayRevealFrameRef.current = undefined;}+ container.style.removeProperty("visibility");// Before the terminal is disposed below: a deadline flush one tick later// would write into it after it is gone.cancelHoldTimer();@@ -1252,7 +1229,6 @@ export function AgenticTerminal({disposeCopyBridge();disposePasteBridge();disposeNewlineBridge();- liveTuiTracking.dispose();disposeQuerySuppression();try {socket?.close();@@ -1286,10 +1262,12 @@ export function AgenticTerminal({replayRevealFrameRef.current = undefined;}if (!active) {+ containerRef.current?.style.setProperty("visibility", "hidden");setTailReady(false);visibilityRef.current?.park();return;}+ containerRef.current?.style.setProperty("visibility", "hidden");setTailReady(false);let cancelled = false;let frame: number | undefined;@@ -1311,7 +1289,10 @@ export function AgenticTerminal({// A replay mid-rebuild keeps the curtain: lifting it here would show// the rest of its history printing. Its own completion reveals the// pane (see `replayToPane`).- if (!replayCurtainRef.current) setTailReady(true);+ if (!replayCurtainRef.current) {+ setTailReady(true);+ containerRef.current?.style.removeProperty("visibility");+ }});};const afterFlush = () => {@@ -1588,7 +1569,6 @@ export function AgenticTerminal({epoch={terminalEpoch}appearance={appearance}onFocus={onFocus}- onOpenHistory={() => setHistoryOpen(true)}/><PaneConversationDialogterminal={name}diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsxindex dfa4abc764..4b4d830df5 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx@@ -50,48 +50,38 @@ interface TerminalHarness {term: Terminal;scrollToLine: ReturnType<typeof vi.fn>;scrollLines: ReturnType<typeof vi.fn>;- input: ReturnType<typeof vi.fn>;- setOwner: (owner: "terminal" | "mouse-app" | "page-app") => void;- /** Repaint every visible row, which is what a moved application looks like. */- repaint: () => void;+ scrollToTop: ReturnType<typeof vi.fn>;+ scrollToBottom: ReturnType<typeof vi.fn>;}function fakeTerminal({- owner,+ type = "normal",line = 100,maxLine = 100,}: {- owner: "terminal" | "mouse-app" | "page-app";+ type?: "normal" | "alternate";line?: number;maxLine?: number;-}): TerminalHarness {+} = {}): TerminalHarness {const scroll = signal<number>();const parsed = signal<void>();const changed = signal<unknown>();- let generation = 0;- const active = {- type: owner === "terminal" ? "normal" : "alternate",- baseY: maxLine,- viewportY: line,- getLine: (index: number) => ({- translateToString: () => `row ${index} of paint ${generation}`,- }),- };- const modes = {- mouseTrackingMode: owner === "mouse-app" ? "any" : "none",- };+ const active = { type, baseY: maxLine, viewportY: line };const scrollToLine = vi.fn((next: number) => {active.viewportY = next;scroll.fire(next);});const scrollLines = vi.fn((amount: number) => {- active.viewportY = Math.max(0, Math.min(active.baseY, active.viewportY + amount));+ active.viewportY = Math.max(+ 0,+ Math.min(active.baseY, active.viewportY + amount),+ );scroll.fire(active.viewportY);});- const input = vi.fn();+ const scrollToTop = vi.fn(() => scrollToLine(0));+ const scrollToBottom = vi.fn(() => scrollToLine(active.baseY));const term = {rows: 20,- modes,buffer: {active,onBufferChange: changed.event,@@ -100,48 +90,19 @@ function fakeTerminal({onWriteParsed: parsed.event,scrollToLine,scrollLines,- scrollToTop: vi.fn(() => scrollToLine(0)),- scrollToBottom: vi.fn(() => scrollToLine(active.baseY)),- input,+ scrollToTop,+ scrollToBottom,} as unknown as Terminal;- const setOwner = (next: "terminal" | "mouse-app" | "page-app") => {- active.type = next === "terminal" ? "normal" : "alternate";- modes.mouseTrackingMode = next === "mouse-app" ? "any" : "none";- changed.fire(active);- };- return {- term,- scrollToLine,- scrollLines,- input,- setOwner,- repaint: () => {- generation += 1;- },- };+ return { term, scrollToLine, scrollLines, scrollToTop, scrollToBottom };}-function RailHarness({- name,- term,- liveTuiCandidate = false,- onOpenHistory,-}: {- name: string;- term: Terminal;- liveTuiCandidate?: boolean;- onOpenHistory?: () => void;-}) {+function RailHarness({ name, term }: { name: string; term: Terminal }) {const regionRef = useRef<HTMLDivElement | null>(null);const hostRef = useRef<HTMLDivElement | null>(null);const terminalRef = useRef<Terminal | null>(term);return (<div ref={regionRef} id={`terminal-${name}`}>- <div- ref={hostRef}- data-live-tui-candidate={liveTuiCandidate ? "true" : "false"}- data-live-tui-navigation="false"- >+ <div ref={hostRef}><div className="xterm-screen" data-testid={`xterm-screen-${name}`} /></div><PaneScrollRail@@ -152,7 +113,6 @@ function RailHarness({terminalRef={terminalRef}epoch={1}appearance="dark"- onOpenHistory={onOpenHistory}/></div>);@@ -182,8 +142,8 @@ function giveTrackGeometry(name: string, height = 200): HTMLElement {describe("PaneScrollRail", () => {it("drags the exact xterm history independently for each terminal ID", () => {- const mika = fakeTerminal({ owner: "terminal" });- const nova = fakeTerminal({ owner: "terminal" });+ const mika = fakeTerminal();+ const nova = fakeTerminal();render(<><RailHarness name="Mika" term={mika.term} />@@ -202,9 +162,6 @@ describe("PaneScrollRail", () => {expect(mika.scrollToLine.mock.calls.at(-1)?.[0]).toBeLessThan(30);expect(nova.scrollToLine).not.toHaveBeenCalled();expect(thumb.style.top).not.toBe("");- expect(screen.getByTestId("pane-scroll-rail-Mika").dataset.scrollMode).toBe(- "terminal",- );expect(screen.getByRole("scrollbar", { name: "Scroll Mika" })@@ -212,299 +169,41 @@ describe("PaneScrollRail", () => {).toBe("terminal-Mika");});- it("strokes a positionless live inline TUI in both directions", () => {- const harness = fakeTerminal({ owner: "terminal" });- render(<RailHarness name="Mira" term={harness.term} liveTuiCandidate />);- const rail = giveTrackGeometry("Mira");-- // Cursor-hidden is only a candidate. Until the user explicitly activates- // the live view, the exact terminal thumb and its keyboard behavior win.- expect(screen.getByTestId("pane-scroll-thumb-Mira")).toBeTruthy();- const candidateButton = screen.getByRole("button", {- name: "Control live view in Mira",- });- const nativeWheel: number[] = [];- screen- .getByTestId("xterm-screen-Mira")- .addEventListener("wheel", (event) => nativeWheel.push(event.deltaY));- fireEvent.wheel(candidateButton, { deltaY: 120 });- expect(nativeWheel).toEqual([120]);- fireEvent.keyDown(rail, { key: "ArrowDown" });- expect(harness.scrollLines).toHaveBeenCalledWith(1);- expect(harness.input).not.toHaveBeenCalled();-- fireEvent.click(candidateButton);- const grip = screen.getByTestId("pane-scroll-grip-Mira");-- fireEvent.pointerDown(grip, { button: 0, clientY: 100, pointerId: 21 });- fireEvent.pointerMove(rail, { clientY: 115, pointerId: 21 });- fireEvent.pointerMove(rail, { clientY: 109, pointerId: 21 });- fireEvent.pointerUp(rail, { clientY: 109, pointerId: 21 });-- expect(harness.input.mock.calls.map((call) => call[0])).toEqual([- "\x1b[B".repeat(5),- "\x1b[A".repeat(2),- ]);- expect(screen.queryByTestId("pane-scroll-thumb-Mira")).toBeNull();- expect(rail.dataset.scrollPosition).toBe("none");- });-- it("hands ArrowDown and PageDown to an explicit live inline TUI", () => {- const harness = fakeTerminal({ owner: "terminal" });- render(<RailHarness name="Tali" term={harness.term} liveTuiCandidate />);- const rail = giveTrackGeometry("Tali");- fireEvent.click(- screen.getByRole("button", { name: "Control live view in Tali" }),- );-- fireEvent.keyDown(rail, { key: "ArrowDown" });- fireEvent.keyDown(rail, { key: "PageDown" });-- expect(harness.scrollLines).not.toHaveBeenCalled();- expect(harness.input.mock.calls.map((call) => call[0])).toEqual([- "\x1b[B",- "\x1b[B".repeat(7),- ]);- });-- it("keeps ArrowDown native at a visible-cursor prompt, including its tail", () => {- const harness = fakeTerminal({ owner: "terminal" });- render(<RailHarness name="Niko" term={harness.term} />);- const rail = giveTrackGeometry("Niko");-- fireEvent.keyDown(rail, { key: "ArrowDown" });-- expect(harness.scrollLines).toHaveBeenCalledWith(1);- expect(harness.input).not.toHaveBeenCalled();- });-- it("strokes a mouse-aware full-screen IDE both ways and shows no position at all", () => {- const harness = fakeTerminal({ owner: "mouse-app" });- render(<RailHarness name="Aria" term={harness.term} />);- const rail = giveTrackGeometry("Aria");- const xtermScreen = screen.getByTestId("xterm-screen-Aria");- const deltas: number[] = [];- xtermScreen.addEventListener("wheel", (event) => deltas.push(event.deltaY));- // The regression this pins: no shape in this track, in any state. Twice a- // grip was drawn here and twice it was read as a position that was wrong.- expect(screen.queryByTestId("pane-scroll-thumb-Aria")).toBeNull();- expect(rail.dataset.scrollPosition).toBe("none");-- fireEvent.pointerDown(rail, { button: 0, clientY: 100, pointerId: 2 });- // A press alone must move nothing: there is no position it could mean.- expect(deltas).toEqual([]);- fireEvent.pointerMove(rail, { clientY: 65, pointerId: 2 });- fireEvent.pointerMove(rail, { clientY: 121, pointerId: 2 });- fireEvent.pointerUp(rail, { clientY: 121, pointerId: 2 });-- expect(deltas.some((delta) => delta < 0)).toBe(true);- expect(deltas.some((delta) => delta > 0)).toBe(true);- expect(screen.queryByTestId("pane-scroll-thumb-Aria")).toBeNull();- expect(rail.dataset.scrollMode).toBe("application");- expect(rail.hasAttribute("aria-valuemin")).toBe(false);- expect(rail.hasAttribute("aria-valuemax")).toBe(false);- expect(rail.hasAttribute("aria-valuenow")).toBe(false);- expect(rail.hasAttribute("aria-valuetext")).toBe(false);- expect(- screen- .getByRole("button", { name: "Scroll older in Aria" })- .getAttribute("aria-controls"),- ).toBe("terminal-Aria");- expect(- screen- .getByRole("button", { name: "Scroll newer in Aria" })- .getAttribute("aria-controls"),- ).toBe("terminal-Aria");- });-- it("drags the application grip to stroke, and it springs back to centre", () => {- const harness = fakeTerminal({ owner: "mouse-app" });- render(<RailHarness name="Rex" term={harness.term} />);- const rail = giveTrackGeometry("Rex");- const grip = screen.getByTestId("pane-scroll-grip-Rex");- const deltas: number[] = [];- screen- .getByTestId("xterm-screen-Rex")- .addEventListener("wheel", (event) => deltas.push(event.deltaY));-- // At rest the grip sits dead centre — it carries no position.- expect(grip.style.transform).toBe("translate(-50%, calc(-50% + 0px))");-- fireEvent.pointerDown(grip, { button: 0, clientY: 100, pointerId: 9 });- fireEvent.pointerMove(rail, { clientY: 60, pointerId: 9 });-- // The drag strokes the application and the grip rides along with it.- expect(deltas.length).toBeGreaterThan(0);- expect(deltas.every((delta) => delta < 0)).toBe(true);- expect(grip.style.transform).toBe("translate(-50%, calc(-50% + -40px))");-- fireEvent.pointerUp(rail, { clientY: 60, pointerId: 9 });-- // Released, it returns to centre: a handle that never stays put cannot be- // read as "you are here". The thumb testid stays application-free.- expect(grip.style.transform).toBe("translate(-50%, calc(-50% + 0px))");- expect(screen.queryByTestId("pane-scroll-thumb-Rex")).toBeNull();- });-- it("opens the recorded conversation on a grip click, but not after a drag", () => {- const harness = fakeTerminal({ owner: "mouse-app" });- const onOpenHistory = vi.fn();- render(- <RailHarness name="Uma" term={harness.term} onOpenHistory={onOpenHistory} />,- );- const rail = giveTrackGeometry("Uma");- const grip = screen.getByTestId("pane-scroll-grip-Uma");-- // A real drag scrolls; it must NOT also open the history on release.- fireEvent.pointerDown(grip, { button: 0, clientY: 100, pointerId: 11 });- fireEvent.pointerMove(rail, { clientY: 60, pointerId: 11 });- fireEvent.pointerUp(rail, { clientY: 60, pointerId: 11 });- expect(onOpenHistory).not.toHaveBeenCalled();-- // A press-and-release that never moved is a click, and a click opens it.- fireEvent.pointerDown(grip, { button: 0, clientY: 100, pointerId: 12 });- fireEvent.pointerUp(rail, { clientY: 101, pointerId: 12 });- expect(onOpenHistory).toHaveBeenCalledTimes(1);-- // Pressing the empty track is a stroke gesture, never a click-open.- fireEvent.pointerDown(rail, { button: 0, clientY: 40, pointerId: 13 });- fireEvent.pointerUp(rail, { clientY: 40, pointerId: 13 });- expect(onOpenHistory).toHaveBeenCalledTimes(1);- });-- it("pages the application from the visible arrow caps", () => {- const harness = fakeTerminal({ owner: "mouse-app" });+ it("jumps to a pressed track spot and keeps dragging from there", () => {+ const harness = fakeTerminal({ line: 100, maxLine: 100 });render(<RailHarness name="Odo" term={harness.term} />);- giveTrackGeometry("Odo");- const deltas: number[] = [];- screen- .getByTestId("xterm-screen-Odo")- .addEventListener("wheel", (event) =>- deltas.push((event as WheelEvent).deltaY),- );-- fireEvent.click(screen.getByRole("button", { name: "Scroll older in Odo" }));- expect(deltas.length).toBeGreaterThan(0);- expect(deltas.every((delta) => delta < 0)).toBe(true);-- fireEvent.click(screen.getByRole("button", { name: "Scroll newer in Odo" }));- expect(deltas.some((delta) => delta > 0)).toBe(true);- });+ const rail = giveTrackGeometry("Odo");- it("says plainly why an application rail has no position, and stays visible", () => {- const harness = fakeTerminal({ owner: "mouse-app" });- render(<RailHarness name="Ida" term={harness.term} />);- const rail = giveTrackGeometry("Ida");+ fireEvent.pointerDown(rail, { button: 0, clientY: 20, pointerId: 2 });+ expect(harness.scrollToLine).toHaveBeenCalled();+ expect(harness.scrollToLine.mock.calls.at(-1)?.[0]).toBeLessThan(30);- expect(rail.title).toBe(- "Scroll Ida: this app keeps its own history, so there is no position to show",- );- // The regression this pins: the application rail once hid at rest, and an- // invisible control next to a sibling pane's always-visible thumb was read- // as "the scrollbar is broken in this CLI". Both rail kinds now share the- // same resting visibility.- expect(rail.className).not.toContain("opacity-0");- expect(rail.className).toContain("opacity-65");+ fireEvent.pointerMove(rail, { clientY: 190, pointerId: 2 });+ fireEvent.pointerUp(rail, { clientY: 190, pointerId: 2 });+ expect(harness.scrollToLine.mock.calls.at(-1)?.[0]).toBe(100);});- it("notices a mouse-tracking flip that arrives without any buffer event", () => {- vi.useFakeTimers({- toFake: [- "setInterval",- "clearInterval",- "requestAnimationFrame",- "cancelAnimationFrame",- ],- });- try {- const harness = fakeTerminal({ owner: "terminal" });- render(<RailHarness name="Vera" term={harness.term} />);- const rail = screen.getByTestId("pane-scroll-rail-Vera");- expect(rail.dataset.scrollMode).toBe("terminal");-- // A replayed session consumes the TUI's DECSET before the rail- // subscribes, so the flip reaches xterm without any later event.- (- harness.term.modes as { mouseTrackingMode: string }- ).mouseTrackingMode = "any";- act(() => {- vi.advanceTimersByTime(1600);- });-- expect(rail.dataset.scrollMode).toBe("application");- } finally {- vi.useRealTimers();- }- });-- it("drops the exact thumb when a TUI takes the screen during a drag", () => {- vi.useFakeTimers({- toFake: [- "setInterval",- "clearInterval",- "requestAnimationFrame",- "cancelAnimationFrame",- ],- });- try {- const harness = fakeTerminal({ owner: "terminal", line: 50 });- render(<RailHarness name="Iris" term={harness.term} />);- const rail = giveTrackGeometry("Iris");- const thumb = screen.getByTestId("pane-scroll-thumb-Iris");- expect(rail.dataset.scrollMode).toBe("terminal");- const deltas: number[] = [];- screen- .getByTestId("xterm-screen-Iris")- .addEventListener("wheel", (event) => deltas.push(event.deltaY));-- fireEvent.pointerDown(thumb, { button: 0, clientY: 100, pointerId: 5 });- harness.setOwner("mouse-app");- fireEvent.pointerMove(rail, { clientY: 60, pointerId: 5 });- fireEvent.pointerUp(rail, { clientY: 60, pointerId: 5 });- act(() => {- vi.advanceTimersByTime(50);- });-- // The gesture continues as a stroke on the application that took over,- // and the thumb it started on is gone rather than left pointing at a line- // the pane no longer has.- expect(deltas.length).toBeGreaterThan(0);- expect(deltas.every((delta) => delta < 0)).toBe(true);- expect(screen.queryByTestId("pane-scroll-thumb-Iris")).toBeNull();- expect(rail.dataset.scrollMode).toBe("application");- } finally {- vi.useRealTimers();- }- });-- it("cancels an uncaptured drag when the pointer leaves the rail", () => {- const harness = fakeTerminal({ owner: "terminal", line: 50 });- render(<RailHarness name="Lumi" term={harness.term} />);- const rail = giveTrackGeometry("Lumi");- const thumb = screen.getByTestId("pane-scroll-thumb-Lumi");-- fireEvent.pointerDown(thumb, { button: 0, clientY: 100, pointerId: 6 });- expect(rail.className).toContain("cursor-grabbing");- fireEvent.pointerLeave(rail, { pointerId: 6 });- expect(rail.className).not.toContain("cursor-grabbing");- });-- it("uses PageUp and PageDown for an alternate-screen IDE without mouse mode", () => {- const harness = fakeTerminal({ owner: "page-app" });- render(<RailHarness name="Sora" term={harness.term} />);- const rail = giveTrackGeometry("Sora");+ it("scrolls with the keyboard on every pane the same way", () => {+ const harness = fakeTerminal({ line: 50 });+ render(<RailHarness name="Vera" term={harness.term} />);+ const rail = giveTrackGeometry("Vera");+ fireEvent.keyDown(rail, { key: "ArrowUp" });+ fireEvent.keyDown(rail, { key: "ArrowDown" });fireEvent.keyDown(rail, { key: "PageUp" });fireEvent.keyDown(rail, { key: "PageDown" });+ fireEvent.keyDown(rail, { key: "Home" });+ fireEvent.keyDown(rail, { key: "End" });- expect(harness.input.mock.calls.map((call) => call[0])).toEqual([- "\x1b[5~",- "\x1b[6~",+ expect(harness.scrollLines.mock.calls.map((call) => call[0])).toEqual([+ -1, 1, -20, 20,]);+ expect(harness.scrollToTop).toHaveBeenCalledOnce();+ expect(harness.scrollToBottom).toHaveBeenCalledOnce();});it("forwards a wheel over the rail unchanged to its own terminal", () => {- const harness = fakeTerminal({ owner: "mouse-app" });+ const harness = fakeTerminal();render(<RailHarness name="Nia" term={harness.term} />);const rail = giveTrackGeometry("Nia");const xtermScreen = screen.getByTestId("xterm-screen-Nia");@@ -524,4 +223,31 @@ describe("PaneScrollRail", () => {expect(forwarded.deltaY).toBe(120);expect(forwarded.shiftKey).toBe(true);});++ it("cancels an uncaptured drag when the pointer leaves the rail", () => {+ const harness = fakeTerminal({ line: 50 });+ render(<RailHarness name="Lumi" term={harness.term} />);+ const rail = giveTrackGeometry("Lumi");+ const thumb = screen.getByTestId("pane-scroll-thumb-Lumi");++ fireEvent.pointerDown(thumb, { button: 0, clientY: 100, pointerId: 6 });+ expect(rail.className).toContain("cursor-grabbing");+ fireEvent.pointerLeave(rail, { pointerId: 6 });+ expect(rail.className).not.toContain("cursor-grabbing");+ });++ it("says honestly when a full-screen app owns the pane", () => {+ const harness = fakeTerminal({ type: "alternate", line: 0, maxLine: 0 });+ render(<RailHarness name="Ida" term={harness.term} />);+ const rail = giveTrackGeometry("Ida");+ const thumb = screen.getByTestId("pane-scroll-thumb-Ida");++ // No history to scroll: the thumb honestly fills the whole track, and the+ // tooltip explains who owns the screen. One rail shape for every pane —+ // the owner-switching rail (grip, caps, strokes) is gone.+ expect(thumb.style.height).toBe("200px");+ expect(rail.title).toBe(+ "Scroll Ida: a full-screen app owns this pane right now",+ );+ });});diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsxindex d95f7036db..8501f2cb29 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx@@ -1,25 +1,17 @@/**- * One honest scroll rail for one Agentic-IDE terminal pane.+ * One scroll rail for one Agentic-IDE terminal pane — the SAME rail for every+ * provider and every CLI mode.*- * Normal terminal history gets a conventional absolute thumb: xterm knows the- * line and the extent, so the thumb is the truth and dragging it is a seek.- * A cursor-hidden normal-buffer view stays in that exact mode until the user- * activates the live-view control; cursor visibility alone never authorizes- * synthetic keyboard input.+ * It draws xterm's exact viewport position as a conventional thumb: dragging+ * seeks, clicking the track jumps, arrow/page keys scroll, and the wheel+ * passes through to the terminal. There is no second regime. The previous+ * owner-switching rail (grip, stroke gestures, key relays, live-view opt-in)+ * accumulated eight confirmed defects across four iterations and was removed+ * whole on the maintainer's verdict — see ./terminalScrollSurface for why the+ * single xterm-owned rule is honest for today's coding CLIs.*- * A full-screen coding TUI keeps its history inside the application, and this- * rail then draws NO POSITION AT ALL. It becomes what it can honestly be —- * arrow caps that page, a strip that scrolls while stroked, the wheel passing- * through, and a GRIP that makes the stroke visible and grabbable: it rests in- * the middle, follows the hand while dragging, and springs back to the middle- * on release. The spring-back is the honesty — a handle that always returns to- * centre cannot be read as "you are here".- *- * Two attempts to show an actual position there were built and reverted after- * the maintainer used them; ./terminalScrollSurface records both and why. The- * short version: any shape that STAYS where the drag left it gets read as- * "you are here", and being slightly wrong about that is worse than saying- * nothing.+ * While an alternate-screen app (vim, less) holds the screen, xterm has no+ * history: the thumb fills the track and the rail says so in its tooltip.*/import {useCallback,@@ -33,47 +25,24 @@ import {type RefObject,} from "react";import type { Terminal } from "@xterm/xterm";-import { useT } from "@/i18n";import { cn } from "@/lib/utils";import { PANE_CHROME, type TerminalAppearance } from "./terminalThemes";import {- applicationPageNotches,bindTerminalScrollRegion,forwardWheelToTerminal,lineAtThumbTop,readTerminalScrollView,- scrollApplication,- scrollLiveCursor,scrollThumbGeometry,- strokeUnits,type TerminalScrollView,} from "./terminalScrollSurface";interface DragSession {pointerId: number;- owner: TerminalScrollView["owner"];+ /** Pixel offset between the grab point and the thumb's top edge. */grabOffset: number;- /** Where the stroke was last accounted for. Application rails only. */- lastY: number;- /** Where the pointer went down — the grip's visual travel is measured from- * here so it can spring back to centre on release. Application rails only. */- originY: number;- /** Did this gesture start on the grip capsule itself? */- grabbedGrip: boolean;- /** Farthest the pointer travelled — a release under the click threshold- * opens the pane's conversation history instead of having scrolled. */- movedPx: number;captured: boolean;}-/** Pointer travel below which a grip press-and-release counts as a click. */-const GRIP_CLICK_PX = 5;--/** Height of the application grip capsule, in px. Must match the render. */-const GRIP_PX = 28;-/** Height of one arrow cap, which the grip must never slide under. */-const CAP_PX = 16;-interface PaneScrollRailProps {name: string;controlsId: string;@@ -84,9 +53,6 @@ interface PaneScrollRailProps {epoch: number;appearance: TerminalAppearance;onFocus?: () => void;- /** A click (not a drag) on the application grip asks for the pane's- * recorded conversation — the owner of that dialog lives in the pane. */- onOpenHistory?: () => void;}function sameView(@@ -94,10 +60,10 @@ function sameView(right: TerminalScrollView,): boolean {return (- left?.owner === right.owner &&- left.rows === right.rows &&+ left?.rows === right.rows &&left.maxLine === right.maxLine &&- left.line === right.line+ left.line === right.line &&+ left.altScreen === right.altScreen);}@@ -110,98 +76,31 @@ export function PaneScrollRail({epoch,appearance,onFocus,- onOpenHistory,}: PaneScrollRailProps) {- const t = useT();const trackRef = useRef<HTMLDivElement | null>(null);const thumbRef = useRef<HTMLDivElement | null>(null);- const gripRef = useRef<HTMLDivElement | null>(null);const dragRef = useRef<DragSession | null>(null);const frameRef = useRef<number | null>(null);const [view, setView] = useState<TerminalScrollView | null>(null);const [trackPx, setTrackPx] = useState(0);const [dragging, setDragging] = useState(false);- const [liveTuiCandidate, setLiveTuiCandidate] = useState(false);- const [liveTuiNavigation, setLiveTuiNavigation] = useState(false);- /** The application grip's travel from centre while a stroke is held. */- const [gripOffset, setGripOffset] = useState(0);-- const readView = useCallback(- (term: Terminal) =>- readTerminalScrollView(- term,- hostRef.current?.dataset.liveTuiNavigation === "true",- ),- [hostRef],- );-- const canActivateLiveTui = useCallback(- (term: Terminal) =>- hostRef.current?.dataset.liveTuiCandidate === "true" &&- (term.buffer?.active?.type ?? "normal") === "normal" &&- (term.modes?.mouseTrackingMode ?? "none") === "none",- [hostRef],- );const sync = useCallback(() => {frameRef.current = null;const term = terminalRef.current;- const host = hostRef.current;if (!term) {setView(null);- setLiveTuiCandidate(false);- setLiveTuiNavigation(false);return;}- const candidate = canActivateLiveTui(term);- if (!candidate && host) host.dataset.liveTuiNavigation = "false";- const navigation = candidate && host?.dataset.liveTuiNavigation === "true";- const next = readView(term);- if (host) host.dataset.scrollOwner = next.owner;- setLiveTuiCandidate((current) =>- current === candidate ? current : candidate,- );- setLiveTuiNavigation((current) =>- current === navigation ? current : navigation,- );+ const next = readTerminalScrollView(term);setView((current) => (sameView(current, next) ? current : next));- }, [canActivateLiveTui, hostRef, readView, terminalRef]);+ }, [terminalRef]);const scheduleSync = useCallback(() => {if (frameRef.current !== null) return;frameRef.current = requestAnimationFrame(sync);}, [sync]);- /** Relay to the application, whichever protocol it speaks. */- const relayApplication = useCallback(- (direction: -1 | 1, notches: number) => {- const term = terminalRef.current;- if (!term) return;- const bufferType = term.buffer?.active?.type ?? "normal";- const tracking = term.modes?.mouseTrackingMode ?? "none";- const keyboardOwnedLiveView =- hostRef.current?.dataset.liveTuiCandidate === "true" &&- hostRef.current?.dataset.liveTuiNavigation === "true" &&- bufferType === "normal" &&- tracking === "none";- if (keyboardOwnedLiveView) {- scrollLiveCursor(term, direction, notches);- } else if (bufferType === "alternate" || tracking !== "none") {- scrollApplication(term, hostRef.current, direction, notches);- }- },- [hostRef, terminalRef],- );-- const activateLiveTuiNavigation = useCallback(() => {- const term = terminalRef.current;- const host = hostRef.current;- if (!term || !host || !canActivateLiveTui(term)) return;- host.dataset.liveTuiNavigation = "true";- onFocus?.();- sync();- }, [canActivateLiveTui, hostRef, onFocus, sync, terminalRef]);-useEffect(() => {const term = terminalRef.current;if (!term) {@@ -221,16 +120,6 @@ export function PaneScrollRail({};}, [epoch, scheduleSync, sync, terminalRef]);- useEffect(() => {- // A replayed session can hand this rail a terminal whose mouse-tracking- // DECSET was parsed before the subscriptions above existed, and a TUI can- // flip tracking without emitting anything else afterwards. Observed live:- // panes stuck on "no history" while the application was already scrolling.- // A slow poll is the safety net; sameView keeps it render-free.- const timer = window.setInterval(scheduleSync, 750);- return () => window.clearInterval(timer);- }, [scheduleSync]);-useEffect(() => {const region = regionRef.current;if (!region) return;@@ -274,10 +163,11 @@ export function PaneScrollRail({return { top: box.top, height: track.clientHeight || box.height };}, []);- const moveExact = useCallback(- (current: TerminalScrollView, clientY: number, grabOffset: number) => {+ const moveTo = useCallback(+ (clientY: number, grabOffset: number) => {const term = terminalRef.current;if (!term) return;+ const current = readTerminalScrollView(term);const track = liveTrack();if (track.height <= 0) return;const thumbTop = clientY - track.top - grabOffset;@@ -287,37 +177,18 @@ export function PaneScrollRail({[liveTrack, scheduleSync, terminalRef],);- /**- * Stroke an application rail: distance moved becomes distance scrolled.- *- * Not a seek — there is no scale to seek on. The pointer's travel since the- * last accounted position is converted to relay units and the remainder is- * carried, so a slow drag scrolls smoothly and a fast one scrolls far.- */- const strokeApplication = useCallback(- (clientY: number) => {- const drag = dragRef.current;- if (!drag) return;- const { units, consumedPx } = strokeUnits(clientY - drag.lastY);- if (units === 0) return;- relayApplication(consumedPx < 0 ? -1 : 1, units);- drag.lastY += consumedPx;- },- [relayApplication],- );-const onPointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {if (event.button !== 0) return;const term = terminalRef.current;if (!term) return;- const current = readView(term);const track = liveTrack();if (track.height <= 0) return;event.preventDefault();event.stopPropagation();onFocus?.();+ const current = readTerminalScrollView(term);const geometry = scrollThumbGeometry(current, track.height);const grabbedThumb = event.target === thumbRef.current;const grabOffset = grabbedThumb@@ -325,14 +196,7 @@ export function PaneScrollRail({: geometry.height / 2;dragRef.current = {pointerId: event.pointerId,- owner: current.owner,grabOffset,- lastY: event.clientY,- originY: event.clientY,- grabbedGrip:- gripRef.current !== null &&- gripRef.current.contains(event.target as Node),- movedPx: 0,captured: false,};setDragging(true);@@ -343,137 +207,64 @@ export function PaneScrollRail({} catch {// Older WebViews and jsdom have no pointer-capture implementation.}-- if (current.owner === "terminal") {- if (!grabbedThumb) moveExact(current, event.clientY, grabOffset);- return;- }- // A press on an application rail starts a stroke and moves nothing yet:- // pressing must not teleport the transcript to a place the press did not- // mean, and there is no position for it to have meant.+ // A press on the bare track is a jump to that spot; the drag continues+ // from there. A press on the thumb keeps the line under the hand.+ if (!grabbedThumb) moveTo(event.clientY, grabOffset);},- [liveTrack, moveExact, onFocus, readView, terminalRef],+ [liveTrack, moveTo, onFocus, terminalRef],);const onPointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {const drag = dragRef.current;- const term = terminalRef.current;- if (!drag || !term || drag.pointerId !== event.pointerId) return;+ if (!drag || drag.pointerId !== event.pointerId) return;event.preventDefault();- const current = readView(term);- drag.movedPx = Math.max(- drag.movedPx,- Math.abs(event.clientY - drag.originY),- );- if (drag.owner === "terminal" && current.owner === "terminal") {- moveExact(current, event.clientY, drag.grabOffset);- drag.lastY = event.clientY;- } else {- strokeApplication(event.clientY);- // The grip follows the hand, clamped so it never slides under an- // arrow cap. finishDrag springs it back to centre.- const travel = Math.max(0, liveTrack().height / 2 - CAP_PX - GRIP_PX / 2);- setGripOffset(- Math.max(-travel, Math.min(travel, event.clientY - drag.originY)),- );- }+ moveTo(event.clientY, drag.grabOffset);},- [liveTrack, moveExact, readView, strokeApplication, terminalRef],+ [moveTo],);- const finishDrag = useCallback(- (pointerId?: number) => {- const drag = dragRef.current;- if (!drag || (pointerId !== undefined && pointerId !== drag.pointerId)) return;- dragRef.current = null;- setDragging(false);- // The grip is a control, not an indicator: it always returns to centre,- // which is what keeps it from ever being read as a position.- setGripOffset(0);- // Restore from the current owner, not the owner at pointer-down. A TUI- // may enter or leave its alternate buffer while the gesture is active,- // and an exact thumb left where the hand dropped it would be a lie about- // a screen that can answer for itself.- const term = terminalRef.current;- const thumb = thumbRef.current;- const track = liveTrack();- if (term && thumb && track.height > 0) {- const current = readView(term);- thumb.style.top = `${scrollThumbGeometry(current, track.height).top}px`;- }- },- [liveTrack, readView, terminalRef],- );+ const finishDrag = useCallback((pointerId?: number) => {+ const drag = dragRef.current;+ if (!drag || (pointerId !== undefined && pointerId !== drag.pointerId)) {+ return;+ }+ dragRef.current = null;+ setDragging(false);+ }, []);const onPointerUp = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {- const drag = dragRef.current;- // A press-and-release on the grip that never really moved is a CLICK,- // and a click on the grip opens the one history that can honestly show- // a position: the pane's own recorded conversation.- const clickedGrip =- drag !== null &&- drag.pointerId === event.pointerId &&- drag.owner === "application" &&- drag.grabbedGrip &&- drag.movedPx < GRIP_CLICK_PX;finishDrag(event.pointerId);try {event.currentTarget.releasePointerCapture(event.pointerId);} catch {// No capture was available; the drag still completed on this event.}- if (clickedGrip) onOpenHistory?.();},- [finishDrag, onOpenHistory],+ [finishDrag],);const onKeyDown = useCallback((event: ReactKeyboardEvent<HTMLDivElement>) => {const term = terminalRef.current;if (!term) return;- const current = readView(term);+ const current = readTerminalScrollView(term);let handled = true;- if (current.owner === "terminal") {- if (event.key === "ArrowUp") term.scrollLines(-1);- else if (event.key === "ArrowDown") term.scrollLines(1);- else if (event.key === "PageUp") term.scrollLines(-current.rows);- else if (event.key === "PageDown") term.scrollLines(current.rows);- else if (event.key === "Home") term.scrollToTop();- else if (event.key === "End") term.scrollToBottom();- else handled = false;- } else if (event.key === "ArrowUp") {- relayApplication(-1, 1);- } else if (event.key === "ArrowDown") {- relayApplication(1, 1);- } else if (event.key === "PageUp") {- relayApplication(-1, applicationPageNotches(current.rows));- } else if (event.key === "PageDown") {- relayApplication(1, applicationPageNotches(current.rows));- } else {- handled = false;- }+ if (event.key === "ArrowUp") term.scrollLines(-1);+ else if (event.key === "ArrowDown") term.scrollLines(1);+ else if (event.key === "PageUp") term.scrollLines(-current.rows);+ else if (event.key === "PageDown") term.scrollLines(current.rows);+ else if (event.key === "Home") term.scrollToTop();+ else if (event.key === "End") term.scrollToBottom();+ else handled = false;if (!handled) return;event.preventDefault();event.stopPropagation();onFocus?.();scheduleSync();},- [onFocus, readView, relayApplication, scheduleSync, terminalRef],- );-- const scrollApplicationPage = useCallback(- (direction: -1 | 1) => {- const term = terminalRef.current;- if (!term) return;- const current = readView(term);- if (current.owner !== "application") return;- relayApplication(direction, applicationPageNotches(current.rows));- onFocus?.();- scheduleSync();- },- [onFocus, readView, relayApplication, scheduleSync, terminalRef],+ [onFocus, scheduleSync, terminalRef],);const geometry = useMemo(@@ -482,197 +273,58 @@ export function PaneScrollRail({);if (!view) return null;- const exact = view.owner === "terminal";- const valueText = exact- ? view.maxLine === 0+ const valueText = view.altScreen+ ? `Scroll ${name}: a full-screen app owns this pane right now`+ : view.maxLine === 0? "No terminal history yet"- : `Terminal line ${view.line} of ${view.maxLine}`- : liveTuiNavigation- ? `Scroll ${name}: live-view navigation is active; use Shift+wheel for terminal history`- : `Scroll ${name}: this app keeps its own history, so there is no position to show`;+ : `Terminal line ${view.line} of ${view.maxLine}`;const shell = PANE_CHROME[appearance].shell;return (- <>- {liveTuiCandidate && exact && (- <button- type="button"- data-testid={`pane-live-navigation-${name}`}- aria-label={`Control live view in ${name}`}- aria-controls={controlsId}- title="Enable live-view navigation with the wheel and scroll rail"- onWheelCapture={(event) =>- forwardWheelToTerminal(hostRef.current, event.nativeEvent)- }- onClick={activateLiveTuiNavigation}- className={cn(- "absolute right-0 top-1/2 z-20 flex h-8 w-6 -translate-y-1/2 items-center justify-end rounded-l-md border border-r-0 pr-0.5",- "border-[#e7c46e]/55 text-[#e7c46e]/85 shadow-sm outline-none",- "hover:text-[#e7c46e] focus-visible:ring-1 focus-visible:ring-[#e7c46e]",- )}- style={{ background: shell }}- >- <svg- viewBox="0 0 8 16"- className="h-4 w-2 fill-current"- aria-hidden="true"- >- <path d="M4 0 8 5H0Z" />- <path d="M4 16 0 11h8Z" />- </svg>- </button>+ <div+ ref={trackRef}+ role="scrollbar"+ aria-label={`Scroll ${name}`}+ aria-controls={controlsId}+ aria-orientation="vertical"+ aria-valuemin={0}+ aria-valuemax={Math.max(1, view.maxLine)}+ aria-valuenow={view.line}+ aria-valuetext={valueText}+ tabIndex={0}+ data-testid={`pane-scroll-rail-${name}`}+ title={valueText}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={(event) => finishDrag(event.pointerId)}+ onLostPointerCapture={(event) => finishDrag(event.pointerId)}+ onPointerLeave={() => {+ if (dragRef.current && !dragRef.current.captured) finishDrag();+ }}+ onKeyDown={onKeyDown}+ className={cn(+ "group absolute inset-y-1 right-0 z-10 w-3 touch-none select-none rounded-full outline-none",+ "opacity-65 transition-opacity hover:opacity-100 focus-visible:opacity-100",+ "focus-visible:ring-1 focus-visible:ring-[#e7c46e]/80",+ // `!` so a drag that carries the pointer out of the pane does not+ // fade the rail out from under the hand still holding it.+ dragging ? "cursor-grabbing !opacity-100" : "cursor-grab",)}+ style={{ background: shell }}+ ><div- ref={trackRef}- role={exact ? "scrollbar" : "group"}- aria-label={- exact ? `Scroll ${name}` : `Scroll ${name} application history`- }- aria-controls={controlsId}- aria-orientation={exact ? "vertical" : undefined}- aria-valuemin={exact ? 0 : undefined}- aria-valuemax={exact ? Math.max(1, view.maxLine) : undefined}- aria-valuenow={exact ? view.line : undefined}- aria-valuetext={exact ? valueText : undefined}- tabIndex={exact ? 0 : undefined}- data-testid={`pane-scroll-rail-${name}`}- data-scroll-mode={view.owner}- data-scroll-position={exact ? "exact" : "none"}- title={valueText}- onPointerDown={onPointerDown}- onPointerMove={onPointerMove}- onPointerUp={onPointerUp}- onPointerCancel={(event) => finishDrag(event.pointerId)}- onLostPointerCapture={(event) => finishDrag(event.pointerId)}- onPointerLeave={() => {- if (dragRef.current && !dragRef.current.captured) finishDrag();- }}- onKeyDown={onKeyDown}+ ref={thumbRef}+ data-pane-scroll-thumb="true"+ data-testid={`pane-scroll-thumb-${name}`}className={cn(- "group absolute inset-y-1 right-0 z-10 w-3 touch-none select-none rounded-full outline-none",- "transition-opacity hover:opacity-100 focus-visible:opacity-100 focus-within:opacity-100",- // BOTH rail kinds stay legible at rest, at the same level. The- // application rail used to hide until the pointer entered its pane,- // and a control that is invisible next to a sibling pane's visible- // thumb reads as "the scrollbar is broken in this CLI".- "opacity-65",- "focus-visible:ring-1 focus-visible:ring-[#e7c46e]/80 focus-within:ring-1 focus-within:ring-[#e7c46e]/80",- // `!` so a stroke that carries the pointer out of the pane does not- // fade the rail out from under the hand still holding it.- dragging ? "cursor-grabbing !opacity-100" : "cursor-grab",- )}- style={{ background: shell }}- >- {!exact && (- <>- <button- type="button"- aria-label={`Scroll older in ${name}`}- aria-controls={controlsId}- onPointerDown={(event) => event.stopPropagation()}- onClick={() => scrollApplicationPage(-1)}- className={cn(- "absolute inset-x-0 top-0 flex h-4 items-start justify-center rounded-t-full pt-1",- "text-[#e7c46e]/70 outline-none hover:text-[#e7c46e] focus-visible:text-[#e7c46e]",- )}- >- <svg- viewBox="0 0 8 5"- className="h-[5px] w-2 fill-current"- aria-hidden="true"- >- <path d="M4 0 8 5H0Z" />- </svg>- </button>- <button- type="button"- aria-label={`Scroll newer in ${name}`}- aria-controls={controlsId}- onPointerDown={(event) => event.stopPropagation()}- onClick={() => scrollApplicationPage(1)}- className={cn(- "absolute inset-x-0 bottom-0 flex h-4 items-end justify-center rounded-b-full pb-1",- "text-[#e7c46e]/70 outline-none hover:text-[#e7c46e] focus-visible:text-[#e7c46e]",- )}- >- <svg- viewBox="0 0 8 5"- className="h-[5px] w-2 fill-current"- aria-hidden="true"- >- <path d="M4 5 0 0h8Z" />- </svg>- </button>- </>- )}- {/*- The application grip: grabbable, but positionless. It rests in the- middle, rides along while a stroke is held, and springs back on- release — see the module docstring for why it must never stay where- the drag left it. Pointer events bubble to the track's stroke- handlers; the grip itself adds nothing but a place to hold.- */}- {!exact && (- <div- ref={gripRef}- data-testid={`pane-scroll-grip-${name}`}- role="presentation"- title={t("agentic_grid.conversation.grip_hint")}- className={cn(- "absolute left-1/2 top-1/2 w-2 rounded-full bg-[#e7c46e]/45",- "shadow-[0_0_0_1px_rgba(0,0,0,0.18)]",- "group-hover:bg-[#e7c46e]/80 group-focus-within:bg-[#e7c46e]/80",- dragging- ? "bg-[#e7c46e] transition-none"- : "transition-transform duration-200",- )}- style={{- height: GRIP_PX,- transform: `translate(-50%, calc(-50% + ${gripOffset}px))`,- }}- >- <svg- viewBox="0 0 8 28"- className="h-full w-full fill-[#141210]/70"- aria-hidden="true"- >- {/* While held, the dots become an arrow in the direction the hand- is moving — the gesture's receipt, since the grip itself will- not stay anywhere. */}- {dragging && gripOffset < 0 ? (- <path d="M4 9 7 15H1Z" />- ) : dragging && gripOffset > 0 ? (- <path d="M4 19 1 13h6Z" />- ) : (- <>- <circle cx="4" cy="10" r="1.1" />- <circle cx="4" cy="14" r="1.1" />- <circle cx="4" cy="18" r="1.1" />- </>- )}- </svg>- </div>- )}- {/*- The thumb exists only where a position does — an application pane gets- the self-centring grip above instead, never a shape that stays where- the drag left it.- */}- {exact && (- <div- ref={thumbRef}- data-pane-scroll-thumb="true"- data-testid={`pane-scroll-thumb-${name}`}- className={cn(- "absolute right-[3px] w-1.5 rounded-full bg-[#e7c46e]/65",- "shadow-[0_0_0_1px_rgba(0,0,0,0.18)] transition-[background-color,top]",- "group-hover:bg-[#e7c46e]/90 group-focus-visible:bg-[#e7c46e]/90",- dragging && "bg-[#e7c46e] transition-none",- )}- style={{ top: geometry.top, height: geometry.height }}- />+ "absolute right-[3px] w-1.5 rounded-full bg-[#e7c46e]/65",+ "shadow-[0_0_0_1px_rgba(0,0,0,0.18)] transition-[background-color,top]",+ "group-hover:bg-[#e7c46e]/90 group-focus-visible:bg-[#e7c46e]/90",+ dragging && "bg-[#e7c46e] transition-none",)}- </div>- </>+ style={{ top: geometry.top, height: geometry.height }}+ />+ </div>);}diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.tsindex e51b0a8535..1daa055168 100644--- a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts@@ -1,18 +1,12 @@import type { Terminal } from "@xterm/xterm";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import {- applicationPageNotches,bindTerminalScrollRegion,- createLiveTuiWheelHandler,+ captureWheelForTerminalHistory,forwardWheelToTerminal,- installLiveTuiCursorTracking,lineAtThumbTop,readTerminalScrollView,- scrollApplication,- scrollLiveCursor,scrollThumbGeometry,- strokeUnits,- terminalScrollOwner,} from "./terminalScrollSurface";function write(term: Terminal, data: string): Promise<void> {@@ -40,280 +34,140 @@ async function newTerminal(): Promise<Terminal> {function terminalDouble(tracking: "none" | "any",type: "normal" | "alternate",-): Terminal & { input: ReturnType<typeof vi.fn> } {+ { baseY = 0, viewportY = 0 } = {},+): Terminal & { scrollLines: ReturnType<typeof vi.fn> } {return {rows: 24,modes: { mouseTrackingMode: tracking },- buffer: { active: { type, baseY: 0, viewportY: 0 } },- input: vi.fn(),- } as unknown as Terminal & { input: ReturnType<typeof vi.fn> };+ buffer: { active: { type, baseY, viewportY } },+ scrollLines: vi.fn(),+ } as unknown as Terminal & { scrollLines: ReturnType<typeof vi.fn> };}-describe("terminalScrollSurface", () => {- it("uses the real xterm parser to distinguish scrollback from every TUI mode", async () => {- const term = await newTerminal();- try {- expect(terminalScrollOwner(term)).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(terminalScrollOwner(term)).toBe("application");-- await write(- term,- "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1049l",- );- expect(terminalScrollOwner(term)).toBe("terminal");- } finally {- term.dispose();- }- });+function wheel(init: WheelEventInit): WheelEvent {+ return new WheelEvent("wheel", { deltaMode: WheelEvent.DOM_DELTA_PIXEL, ...init });+}- it("maps a normal buffer to an exact conventional thumb", () => {- const term = {- rows: 20,- modes: { mouseTrackingMode: "none" },- buffer: { active: { type: "normal", baseY: 80, viewportY: 40 } },- } as unknown as Terminal;+describe("terminalScrollSurface", () => {+ it("reads the exact xterm position for every pane the same way", () => {+ const term = terminalDouble("none", "normal", { baseY: 80, viewportY: 40 });const view = readTerminalScrollView(term);- expect(view).toEqual({ owner: "terminal", rows: 20, maxLine: 80, line: 40 });- expect(scrollThumbGeometry(view, 200)).toEqual({ top: 80, height: 40 });- expect(lineAtThumbTop(view, 0, 200)).toBe(0);- expect(lineAtThumbTop(view, 80, 200)).toBe(40);- expect(lineAtThumbTop(view, 160, 200)).toBe(80);- });-- it("tracks hidden-cursor live views through the real xterm parser", async () => {- const term = await newTerminal();- const states: boolean[] = [];- const tracking = installLiveTuiCursorTracking(term.parser, (active) =>- states.push(active),- );- try {- await write(term, "\x1b[?25l");- await write(term, "\x1b[?25l");- expect(states).toEqual([true]);-- tracking.reset();- expect(states).toEqual([true, false]);- await write(term, "\x1b[?25l");- await write(term, "\x1b[?25h");- expect(states).toEqual([true, false, true, false]);-- await write(term, "\x1b[?25l");- await write(term, "\x1b[!p");- expect(states).toEqual([true, false, true, false, true, false]);-- await write(term, "\x1b[?25l");- await write(term, "\x1bc");- expect(states).toEqual([- true,- false,- true,- false,- true,- false,- true,- false,- ]);- } finally {- tracking.dispose();- term.dispose();- }+ expect(view).toEqual({ rows: 24, maxLine: 80, line: 40, altScreen: false });+ expect(scrollThumbGeometry(view, 208)).toEqual({ top: 80, height: 48 });+ expect(lineAtThumbTop(view, 0, 208)).toBe(0);+ expect(lineAtThumbTop(view, 80, 208)).toBe(40);+ expect(lineAtThumbTop(view, 160, 208)).toBe(80);});- it("offers NO thumb geometry for an application-owned screen", () => {- // The regression this pins: twice a shape was drawn in this track — once- // parked in the middle, once at a measured offset — and both times the- // maintainer read it as "you are here" and both times it was wrong. A zero- // height is the instruction to draw nothing at all.- const view = readTerminalScrollView(terminalDouble("any", "alternate"));-- expect(view).toEqual({ owner: "application", rows: 24, maxLine: 0, line: 0 });- expect(scrollThumbGeometry(view, 200)).toEqual({ top: 0, height: 0 });- expect(scrollThumbGeometry(view, 900)).toEqual({ top: 0, height: 0 });- });+ it("fills the whole track before any history exists — never a fake position", () => {+ const empty = readTerminalScrollView(terminalDouble("none", "normal"));+ expect(empty.maxLine).toBe(0);+ expect(scrollThumbGeometry(empty, 200)).toEqual({ top: 0, height: 200 });- it("converts a stroke into whole relay units and carries the remainder", () => {- // 3px per unit: five units and 2px left over for the next pointer event,- // so a slow drag accumulates instead of being rounded away to nothing.- expect(strokeUnits(17)).toEqual({ units: 5, consumedPx: 15 });- expect(strokeUnits(-17)).toEqual({ units: 5, consumedPx: -15 });- expect(strokeUnits(2)).toEqual({ units: 0, consumedPx: 0 });- expect(strokeUnits(0)).toEqual({ units: 0, consumedPx: 0 });- expect(strokeUnits(50, 25)).toEqual({ units: 2, consumedPx: 50 });+ const alt = readTerminalScrollView(terminalDouble("any", "alternate"));+ expect(alt.altScreen).toBe(true);+ expect(scrollThumbGeometry(alt, 200)).toEqual({ top: 0, height: 200 });});- it("relays standard wheel reports through xterm for a mouse-aware coding TUI", () => {- const host = document.createElement("div");- const screen = document.createElement("div");- screen.className = "xterm-screen";- host.append(screen);- const term = terminalDouble("any", "alternate");- const deltas: number[] = [];- screen.addEventListener("wheel", (event) => deltas.push(event.deltaY));+ it("keeps the wheel on xterm history while a normal-buffer CLI tracks the mouse", () => {+ const term = terminalDouble("any", "normal", { baseY: 300, viewportY: 300 });+ const handler = captureWheelForTerminalHistory(term);- expect(scrollApplication(term, host, -1, 3)).toBe(3);- expect(scrollApplication(term, host, 1, 2)).toBe(2);+ // 120 wheel pixels = three rows, handled here — never a mouse report.+ expect(handler(wheel({ deltaY: 120 }))).toBe(false);+ expect(term.scrollLines).toHaveBeenCalledWith(3);- expect(deltas).toEqual([-1, -1, -1, 1, 1]);- expect(term.input).not.toHaveBeenCalled();- });-- it("falls back to standard page keys for an alternate screen without mouse mode", () => {- const term = terminalDouble("none", "alternate");- const page = applicationPageNotches(term.rows);-- expect(scrollApplication(term, null, -1, page)).toBe(1);- expect(scrollApplication(term, null, 1, page * 2)).toBe(2);- expect(term.input.mock.calls.map((call) => call[0])).toEqual([- "\x1b[5~",- "\x1b[6~",- "\x1b[6~",- ]);- });-- it("reveals all eight rows after explicit live-view activation", () => {- const term = terminalDouble("none", "normal");- const agents = Array.from(- { length: 8 },- (_, index) => `agent-${index + 1}`,- );- let selected = 4;- term.input.mockImplementation((data: string) => {- for (const sequence of data.matchAll(/\x1b\[([AB])/g)) {- selected = Math.max(- 0,- Math.min(- agents.length - 1,- selected + (sequence[1] === "B" ? 1 : -1),- ),- );- }- });- const visible = () => {- const start = Math.min(Math.max(0, selected - 4), agents.length - 5);- return agents.slice(start, start + 5);- };- const handleWheel = createLiveTuiWheelHandler(term, () => true);-- expect(visible()).toEqual(agents.slice(0, 5));+ // Sub-row trackpad deltas accumulate instead of being rounded away.+ term.scrollLines.mockClear();+ expect(handler(wheel({ deltaY: -25 }))).toBe(false);+ expect(term.scrollLines).not.toHaveBeenCalled();+ expect(handler(wheel({ deltaY: -25 }))).toBe(false);+ expect(term.scrollLines).toHaveBeenCalledWith(-1);+ // Line-mode wheels scroll whole lines 1:1.+ term.scrollLines.mockClear();expect(- handleWheel(- new WheelEvent("wheel", {- deltaMode: WheelEvent.DOM_DELTA_PIXEL,- deltaY: 120,- }),- ),+ handler(wheel({ deltaY: 2, deltaMode: WheelEvent.DOM_DELTA_LINE })),).toBe(false);- expect(term.input).toHaveBeenCalledWith("\x1b[B".repeat(3), true);- expect(visible()).toEqual(agents.slice(3, 8));-- expect(handleWheel(new WheelEvent("wheel", { deltaY: -40 }))).toBe(false);- expect(term.input).toHaveBeenLastCalledWith("\x1b[A", true);+ expect(term.scrollLines).toHaveBeenCalledWith(2);});- it("keeps both wheel directions native without explicit activation", () => {- const term = terminalDouble("none", "normal");- const handleWheel = createLiveTuiWheelHandler(term, () => false);-- expect(handleWheel(new WheelEvent("wheel", { deltaY: 120 }))).toBe(true);- expect(handleWheel(new WheelEvent("wheel", { deltaY: -120 }))).toBe(true);- expect(term.input).not.toHaveBeenCalled();- });-- it("keeps Shift+wheel as access to exact xterm history", () => {- const term = terminalDouble("none", "normal");- const handleWheel = createLiveTuiWheelHandler(term, () => true);+ it("stays native wherever xterm's default behaviour is already right", () => {+ // No tracking: xterm scrolls its own viewport without help.+ const plain = terminalDouble("none", "normal");+ expect(captureWheelForTerminalHistory(plain)(wheel({ deltaY: 120 }))).toBe(+ true,+ );+ expect(plain.scrollLines).not.toHaveBeenCalled();- expect(- handleWheel(new WheelEvent("wheel", { deltaY: -120, shiftKey: true })),- ).toBe(true);- expect(term.input).not.toHaveBeenCalled();+ // Alternate screen: the app owns the screen and keeps its protocols.+ const alt = terminalDouble("any", "alternate");+ expect(captureWheelForTerminalHistory(alt)(wheel({ deltaY: 120 }))).toBe(+ true,+ );+ expect(alt.scrollLines).not.toHaveBeenCalled();++ // Modifier chords and horizontal gestures stay native too.+ const tracked = terminalDouble("any", "normal");+ const handler = captureWheelForTerminalHistory(tracked);+ expect(handler(wheel({ deltaY: 120, shiftKey: true }))).toBe(true);+ expect(handler(wheel({ deltaY: 120, ctrlKey: true }))).toBe(true);+ expect(handler(wheel({ deltaY: 10, deltaX: 50 }))).toBe(true);+ expect(tracked.scrollLines).not.toHaveBeenCalled();});- it("leaves negotiated normal-buffer mouse tracking untouched", () => {- const term = terminalDouble("any", "normal");- Object.assign(term.modes, { applicationCursorKeysMode: true });- const handleWheel = createLiveTuiWheelHandler(term, () => true);-- expect(- handleWheel(- new WheelEvent("wheel", {- deltaMode: WheelEvent.DOM_DELTA_LINE,- deltaY: -2,- }),- ),- ).toBe(true);- expect(term.input).not.toHaveBeenCalled();- });+ it("recognises tracking negotiated through the real xterm parser", async () => {+ const term = await newTerminal();+ const scrollLines = vi.spyOn(term, "scrollLines");+ const handler = captureWheelForTerminalHistory(term);+ try {+ expect(handler(wheel({ deltaY: 120 }))).toBe(true);- it("leaves alternate-screen mouse protocols untouched", () => {- const term = terminalDouble("any", "alternate");- const handleWheel = createLiveTuiWheelHandler(term, () => true);+ await write(term, "\x1b[?1000h\x1b[?1006h");+ expect(handler(wheel({ deltaY: 120 }))).toBe(false);+ expect(scrollLines).toHaveBeenCalledWith(3);- expect(handleWheel(new WheelEvent("wheel", { deltaY: 120 }))).toBe(true);- expect(term.input).not.toHaveBeenCalled();+ await write(term, "\x1b[?1006l\x1b[?1000l");+ expect(handler(wheel({ deltaY: 120 }))).toBe(true);+ } finally {+ term.dispose();+ }});- it("accumulates fine trackpad input without moving two histories", () => {- const term = terminalDouble("none", "normal");- const handleWheel = createLiveTuiWheelHandler(term, () => true);-- expect(handleWheel(new WheelEvent("wheel", { deltaY: 20 }))).toBe(false);- expect(term.input).not.toHaveBeenCalled();- expect(handleWheel(new WheelEvent("wheel", { deltaY: 20 }))).toBe(false);- expect(term.input).toHaveBeenCalledWith("\x1b[B", true);- });+ it("forwards a rail wheel to the xterm screen unchanged", () => {+ const host = document.createElement("div");+ const screen = document.createElement("div");+ screen.className = "xterm-screen";+ host.append(screen);+ const seen: WheelEvent[] = [];+ screen.addEventListener("wheel", (event) => seen.push(event));- it("emits no more cursor rows than one bounded wheel action", () => {- const term = terminalDouble("none", "normal");+ forwardWheelToTerminal(+ host,+ wheel({ deltaY: 120, deltaX: 5, shiftKey: true }),+ );- expect(scrollLiveCursor(term, 1, 100)).toBe(12);- expect(term.input).toHaveBeenCalledOnce();- expect(term.input).toHaveBeenCalledWith("\x1b[B".repeat(12), true);+ expect(seen).toHaveLength(1);+ expect(seen[0].deltaY).toBe(120);+ expect(seen[0].deltaX).toBe(5);+ expect(seen[0].shiftKey).toBe(true);});- it("forwards the wheel over a rail unchanged and contains the workspace", () => {- const workspace = document.createElement("div");+ it("contains wheel input inside the terminal region", () => {const region = document.createElement("div");- const host = document.createElement("div");- const xtermScreen = document.createElement("div");- xtermScreen.className = "xterm-screen";- workspace.append(region);- region.append(host);- host.append(xtermScreen);- const terminalWheel = vi.fn();- const workspaceWheel = vi.fn();- xtermScreen.addEventListener("wheel", terminalWheel);- workspace.addEventListener("wheel", workspaceWheel);- const dispose = bindTerminalScrollRegion(region);- try {- const source = new WheelEvent("wheel", {- bubbles: true,- cancelable: true,- deltaMode: WheelEvent.DOM_DELTA_PIXEL,- deltaX: 4,- deltaY: 120,- shiftKey: true,- });+ const parentSaw = vi.fn();+ document.body.append(region);+ document.body.addEventListener("wheel", parentSaw);+ const unbind = bindTerminalScrollRegion(region);- expect(forwardWheelToTerminal(host, source)).toBe(true);- expect(terminalWheel).toHaveBeenCalledOnce();- const forwarded = terminalWheel.mock.calls[0][0] as WheelEvent;- expect(forwarded.deltaX).toBe(4);- expect(forwarded.deltaY).toBe(120);- expect(forwarded.deltaMode).toBe(WheelEvent.DOM_DELTA_PIXEL);- expect(forwarded.shiftKey).toBe(true);- expect(workspaceWheel).not.toHaveBeenCalled();- } finally {- dispose();- }+ region.dispatchEvent(+ new WheelEvent("wheel", { deltaY: 120, bubbles: true, cancelable: true }),+ );+ expect(parentSaw).not.toHaveBeenCalled();++ unbind();+ document.body.removeEventListener("wheel", parentSaw);+ region.remove();});});diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.tsindex beea2732f7..cc1817d961 100644--- a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts@@ -1,48 +1,37 @@/**- * Provider-neutral terminal scrolling primitives.- *- * A terminal has one of two scroll owners:- *- * * xterm owns a normal buffer, so its exact line and extent are public;- * * a full-screen application owns an alternate/mouse-tracking buffer, or the- * user explicitly activates a keyboard-owned inline view, so the only- * truthful operation is to relay scroll input to that application.- *- * In the second case there is NO POSITION. Not an estimated one — none, so- * that nothing on screen can be read as an answer to "where am I". The rail- * there is a control: arrow caps that page, a strip that scrolls when stroked,- * the wheel passing through, and a self-centring grip that makes the stroke- * grabbable. The grip is allowed precisely because it ALWAYS springs back to- * centre on release — a handle that never stays put cannot be read as a- * position, where both reverted attempts below drew shapes that did stay put.- *- * Two attempts to show a position anyway are on record, both reverted after the- * maintainer used them:- *- * 1. Counting wheel events and reading one CLI's screen text for its endpoints.- * Drifted in that CLI and was wrong in every other one.- * 2. Counting relayed units and treating "the application did not repaint" as an- * end (2026-08-08). Sound on paper and green in tests; in the real pane the- * grip still read as stuck near the middle, a drag to the top moved the- * transcript by a fraction of the way, and letting go put the grip back.- *- * The lesson both times is the same: a full-screen application's scroll state- * lives in that process, an approximation of it LOOKS exactly like a position,- * and a position that is even slightly wrong is worse than an honest control —- * the user trusts it, acts on it, and is misled. Do not try a third time unless- * the CLI itself reports where it is.+ * Terminal scrolling with ONE rule: xterm owns scrolling, always.+ *+ * Every pane, every provider, every CLI mode shows the same scrollbar — the+ * exact xterm viewport position — and the wheel always moves xterm's own+ * scrollback. This file used to hold a second "application-owned" regime+ * (owner switching, stroke gestures, PageUp/arrow-key relays, a self-centring+ * grip, an opt-in live-view navigation). Four iterations of it produced eight+ * confirmed defects in one review (2026-08-08, xhigh) — mode flips mid-drag+ * typed keys into the CLI, a 3px stroke step catapulted alternate-screen+ * apps, the rail morphed shapes on a 750ms poll, and a second native+ * scrollbar double-drew next to this one. The maintainer's verdict after+ * living with it was to remove the whole regime.+ *+ * What makes the single rule honest today: the current coding CLIs (Claude+ * Code 2.1.226, Codex) paint the NORMAL buffer line by line — measured via a+ * ConPTY probe, no alt-screen (1049), no mouse tracking at boot — so xterm's+ * scrollback is the real transcript and its position is the real position.+ * A CLI that briefly negotiates mouse tracking mid-session does not get the+ * wheel handed to it: `captureWheelForTerminalHistory` keeps wheel input on+ * xterm's history, which is exactly how Windows Terminal treats these CLIs.+ * Only a true alternate-screen application (vim, less) keeps its negotiated+ * protocols — there xterm has no history, and the rail says so.*/import type { Terminal } from "@xterm/xterm";-export type TerminalScrollOwner = "terminal" | "application";-export interface TerminalScrollView {- owner: TerminalScrollOwner;rows: number;- /** Last exact viewport line. Zero for an application-owned screen. */+ /** Last xterm viewport line. Zero while no history has scrolled off yet. */maxLine: number;- /** Current exact viewport line. Zero for an application-owned screen. */+ /** Current xterm viewport line. */line: number;+ /** True while an alternate-screen app (vim, less) owns the screen. */+ altScreen: boolean;}export interface ScrollThumbGeometry {@@ -50,46 +39,12 @@ export interface ScrollThumbGeometry {height: number;}-/** The CSI slice used to observe cursor visibility without handling the mode. */-export interface TerminalModeParser {- registerCsiHandler(- id: { prefix?: string; intermediates?: string; final: string },- callback: (params: (number | number[])[]) => boolean,- ): { dispose(): void };- registerEscHandler(- id: { intermediates?: string; final: string },- callback: () => boolean,- ): { dispose(): void };-}--export interface LiveTuiCursorTracking {- /** Reset local mode state before a terminal replay/reset boundary. */- reset(): void;- dispose(): void;-}-export const MIN_THUMB_PX = 28;-const MAX_RELAY_NOTCHES = 80;-const PAGE_UP = "\x1b[5~";-const PAGE_DOWN = "\x1b[6~";-const CURSOR_UP = "\x1b[A";-const CURSOR_DOWN = "\x1b[B";-const APPLICATION_CURSOR_UP = "\x1bOA";-const APPLICATION_CURSOR_DOWN = "\x1bOB";-const WHEEL_PIXELS_PER_CURSOR_ROW = 40;-const MAX_CURSOR_ROWS_PER_WHEEL = 12;-/**- * Pixels of pointer travel per relayed unit when stroking an application rail.- *- * A stroke, not a jump to a position: the gesture says "keep going this way",- * which is the only thing the rail can honestly promise when the application- * owns the history. At 7 the maintainer's verdict on a real Claude pane was- * "you drag and almost nothing happens" — a grip that moves the transcript- * less than the hand moved feels dead, so the step errs brisk rather than- * fine; the wheel remains the fine-grained gesture.- */-export const STROKE_STEP_PX = 3;+/** Pixels of wheel travel per scrolled row when the wheel reports pixels. */+const WHEEL_PIXELS_PER_ROW = 40;+/** Ceiling per wheel event, so one coalesced trackpad burst cannot teleport. */+const MAX_ROWS_PER_WHEEL = 40;function clamp(value: number, low: number, high: number): number {return Math.min(high, Math.max(low, value));@@ -100,40 +55,20 @@ function finiteWhole(value: unknown): number {return Number.isFinite(number) ? Math.max(0, Math.floor(number)) : 0;}-/** Which side can truthfully answer where this pane is scrolled. */-export function terminalScrollOwner(- term: Terminal,- liveTuiActive = false,-): TerminalScrollOwner {- const tracking = term.modes?.mouseTrackingMode ?? "none";- const bufferType = term.buffer?.active?.type ?? "normal";- return liveTuiActive || bufferType === "alternate" || tracking !== "none"- ? "application"- : "terminal";-}--/** Read a scroll view without inspecting or interpreting terminal content. */-export function readTerminalScrollView(- term: Terminal,- liveTuiActive = false,-): TerminalScrollView {- const owner = terminalScrollOwner(term, liveTuiActive);- const rows = Math.max(1, finiteWhole(term.rows));- if (owner === "application") {- return { owner, rows, maxLine: 0, line: 0 };- }+/** The exact xterm viewport position — the only scroll truth this UI shows. */+export function readTerminalScrollView(term: Terminal): TerminalScrollView {const active = term.buffer?.active;+ const rows = Math.max(1, finiteWhole(term.rows));const maxLine = finiteWhole(active?.baseY);- const line = clamp(finiteWhole(active?.viewportY), 0, maxLine);- return { owner, rows, maxLine, line };+ return {+ rows,+ maxLine,+ line: clamp(finiteWhole(active?.viewportY), 0, maxLine),+ altScreen: (active?.type ?? "normal") === "alternate",+ };}-/**- * Geometry for the exact thumb, and the absence of one everywhere else.- *- * A zero height means "draw no thumb" — the caller renders nothing rather than- * a shape the user would read as a position. See the module docstring.- */+/** Thumb geometry. With no history yet the thumb honestly fills the track. */export function scrollThumbGeometry(view: TerminalScrollView,trackPx: number,@@ -141,8 +76,6 @@ export function scrollThumbGeometry(): ScrollThumbGeometry {const track = Math.max(0, trackPx);if (track === 0) return { top: 0, height: 0 };- if (view.owner === "application") return { top: 0, height: 0 };-if (view.maxLine === 0) return { top: 0, height: track };const contentLines = view.maxLine + view.rows;const height = clamp(@@ -157,13 +90,13 @@ export function scrollThumbGeometry(};}-/** Map a dragged exact thumb back to xterm's absolute viewport line. */+/** Map a dragged thumb back to xterm's absolute viewport line. */export function lineAtThumbTop(view: TerminalScrollView,topPx: number,trackPx: number,): number {- if (view.owner !== "terminal" || view.maxLine === 0) return 0;+ if (view.maxLine === 0) return 0;const thumb = scrollThumbGeometry(view, trackPx);const travel = Math.max(0, trackPx - thumb.height);if (travel === 0) return view.maxLine;@@ -171,135 +104,21 @@ export function lineAtThumbTop(}/**- * Turn pointer travel along the rail into relayed units.- *- * Returns whole units and the pixels they consumed, so the caller can carry the- * remainder into the next pointer event instead of losing it — a stroke has to- * feel continuous even though the relay protocol is discrete.- */-export function strokeUnits(- deltaPx: number,- stepPx = STROKE_STEP_PX,-): { units: number; consumedPx: number } {- const step = Math.max(1, stepPx);- const units = Math.floor(Math.abs(deltaPx) / step);- if (units === 0) return { units: 0, consumedPx: 0 };- return { units, consumedPx: Math.sign(deltaPx) * units * step };-}--/** A page expressed in the wheel reports used by mouse-aware coding TUIs. */-export function applicationPageNotches(rows: number): number {- // Measured coding TUIs move roughly three transcript rows per report.- return Math.max(1, Math.ceil(Math.max(1, rows) / 3));-}--/**- * Track cursor visibility as a candidate signal for a live drawn view.- *- * This is deliberately NOT an input-ownership decision: progress indicators- * and disabled prompts also hide the cursor. A separate explicit user action- * must activate cursor-key navigation while this candidate remains present.- *- * The handlers return false, so xterm still performs DECSET/DECRST itself. The- * caller owns reset boundaries because `Terminal.reset()` is a local API call- * and therefore does not pass through the parser.+ * Keep the wheel on xterm's history even when a normal-buffer CLI has+ * negotiated mouse tracking.+ *+ * Wired via `term.attachCustomWheelEventHandler`. Returning true lets xterm+ * handle the event as usual; returning false means this handler already did.+ *+ * The one intercepted case: normal buffer + mouse tracking on. Left to xterm,+ * that wheel would become mouse reports typed at the CLI — scrolling would+ * "work" only while the CLI feels like it, which is the mode-dependent+ * inconsistency this rebuild removes. An alternate-screen app keeps every+ * negotiated protocol: xterm has no history there to scroll instead.+ * Modifier chords (ctrl=zoom, shift=app escape hatch) stay native.*/-export function installLiveTuiCursorTracking(- parser: TerminalModeParser,- onActive: (active: boolean) => void,-): LiveTuiCursorTracking {- let active = false;- const update = (next: boolean) => {- if (next === active) return;- active = next;- onActive(next);- };- const carriesCursorMode = (params: (number | number[])[]) =>- params.some((param) =>- Array.isArray(param) ? param.includes(25) : param === 25,- );- const handlers = [- parser.registerCsiHandler({ prefix: "?", final: "l" }, (params) => {- if (carriesCursorMode(params)) update(true);- return false;- }),- parser.registerCsiHandler({ prefix: "?", final: "h" }, (params) => {- if (carriesCursorMode(params)) update(false);- return false;- }),- // DECSTR and RIS restore cursor visibility without emitting `?25h`.- // Observe both while leaving xterm's reset implementation in charge.- parser.registerCsiHandler({ intermediates: "!", final: "p" }, () => {- update(false);- return false;- }),- parser.registerEscHandler({ final: "c" }, () => {- update(false);- return false;- }),- ];- return {- reset: () => update(false),- dispose: () => {- update(false);- for (const handler of handlers) handler.dispose();- },- };-}--/**- * Move the selection/viewport of a keyboard-driven live TUI by whole rows.- *- * Inline coding-agent views are often drawn in the normal terminal buffer but- * keep a windowed list of their own. Claude Code's workflow agent list is one- * example: xterm can scroll the surrounding transcript, while the rows omitted- * from that live list exist only inside Claude Code and are reached with cursor- * keys. Use xterm's current cursor-key mode so the bytes match what a physical- * ArrowUp/ArrowDown press would have produced.- */-export function scrollLiveCursor(+export function captureWheelForTerminalHistory(term: Terminal,- direction: -1 | 1,- rows = 1,-): number {- const count = Math.min(- MAX_CURSOR_ROWS_PER_WHEEL,- Math.max(0, Math.floor(rows)),- );- if (count === 0) return 0;- const applicationKeys = term.modes?.applicationCursorKeysMode === true;- const sequence =- direction < 0- ? applicationKeys- ? APPLICATION_CURSOR_UP- : CURSOR_UP- : applicationKeys- ? APPLICATION_CURSOR_DOWN- : CURSOR_DOWN;- // One user action, one PTY/WebSocket frame. Repeating term.input here would- // recreate the frame-count amplification that made long prompt delivery lag.- term.input(sequence.repeat(count), true);- return count;-}--/**- * Give wheel input to an explicitly activated inline TUI view.- *- * Two histories can share a normal xterm buffer:- *- * * xterm's exact transcript, which keeps ordinary wheel behaviour; and- * * a live, windowed block owned by the coding CLI, whose omitted rows are not- * terminal scrollback at all.- *- * `isLiveTuiActive` is an explicit user opt-in, not a guess derived from output- * or cursor visibility. While it is active, both directions belong to the live- * view. Shift+wheel is deliberately left native as the escape hatch to exact- * terminal history. Plain prompts and every negotiated mouse protocol also- * remain native.- */-export function createLiveTuiWheelHandler(- term: Terminal,- isLiveTuiActive: () => boolean,): (event: WheelEvent) => boolean {let pixelRemainder = 0;@@ -314,22 +133,17 @@ export function createLiveTuiWheelHandler(pixelRemainder = 0;return true;}-- const active = term.buffer?.active;- const bufferType = active?.type ?? "normal";+ const bufferType = term.buffer?.active?.type ?? "normal";const tracking = term.modes?.mouseTrackingMode ?? "none";- const direction: -1 | 1 = event.deltaY < 0 ? -1 : 1;- const keyboardOwnedLiveView =- bufferType === "normal" && tracking === "none" && isLiveTuiActive();-- if (!keyboardOwnedLiveView) {+ if (bufferType === "alternate" || tracking === "none") {pixelRemainder = 0;return true;}+ const direction = event.deltaY < 0 ? -1 : 1;let rows: number;if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) {- rows = applicationPageNotches(term.rows);+ rows = Math.max(1, term.rows) * Math.abs(event.deltaY);pixelRemainder = 0;} else if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) {rows = Math.max(1, Math.ceil(Math.abs(event.deltaY)));@@ -339,61 +153,19 @@ export function createLiveTuiWheelHandler(pixelRemainder = 0;}pixelRemainder += event.deltaY;- rows = Math.floor(Math.abs(pixelRemainder) / WHEEL_PIXELS_PER_CURSOR_ROW);+ rows = Math.floor(Math.abs(pixelRemainder) / WHEEL_PIXELS_PER_ROW);if (rows > 0) {- pixelRemainder -= direction * rows * WHEEL_PIXELS_PER_CURSOR_ROW;+ pixelRemainder -= direction * rows * WHEEL_PIXELS_PER_ROW;}}-- if (rows > 0) scrollLiveCursor(term, direction, rows);- // Even a sub-row trackpad delta belongs to the accumulator above. Letting- // xterm also process it would emit a mouse report or move a second history.+ rows = Math.min(MAX_ROWS_PER_WHEEL, rows);+ if (rows > 0) term.scrollLines(direction * rows);+ // Even a sub-row remainder is accounted; xterm must not ALSO emit a+ // mouse report for the same physical notch.return false;};}-/**- * Relay older/newer movement to the application that owns the screen.- *- * Mouse-aware TUIs receive synthetic wheel events through xterm, which already- * knows the exact protocol the process negotiated. An alternate-screen app- * without mouse reporting receives the standard PageUp/PageDown key instead.- */-export function scrollApplication(- term: Terminal,- host: HTMLElement | null,- direction: -1 | 1,- notches = 1,-): number {- const count = Math.min(MAX_RELAY_NOTCHES, Math.max(0, Math.floor(notches)));- if (count === 0) return 0;- const tracking = term.modes?.mouseTrackingMode ?? "none";- if (tracking === "none") {- const pages = Math.max(1, Math.ceil(count / applicationPageNotches(term.rows)));- for (let index = 0; index < pages; index += 1) {- term.input(direction < 0 ? PAGE_UP : PAGE_DOWN, true);- }- return pages;- }-- const screen = host?.querySelector<HTMLElement>(".xterm-screen");- if (!screen || typeof WheelEvent === "undefined") return 0;- const box = screen.getBoundingClientRect();- for (let index = 0; index < count; index += 1) {- screen.dispatchEvent(- new WheelEvent("wheel", {- bubbles: true,- cancelable: true,- clientX: box.left + box.width / 2,- clientY: box.top + box.height / 2,- deltaMode: WheelEvent.DOM_DELTA_LINE,- deltaY: direction,- }),- );- }- return count;-}-/*** Forward a wheel that landed on the overlay rail to xterm unchanged.*diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.cssindex 4889b68116..de8bf01c58 100644--- a/jarvis/ui/web/frontend/src/index.css+++ b/jarvis/ui/web/frontend/src/index.css@@ -215,22 +215,19 @@display: none;}-/* 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 IDE panes draw exactly ONE scrollbar: the golden PaneScrollRail.+ The native viewport scrollbar is hidden unconditionally — when it was only+ hidden for application-owned panes, every normal-buffer pane double-drew+ an 8px grey native thumb underneath the rail, at a different position and+ with its hit area eaten by the rail overlay (confirmed review finding,+ 2026-08-08). 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[data-scroll-owner="application"]- .xterm-viewport::-webkit-scrollbar {+.agentic-terminal-host .xterm-viewport::-webkit-scrollbar {width: 0;height: 0;}