Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): rebuild terminal scroll rail
Ruben Lütke2c2f86fb0f36
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex 031294dcf1..e269714cfe 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -41,7 +41,14 @@* redrawing on every keystroke that is both slow and subtly misaligned. The* canvas renderer draws on a grid, which is what a terminal actually is.*/-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";+import {+ useCallback,+ useEffect,+ useId,+ useLayoutEffect,+ useRef,+ useState,+} from "react";import { Terminal } from "@xterm/xterm";import { FitAddon } from "@xterm/addon-fit";import { WebLinksAddon } from "@xterm/addon-web-links";@@ -101,7 +108,7 @@ import {PARKED_RECHECK_MS,} from "./offscreenBuffer";import { installQuerySuppression } from "./terminalQueries";-import { bindTerminalScrollSurface } from "./terminalScrollSurface";+import { PaneScrollRail } from "./PaneScrollRail";import {openPaneSocket,type PaneSocket,@@ -332,11 +339,14 @@ export function AgenticTerminal({layoutBusy = false,}: AgenticTerminalProps) {const containerRef = useRef<HTMLDivElement | null>(null);+ const terminalRegionRef = useRef<HTMLDivElement | null>(null);+ const terminalRegionId = useId();const termRef = useRef<Terminal | null>(null);const fitRef = useRef<FitAddon | null>(null);// Lets the font-size effect trigger a REAL resize (xterm + the terminal// process together) without reaching into the connect effect's socket.const resizeRef = useRef<(() => void) | null>(null);+ const claimResizeRef = useRef<(() => void) | null>(null);const visibilityRef = useRef<{ show: () => void; park: () => void } | null>(null);const statusRef = useRef<PaneStatus>("connecting");// Mirrored into state purely so the header can show/hide the restart button;@@ -358,6 +368,9 @@ export function AgenticTerminal({* Reconnects therefore stay quiet: the replayed screen is already there.*/const [painted, setPainted] = useState(false);+ // The terminal itself stays in a ref. This small epoch only tells the scroll+ // rail that the ref now points at a new instance after a restart.+ const [terminalEpoch, setTerminalEpoch] = useState(0);/*** The delivery this pane is currently showing a receipt for, if any.*@@ -470,7 +483,7 @@ export function AgenticTerminal({}termRef.current = term;fitRef.current = fit;- const disposeScrollSurface = bindTerminalScrollSurface(container, term);+ setTerminalEpoch((current) => current + 1);// Let the app-wide right-click menu reach this terminal. It cannot use the// browser selection here — the canvas renderer above paints the text, so// there is no selectable DOM to read — and it must paste through xterm so@@ -733,7 +746,14 @@ export function AgenticTerminal({*/let sentSize: { cols: number; rows: number } | null = null;- const sendResize = () => {+ const viewerMayOwn = () =>+ activeRef.current &&+ !documentHidden() &&+ (typeof document === "undefined" ||+ typeof document.hasFocus !== "function" ||+ document.hasFocus());++ const sendResize = (claimOwner = false) => {// A hidden pane measures 0x0 (maximizing another one hides this one), and// fitting to that would resize the PTY to zero columns — which permanently// wrecks the agent's full-screen drawing. Skip while not measurable; the@@ -759,15 +779,20 @@ export function AgenticTerminal({// Re-announcing a size makes the agent on the other end redraw its// entire screen, and a pane refits several times per settling layout.if (+ !claimOwner &&sentSize &&sentSize.cols === size.cols &&sentSize.rows === size.rows) {return;}- if (socket?.send({ t: "r", ...size })) sentSize = size;+ if (socket?.send({ t: claimOwner ? "claim" : "r", ...size })) sentSize = size;};resizeRef.current = sendResize;+ const claimResize = () => {+ if (viewerMayOwn()) sendResize(true);+ };+ claimResizeRef.current = claimResize;socket = openPaneSocket({@@ -776,6 +801,7 @@ export function AgenticTerminal({cols: term.cols || 80,rows: term.rows || 24,appearance: appearanceRef.current,+ claimOwner: viewerMayOwn(),},{onOpen: () => {@@ -989,10 +1015,12 @@ export function AgenticTerminal({const onDocumentVisible = () => {if (documentHidden()) return;revealIfOnScreen();+ claimResize();};if (typeof document !== "undefined") {document.addEventListener("visibilitychange", onDocumentVisible);}+ window.addEventListener("focus", claimResize);return () => {disposed = true;@@ -1004,6 +1032,7 @@ export function AgenticTerminal({// a disposed terminal inside a detached element.cancelPaneReflow(reflow);window.removeEventListener("resize", scheduleResize);+ window.removeEventListener("focus", claimResize);if (typeof document !== "undefined") {document.removeEventListener("visibilitychange", onDocumentVisible);}@@ -1013,7 +1042,6 @@ export function AgenticTerminal({disposePasteBridge();disposeNewlineBridge();disposeQuerySuppression();- disposeScrollSurface();try {socket?.close();} catch {@@ -1023,6 +1051,7 @@ export function AgenticTerminal({termRef.current = null;fitRef.current = null;resizeRef.current = null;+ claimResizeRef.current = null;if (visibilityRef.current === visibility) visibilityRef.current = null;};// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:@@ -1041,7 +1070,7 @@ export function AgenticTerminal({}const reveal = () => {visibilityRef.current?.show();- resizeRef.current?.();+ claimResizeRef.current?.();termRef.current?.scrollToBottom?.();};reveal();@@ -1201,7 +1230,10 @@ export function AgenticTerminal({return (<div- onMouseDown={onFocus}+ onMouseDown={() => {+ onFocus?.();+ claimResizeRef.current?.();+ }}{...dragHandlers}className={cn(// One quiet border per pane; the focused one carries the workspace's@@ -1262,6 +1294,8 @@ export function AgenticTerminal({xterm's canvas must not become its implicit minimum height.*/}<div+ ref={terminalRegionRef}+ id={terminalRegionId}className="relative min-h-0 flex-1 overflow-hidden px-1.5 pb-0.5 pt-0.5"><div@@ -1273,6 +1307,16 @@ export function AgenticTerminal({data-layout-busy={layoutBusy ? "true" : "false"}className="agentic-terminal-host h-full min-h-0 w-full overflow-hidden"/>+ <PaneScrollRail+ name={name}+ controlsId={terminalRegionId}+ regionRef={terminalRegionRef}+ hostRef={containerRef}+ terminalRef={termRef}+ epoch={terminalEpoch}+ appearance={appearance}+ onFocus={onFocus}+ />{/*The pane says it is starting, instead of being a black rectangle.diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsxnew file mode 100644index 0000000000..9198915dc2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx@@ -0,0 +1,281 @@+import { useRef } from "react";+import { act, fireEvent, render, screen } from "@testing-library/react";+import type { Terminal } from "@xterm/xterm";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { PaneScrollRail } from "./PaneScrollRail";++const nativePointerEvent = globalThis.PointerEvent;++class PointerEventHarness extends MouseEvent {+ readonly pointerId: number;++ constructor(type: string, init: PointerEventInit = {}) {+ super(type, init);+ this.pointerId = init.pointerId ?? 0;+ }+}++beforeAll(() => {+ // jsdom has pointer event names but no PointerEvent constructor, so Testing+ // Library would otherwise create an event with none of the drag coordinates.+ Object.defineProperty(globalThis, "PointerEvent", {+ configurable: true,+ value: PointerEventHarness,+ });+});++afterAll(() => {+ Object.defineProperty(globalThis, "PointerEvent", {+ configurable: true,+ value: nativePointerEvent,+ });+});++type Listener<T> = (value: T) => void;++function signal<T>() {+ const listeners = new Set<Listener<T>>();+ return {+ event(listener: Listener<T>) {+ listeners.add(listener);+ return { dispose: () => listeners.delete(listener) };+ },+ fire(value: T) {+ for (const listener of listeners) listener(value);+ },+ };+}++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;+}++function fakeTerminal({+ owner,+ line = 100,+ maxLine = 100,+}: {+ owner: "terminal" | "mouse-app" | "page-app";+ line?: number;+ maxLine?: number;+}): TerminalHarness {+ const scroll = signal<number>();+ const parsed = signal<void>();+ const changed = signal<unknown>();+ const active = {+ type: owner === "terminal" ? "normal" : "alternate",+ baseY: maxLine,+ viewportY: line,+ };+ const modes = {+ mouseTrackingMode: owner === "mouse-app" ? "any" : "none",+ };+ 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));+ scroll.fire(active.viewportY);+ });+ const input = vi.fn();+ const term = {+ rows: 20,+ modes,+ buffer: {+ active,+ onBufferChange: changed.event,+ },+ onScroll: scroll.event,+ onWriteParsed: parsed.event,+ scrollToLine,+ scrollLines,+ scrollToTop: vi.fn(() => scrollToLine(0)),+ scrollToBottom: vi.fn(() => scrollToLine(active.baseY)),+ input,+ } 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 };+}++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}>+ <div className="xterm-screen" data-testid={`xterm-screen-${name}`} />+ </div>+ <PaneScrollRail+ name={name}+ controlsId={`terminal-${name}`}+ regionRef={regionRef}+ hostRef={hostRef}+ terminalRef={terminalRef}+ epoch={1}+ appearance="dark"+ />+ </div>+ );+}++function giveTrackGeometry(name: string, height = 200): HTMLElement {+ const rail = screen.getByTestId(`pane-scroll-rail-${name}`);+ Object.defineProperty(rail, "clientHeight", {+ configurable: true,+ value: height,+ });+ rail.getBoundingClientRect = () =>+ ({+ top: 0,+ left: 0,+ right: 12,+ bottom: height,+ width: 12,+ height,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ }) as DOMRect;+ act(() => fireEvent.resize(window));+ return rail;+}++describe("PaneScrollRail", () => {+ it("drags the exact xterm history independently for each terminal ID", () => {+ const mika = fakeTerminal({ owner: "terminal" });+ const nova = fakeTerminal({ owner: "terminal" });+ render(+ <>+ <RailHarness name="Mika" term={mika.term} />+ <RailHarness name="Nova" term={nova.term} />+ </>,+ );+ const rail = giveTrackGeometry("Mika");+ giveTrackGeometry("Nova");+ const thumb = screen.getByTestId("pane-scroll-thumb-Mika");++ fireEvent.pointerDown(thumb, { button: 0, clientY: 180, pointerId: 1 });+ fireEvent.pointerMove(rail, { clientY: 35, pointerId: 1 });+ fireEvent.pointerUp(rail, { clientY: 35, pointerId: 1 });++ expect(mika.scrollToLine).toHaveBeenCalled();+ 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" })+ .getAttribute("aria-controls"),+ ).toBe("terminal-Mika");+ });++ it("moves a mouse-aware full-screen IDE both up and down without a fake position", () => {+ const harness = fakeTerminal({ owner: "mouse-app" });+ render(<RailHarness name="Aria" term={harness.term} />);+ const rail = giveTrackGeometry("Aria");+ const thumb = screen.getByTestId("pane-scroll-thumb-Aria");+ const xtermScreen = screen.getByTestId("xterm-screen-Aria");+ const deltas: number[] = [];+ xtermScreen.addEventListener("wheel", (event) => deltas.push(event.deltaY));+ const restingTop = thumb.style.top;++ fireEvent.pointerDown(thumb, { button: 0, clientY: 100, pointerId: 2 });+ 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(thumb.style.top).toBe(restingTop);+ 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("restores the current owner geometry when a TUI starts during a drag", () => {+ 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");++ fireEvent.pointerDown(thumb, { button: 0, clientY: 100, pointerId: 5 });+ harness.setOwner("mouse-app");+ fireEvent.pointerMove(rail, { clientY: 40, pointerId: 5 });+ fireEvent.pointerUp(rail, { clientY: 40, pointerId: 5 });++ expect(thumb.style.top).toBe("82px");+ });++ 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");++ fireEvent.keyDown(rail, { key: "PageUp" });+ fireEvent.keyDown(rail, { key: "PageDown" });++ expect(harness.input.mock.calls.map((call) => call[0])).toEqual([+ "\x1b[5~",+ "\x1b[6~",+ ]);+ });++ it("forwards a wheel over the rail unchanged to its own terminal", () => {+ const harness = fakeTerminal({ owner: "mouse-app" });+ render(<RailHarness name="Nia" term={harness.term} />);+ const rail = giveTrackGeometry("Nia");+ const xtermScreen = screen.getByTestId("xterm-screen-Nia");+ const received = vi.fn();+ xtermScreen.addEventListener("wheel", received);++ fireEvent.wheel(rail, {+ deltaMode: WheelEvent.DOM_DELTA_PIXEL,+ deltaX: 5,+ deltaY: 120,+ shiftKey: true,+ });++ expect(received).toHaveBeenCalledOnce();+ const forwarded = received.mock.calls[0][0] as WheelEvent;+ expect(forwarded.deltaX).toBe(5);+ expect(forwarded.deltaY).toBe(120);+ expect(forwarded.shiftKey).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsxnew file mode 100644index 0000000000..6d85f7b07b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx@@ -0,0 +1,454 @@+/**+ * One honest scroll rail for one Agentic-IDE terminal pane.+ *+ * Normal terminal history gets a conventional absolute thumb. Full-screen+ * coding TUIs keep their history inside the application, so their thumb is a+ * centred controller: drag it up or down and the application receives its own+ * standard wheel protocol. It springs back on release because claiming an+ * absolute position there would be a guess.+ */+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type KeyboardEvent as ReactKeyboardEvent,+ type PointerEvent as ReactPointerEvent,+ type RefObject,+} from "react";+import type { Terminal } from "@xterm/xterm";+import { cn } from "@/lib/utils";+import { PANE_CHROME, type TerminalAppearance } from "./terminalThemes";+import {+ applicationPageNotches,+ bindTerminalScrollRegion,+ forwardWheelToTerminal,+ lineAtThumbTop,+ readTerminalScrollView,+ scrollApplication,+ scrollThumbGeometry,+ type TerminalScrollView,+} from "./terminalScrollSurface";++const MOUSE_DRAG_STEP_PX = 7;++interface DragSession {+ pointerId: number;+ owner: TerminalScrollView["owner"];+ grabOffset: number;+ lastY: number;+ captured: boolean;+}++interface PaneScrollRailProps {+ name: string;+ controlsId: string;+ regionRef: RefObject<HTMLElement | null>;+ hostRef: RefObject<HTMLElement | null>;+ terminalRef: RefObject<Terminal | null>;+ /** Bumped whenever the ref above receives a new xterm instance. */+ epoch: number;+ appearance: TerminalAppearance;+ onFocus?: () => void;+}++function sameView(+ left: TerminalScrollView | null,+ right: TerminalScrollView,+): boolean {+ return (+ left?.owner === right.owner &&+ left.rows === right.rows &&+ left.maxLine === right.maxLine &&+ left.line === right.line+ );+}++export function PaneScrollRail({+ name,+ controlsId,+ regionRef,+ hostRef,+ terminalRef,+ epoch,+ appearance,+ onFocus,+}: PaneScrollRailProps) {+ const trackRef = useRef<HTMLDivElement | null>(null);+ const thumbRef = 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 sync = useCallback(() => {+ frameRef.current = null;+ const term = terminalRef.current;+ const host = hostRef.current;+ if (!term) {+ setView(null);+ return;+ }+ const next = readTerminalScrollView(term);+ if (host) host.dataset.scrollOwner = next.owner;+ setView((current) => (sameView(current, next) ? current : next));+ }, [hostRef, terminalRef]);++ const scheduleSync = useCallback(() => {+ if (frameRef.current !== null) return;+ frameRef.current = requestAnimationFrame(sync);+ }, [sync]);++ useEffect(() => {+ const term = terminalRef.current;+ if (!term) {+ setView(null);+ return;+ }+ sync();+ const subscriptions = [+ term.onScroll?.(scheduleSync),+ term.onWriteParsed?.(scheduleSync),+ term.buffer?.onBufferChange?.(scheduleSync),+ ];+ return () => {+ if (frameRef.current !== null) cancelAnimationFrame(frameRef.current);+ frameRef.current = null;+ for (const subscription of subscriptions) subscription?.dispose();+ };+ }, [epoch, scheduleSync, sync, terminalRef]);++ useEffect(() => {+ const region = regionRef.current;+ if (!region) return;+ return bindTerminalScrollRegion(region);+ }, [regionRef]);++ useEffect(() => {+ const track = trackRef.current;+ if (!track) return;+ const forward = (event: WheelEvent) => {+ forwardWheelToTerminal(hostRef.current, event);+ };+ // Passive by design: this listener only clones the input. The terminal+ // region contains the browser default after xterm has received the clone.+ track.addEventListener("wheel", forward, { passive: true });+ return () => track.removeEventListener("wheel", forward);+ }, [hostRef, view !== null]);++ useLayoutEffect(() => {+ const track = trackRef.current;+ if (!track) return;+ const measure = () => {+ const height = track.clientHeight || track.getBoundingClientRect().height;+ setTrackPx((current) => (current === height ? current : height));+ };+ measure();+ const observer =+ typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);+ observer?.observe(track);+ window.addEventListener("resize", measure);+ return () => {+ observer?.disconnect();+ window.removeEventListener("resize", measure);+ };+ }, [view !== null]);++ const liveTrack = useCallback(() => {+ const track = trackRef.current;+ if (!track) return { top: 0, height: 0 };+ const box = track.getBoundingClientRect();+ return { top: box.top, height: track.clientHeight || box.height };+ }, []);++ const moveExact = useCallback(+ (current: TerminalScrollView, clientY: number, grabOffset: number) => {+ const term = terminalRef.current;+ if (!term) return;+ const track = liveTrack();+ if (track.height <= 0) return;+ const thumbTop = clientY - track.top - grabOffset;+ term.scrollToLine(lineAtThumbTop(current, thumbTop, track.height));+ scheduleSync();+ },+ [liveTrack, scheduleSync, terminalRef],+ );++ const moveApplication = useCallback(+ (current: TerminalScrollView, clientY: number) => {+ const drag = dragRef.current;+ const term = terminalRef.current;+ if (!drag || !term) return;+ const delta = clientY - drag.lastY;+ const tracking = term.modes?.mouseTrackingMode ?? "none";+ const step =+ tracking === "none"+ ? Math.max(24, liveTrack().height / 5)+ : MOUSE_DRAG_STEP_PX;+ const notches = Math.floor(Math.abs(delta) / Math.max(1, step));+ if (notches > 0) {+ const direction: -1 | 1 = delta < 0 ? -1 : 1;+ scrollApplication(term, hostRef.current, direction, notches);+ drag.lastY += direction * notches * step;+ }++ // During the gesture the grip follows the hand. It returns to the centre+ // on release, which is the visual contract that this is movement rather+ // than a guessed position.+ const track = liveTrack();+ const thumb = thumbRef.current;+ if (thumb && track.height > 0) {+ const geometry = scrollThumbGeometry(current, track.height);+ const top = Math.min(+ track.height - geometry.height,+ Math.max(0, clientY - track.top - geometry.height / 2),+ );+ thumb.style.top = `${top}px`;+ }+ },+ [hostRef, liveTrack, terminalRef],+ );++ const onPointerDown = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ if (event.button !== 0) return;+ const term = terminalRef.current;+ if (!term) return;+ const current = readTerminalScrollView(term);+ const track = liveTrack();+ if (track.height <= 0) return;+ event.preventDefault();+ event.stopPropagation();+ onFocus?.();++ const geometry = scrollThumbGeometry(current, track.height);+ const grabbedThumb = event.target === thumbRef.current;+ const grabOffset = grabbedThumb+ ? event.clientY - track.top - geometry.top+ : geometry.height / 2;+ dragRef.current = {+ pointerId: event.pointerId,+ owner: current.owner,+ grabOffset,+ lastY: event.clientY,+ captured: false,+ };+ setDragging(true);+ try {+ event.currentTarget.setPointerCapture(event.pointerId);+ dragRef.current.captured =+ event.currentTarget.hasPointerCapture?.(event.pointerId) ?? true;+ } catch {+ // Older WebViews and jsdom have no pointer-capture implementation.+ }++ if (current.owner === "terminal") {+ if (!grabbedThumb) moveExact(current, event.clientY, grabOffset);+ return;+ }+ if (!grabbedThumb) {+ const direction: -1 | 1 =+ event.clientY - track.top < track.height / 2 ? -1 : 1;+ scrollApplication(+ term,+ hostRef.current,+ direction,+ applicationPageNotches(current.rows),+ );+ }+ },+ [hostRef, liveTrack, moveExact, onFocus, terminalRef],+ );++ const onPointerMove = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ const drag = dragRef.current;+ const term = terminalRef.current;+ if (!drag || !term || drag.pointerId !== event.pointerId) return;+ event.preventDefault();+ const current = readTerminalScrollView(term);+ if (drag.owner === "terminal" && current.owner === "terminal") {+ moveExact(current, event.clientY, drag.grabOffset);+ } else {+ moveApplication(current, event.clientY);+ }+ },+ [moveApplication, moveExact, terminalRef],+ );++ const finishDrag = useCallback(+ (pointerId?: number) => {+ const drag = dragRef.current;+ if (!drag || (pointerId !== undefined && pointerId !== drag.pointerId)) return;+ dragRef.current = null;+ setDragging(false);+ // 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.+ const term = terminalRef.current;+ const thumb = thumbRef.current;+ const track = liveTrack();+ if (term && thumb && track.height > 0) {+ const current = readTerminalScrollView(term);+ const geometry = scrollThumbGeometry(current, track.height);+ thumb.style.top = `${geometry.top}px`;+ }+ },+ [liveTrack, terminalRef],+ );++ const onPointerUp = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ finishDrag(event.pointerId);+ try {+ event.currentTarget.releasePointerCapture(event.pointerId);+ } catch {+ // No capture was available; the drag still completed on this event.+ }+ },+ [finishDrag],+ );++ const onKeyDown = useCallback(+ (event: ReactKeyboardEvent<HTMLDivElement>) => {+ const term = terminalRef.current;+ if (!term) return;+ 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") {+ scrollApplication(term, hostRef.current, -1, 1);+ } else if (event.key === "ArrowDown") {+ scrollApplication(term, hostRef.current, 1, 1);+ } else if (event.key === "PageUp") {+ scrollApplication(+ term,+ hostRef.current,+ -1,+ applicationPageNotches(current.rows),+ );+ } else if (event.key === "PageDown") {+ scrollApplication(+ term,+ hostRef.current,+ 1,+ applicationPageNotches(current.rows),+ );+ } else {+ handled = false;+ }+ if (!handled) return;+ event.preventDefault();+ event.stopPropagation();+ onFocus?.();+ scheduleSync();+ },+ [hostRef, onFocus, scheduleSync, terminalRef],+ );++ const scrollApplicationPage = useCallback(+ (direction: -1 | 1) => {+ const term = terminalRef.current;+ if (!term) return;+ const current = readTerminalScrollView(term);+ if (current.owner !== "application") return;+ scrollApplication(+ term,+ hostRef.current,+ direction,+ applicationPageNotches(current.rows),+ );+ onFocus?.();+ scheduleSync();+ },+ [hostRef, onFocus, scheduleSync, terminalRef],+ );++ const geometry = useMemo(+ () => (view ? scrollThumbGeometry(view, trackPx) : { top: 0, height: 0 }),+ [trackPx, view],+ );+ if (!view) return null;++ const exact = view.owner === "terminal";+ const valueText = exact+ ? view.maxLine === 0+ ? "No terminal history yet"+ : `Terminal line ${view.line} of ${view.maxLine}`+ : "Application history; drag up or down to scroll";+ const shell = PANE_CHROME[appearance].shell;++ return (+ <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}+ 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-within:opacity-100",+ "focus-visible:ring-1 focus-visible:ring-[#e7c46e]/80 focus-within:ring-1 focus-within:ring-[#e7c46e]/80",+ dragging ? "cursor-grabbing opacity-100" : "cursor-grab",+ )}+ style={{ background: shell }}+ >+ {!exact && (+ <>+ <button+ type="button"+ className="sr-only"+ aria-label={`Scroll older in ${name}`}+ aria-controls={controlsId}+ onClick={() => scrollApplicationPage(-1)}+ />+ <button+ type="button"+ className="sr-only"+ aria-label={`Scroll newer in ${name}`}+ aria-controls={controlsId}+ onClick={() => scrollApplicationPage(1)}+ />+ </>+ )}+ <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 }}+ />+ </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 b03ecce6c4..706e067dd7 100644--- a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts@@ -1,7 +1,13 @@import type { Terminal } from "@xterm/xterm";import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";import {- bindTerminalScrollSurface,+ applicationPageNotches,+ bindTerminalScrollRegion,+ forwardWheelToTerminal,+ lineAtThumbTop,+ readTerminalScrollView,+ scrollApplication,+ scrollThumbGeometry,terminalScrollOwner,} from "./terminalScrollSurface";@@ -27,65 +33,130 @@ async function newTerminal(): Promise<Terminal> {return new XtermTerminal({ allowProposedApi: true });}+function terminalDouble(+ tracking: "none" | "any",+ type: "normal" | "alternate",+): Terminal & { input: 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> };+}+describe("terminalScrollSurface", () => {- it("uses the real xterm parser to distinguish scrollback from a TUI", async () => {+ it("uses the real xterm parser to distinguish scrollback from every TUI mode", 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");+ expect(terminalScrollOwner(term)).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");+ expect(terminalScrollOwner(term)).toBe("terminal");} finally {- dispose();term.dispose();}});- it("lets the terminal receive a wheel but contains the workspace scroll", async () => {- const parent = document.createElement("div");+ 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;+ 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("centres an application controller instead of inventing a position", () => {+ const term = terminalDouble("any", "alternate");+ const view = readTerminalScrollView(term);+ const thumb = scrollThumbGeometry(view, 200);++ expect(view).toEqual({ owner: "application", rows: 24, maxLine: 0, line: 0 });+ expect(thumb.height).toBe(36);+ expect(thumb.top).toBe(82);+ });++ it("relays standard wheel reports through xterm for a mouse-aware coding TUI", () => {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 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));++ expect(scrollApplication(term, host, -1, 3)).toBe(3);+ expect(scrollApplication(term, host, 1, 2)).toBe(2);++ 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("forwards the wheel over a rail unchanged and contains the workspace", () => {+ const workspace = document.createElement("div");+ 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();- xterm.addEventListener("wheel", xtermWheel);- parent.addEventListener("wheel", workspaceWheel);- const dispose = bindTerminalScrollSurface(host, term);+ xtermScreen.addEventListener("wheel", terminalWheel);+ workspace.addEventListener("wheel", workspaceWheel);+ const dispose = bindTerminalScrollRegion(region);try {- const accepted = xterm.dispatchEvent(- new WheelEvent("wheel", {- bubbles: true,- cancelable: true,- deltaY: 120,- }),- );+ const source = new WheelEvent("wheel", {+ bubbles: true,+ cancelable: true,+ deltaMode: WheelEvent.DOM_DELTA_PIXEL,+ deltaX: 4,+ deltaY: 120,+ shiftKey: true,+ });- expect(xtermWheel).toHaveBeenCalledOnce();+ 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();- 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.tsindex c957d504ea..acfbd07ff2 100644--- a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts@@ -1,19 +1,52 @@/**- * Keep terminal scrolling on the side that actually owns it.+ * Provider-neutral terminal scrolling primitives.*- * 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.+ * 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, so the+ * only truthful operation is to relay scroll input to that application.+ *+ * The second case deliberately has no estimated position. Earlier scrollbars+ * counted wheel events and inferred endpoints from one CLI's screen text; the+ * thumb inevitably drifted or snapped in every other coding CLI. The new rail+ * is an exact scrollbar in the first case and an explicitly centred scroll+ * controller in the second.*/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. */+ maxLine: number;+ /** Current exact viewport line. Zero for an application-owned screen. */+ line: number;+}++export interface ScrollThumbGeometry {+ top: number;+ height: number;+}++export const MIN_THUMB_PX = 28;+const MAX_RELAY_NOTCHES = 80;+const PAGE_UP = "\x1b[5~";+const PAGE_DOWN = "\x1b[6~";++function clamp(value: number, low: number, high: number): number {+ return Math.min(high, Math.max(low, value));+}++function finiteWhole(value: unknown): number {+ const number = typeof value === "number" ? value : Number(value);+ 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): 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"@@ -21,40 +54,147 @@ export function terminalScrollOwner(term: Terminal): TerminalScrollOwner {: "terminal";}+/** Read a scroll view without inspecting or interpreting terminal content. */+export function readTerminalScrollView(term: Terminal): TerminalScrollView {+ const owner = terminalScrollOwner(term);+ const rows = Math.max(1, finiteWhole(term.rows));+ if (owner === "application") {+ return { owner, rows, maxLine: 0, line: 0 };+ }+ const active = term.buffer?.active;+ const maxLine = finiteWhole(active?.baseY);+ const line = clamp(finiteWhole(active?.viewportY), 0, maxLine);+ return { owner, rows, maxLine, line };+}+/**- * 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.+ * Geometry for either an exact thumb or the centred application controller.*/-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;+export function scrollThumbGeometry(+ view: TerminalScrollView,+ trackPx: number,+ minThumbPx = MIN_THUMB_PX,+): ScrollThumbGeometry {+ const track = Math.max(0, trackPx);+ if (track === 0) return { top: 0, height: 0 };++ if (view.owner === "application") {+ const height = clamp(track * 0.18, Math.min(minThumbPx, track), Math.min(64, track));+ return { top: (track - height) / 2, height };+ }++ if (view.maxLine === 0) return { top: 0, height: track };+ const contentLines = view.maxLine + view.rows;+ const height = clamp(+ track * (view.rows / Math.max(1, contentLines)),+ Math.min(minThumbPx, track),+ track,+ );+ const travel = Math.max(0, track - height);+ return {+ top: travel * (view.line / view.maxLine),+ height,};+}++/** Map a dragged exact 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;+ const thumb = scrollThumbGeometry(view, trackPx);+ const travel = Math.max(0, trackPx - thumb.height);+ if (travel === 0) return view.maxLine;+ return Math.round(view.maxLine * (clamp(topPx, 0, travel) / travel));+}++/** 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));+}++/**+ * 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;+ }- // 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 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.+ *+ * The rail observes this passively; the containing terminal region owns the+ * separate job of preventing the workspace behind it from scrolling too.+ */+export function forwardWheelToTerminal(+ host: HTMLElement | null,+ event: WheelEvent,+): boolean {+ const screen = host?.querySelector<HTMLElement>(".xterm-screen");+ if (!screen || typeof WheelEvent === "undefined") return false;+ screen.dispatchEvent(+ new WheelEvent("wheel", {+ bubbles: true,+ cancelable: true,+ clientX: event.clientX,+ clientY: event.clientY,+ deltaMode: event.deltaMode,+ deltaX: event.deltaX,+ deltaY: event.deltaY,+ deltaZ: event.deltaZ,+ ctrlKey: event.ctrlKey,+ shiftKey: event.shiftKey,+ altKey: event.altKey,+ metaKey: event.metaKey,+ }),+ );+ return true;+}++/** Keep terminal wheel input from falling through to the workspace scroller. */+export function bindTerminalScrollRegion(region: HTMLElement): () => void {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;- };+ region.addEventListener("wheel", containWheel, { passive: false });+ return () => region.removeEventListener("wheel", containWheel);}