Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agentic-ide): give the pane scroll rail a real position in full-screen TUIs

rubenluetke10-beepf3a4ca92afca
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx
index fce099faf1..f9a1ab4f05 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.test.tsx
@@ -52,6 +52,8 @@ interface TerminalHarness {
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;
}
function fakeTerminal({
@@ -66,10 +68,14 @@ function fakeTerminal({
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",
@@ -103,7 +109,16 @@ function fakeTerminal({
modes.mouseTrackingMode = next === "mouse-app" ? "any" : "none";
changed.fire(active);
};
- return { term, scrollToLine, scrollLines, input, setOwner };
+ return {
+ term,
+ scrollToLine,
+ scrollLines,
+ input,
+ setOwner,
+ repaint: () => {
+ generation += 1;
+ },
+ };
}
function RailHarness({ name, term }: { name: string; term: Terminal }) {
@@ -182,7 +197,7 @@ describe("PaneScrollRail", () => {
).toBe("terminal-Mika");
});
- it("moves a mouse-aware full-screen IDE both up and down without a fake position", () => {
+ it("moves a mouse-aware full-screen IDE both up and down and keeps the measured position", () => {
const harness = fakeTerminal({ owner: "mouse-app" });
render(<RailHarness name="Aria" term={harness.term} />);
const rail = giveTrackGeometry("Aria");
@@ -190,7 +205,9 @@ describe("PaneScrollRail", () => {
const xtermScreen = screen.getByTestId("xterm-screen-Aria");
const deltas: number[] = [];
xtermScreen.addEventListener("wheel", (event) => deltas.push(event.deltaY));
- const restingTop = thumb.style.top;
+ // Nothing has been relayed yet, so the grip rests in the middle and says so.
+ expect(thumb.style.top).toBe("82px");
+ expect(rail.dataset.scrollPosition).toBe("unmeasured");
fireEvent.pointerDown(thumb, { button: 0, clientY: 100, pointerId: 2 });
fireEvent.pointerMove(rail, { clientY: 65, pointerId: 2 });
@@ -199,7 +216,8 @@ describe("PaneScrollRail", () => {
expect(deltas.some((delta) => delta < 0)).toBe(true);
expect(deltas.some((delta) => delta > 0)).toBe(true);
- expect(thumb.style.top).toBe(restingTop);
+ expect(thumb.style.top).not.toBe("82px");
+ expect(rail.dataset.scrollPosition).toBe("measuring");
expect(rail.dataset.scrollMode).toBe("application");
expect(rail.hasAttribute("aria-valuemin")).toBe(false);
expect(rail.hasAttribute("aria-valuemax")).toBe(false);
@@ -236,6 +254,51 @@ describe("PaneScrollRail", () => {
expect(deltas.some((delta) => delta > 0)).toBe(true);
});
+ it("parks the grip at whichever end the application stopped repainting at", () => {
+ vi.useFakeTimers({
+ toFake: [
+ "setTimeout",
+ "clearTimeout",
+ "setInterval",
+ "clearInterval",
+ "requestAnimationFrame",
+ "cancelAnimationFrame",
+ ],
+ });
+ try {
+ const harness = fakeTerminal({ owner: "mouse-app" });
+ render(<RailHarness name="Ida" term={harness.term} />);
+ const rail = giveTrackGeometry("Ida");
+ const thumb = screen.getByTestId("pane-scroll-thumb-Ida");
+ const older = screen.getByRole("button", { name: "Scroll older in Ida" });
+ const newer = screen.getByRole("button", { name: "Scroll newer in Ida" });
+ const settle = () => act(() => vi.advanceTimersByTime(400));
+
+ // A page the application answers with a repaint is real movement.
+ fireEvent.click(older);
+ harness.repaint();
+ settle();
+ expect(Number.parseFloat(thumb.style.top)).toBeLessThan(164);
+ expect(rail.dataset.scrollPosition).toBe("measuring");
+
+ // A page it answers with nothing is the oldest end, which also fixes the
+ // scale: the distance counted so far IS the whole history.
+ fireEvent.click(older);
+ settle();
+ expect(thumb.style.top).toBe("0px");
+ expect(rail.dataset.scrollPosition).toBe("calibrated");
+ expect(rail.title).toBe("Application history, at the oldest end");
+
+ // And the newest end is the newest end, not the middle.
+ fireEvent.click(newer);
+ settle();
+ expect(thumb.style.top).toBe("164px");
+ expect(rail.title).toBe("Application history, at the newest end");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("notices a mouse-tracking flip that arrives without any buffer event", () => {
vi.useFakeTimers({
toFake: [
@@ -271,13 +334,17 @@ describe("PaneScrollRail", () => {
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");
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 });
+ fireEvent.pointerMove(rail, { clientY: 190, pointerId: 5 });
+ fireEvent.pointerUp(rail, { clientY: 190, pointerId: 5 });
- expect(thumb.style.top).toBe("82px");
+ // The release belongs to the application that took over mid-gesture, so the
+ // grip lands on the application scale, dragged to its newest end. The exact
+ // xterm thumb the drag started on would have rested at 142.86px.
+ expect(thumb.style.top).toBe("164px");
});
it("cancels an uncaptured drag when the pointer leaves the rail", () => {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx
index 18fd5dac1a..400feb9646 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollRail.tsx
@@ -2,12 +2,15 @@
* 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 no absolute
- * position exists to draw; instead of a thumb pretending to be one, the rail
- * becomes a visible controller — arrow caps that page the application and a
- * grip that relays drags as the application's own wheel protocol. The grip
- * springs back to centre on release because claiming a position would be a
- * guess.
+ * coding TUIs keep their history inside the application, where no position can
+ * be read — so this rail measures one instead: it counts every unit of scroll
+ * that reaches the terminal, from its own grip and from the user's wheel alike,
+ * and lets the two ends announce themselves by refusing to repaint. See
+ * ./terminalScrollSurface for why that is a measurement and not a guess.
+ *
+ * The grip therefore travels for both owners. It only rests in the middle
+ * before the first scroll of an application-owned screen, which is the one
+ * moment nothing has been measured yet.
*/
import {
useCallback,
@@ -24,26 +27,46 @@ import type { Terminal } from "@xterm/xterm";
import { cn } from "@/lib/utils";
import { PANE_CHROME, type TerminalAppearance } from "./terminalThemes";
import {
+ applicationOffsetAtThumbTop,
applicationPageNotches,
+ ApplicationScrollTracker,
bindTerminalScrollRegion,
forwardWheelToTerminal,
lineAtThumbTop,
readTerminalScrollView,
+ screenMoved,
+ screenSignature,
scrollApplication,
scrollThumbGeometry,
+ terminalScrollOwner,
+ wheelNotches,
+ type ApplicationScrollEstimate,
type TerminalScrollView,
} from "./terminalScrollSurface";
-const MOUSE_DRAG_STEP_PX = 7;
+/**
+ * How long a run of relays may stay open before the screen is compared.
+ *
+ * The application answers over a PTY, so it is never synchronous. Long enough
+ * that a busy agent has repainted, short enough that letting go of the wheel at
+ * the top of the history feels like an immediate stop.
+ */
+const SETTLE_MS = 180;
interface DragSession {
pointerId: number;
owner: TerminalScrollView["owner"];
grabOffset: number;
- lastY: number;
captured: boolean;
}
+interface PendingMeasure {
+ direction: -1 | 1;
+ notches: number;
+ before: string[];
+ timer: number;
+}
+
interface PaneScrollRailProps {
name: string;
controlsId: string;
@@ -82,10 +105,23 @@ export function PaneScrollRail({
const thumbRef = useRef<HTMLDivElement | null>(null);
const dragRef = useRef<DragSession | null>(null);
const frameRef = useRef<number | null>(null);
+ const trackerRef = useRef<ApplicationScrollTracker>(
+ new ApplicationScrollTracker(),
+ );
+ const measureRef = useRef<PendingMeasure | null>(null);
const [view, setView] = useState<TerminalScrollView | null>(null);
+ const [estimate, setEstimate] = useState<ApplicationScrollEstimate | null>(null);
const [trackPx, setTrackPx] = useState(0);
const [dragging, setDragging] = useState(false);
+ const forgetMeasurements = useCallback(() => {
+ const pending = measureRef.current;
+ measureRef.current = null;
+ if (pending) window.clearTimeout(pending.timer);
+ trackerRef.current.reset();
+ setEstimate((current) => (current === null ? current : null));
+ }, []);
+
const sync = useCallback(() => {
frameRef.current = null;
const term = terminalRef.current;
@@ -96,14 +132,110 @@ export function PaneScrollRail({
}
const next = readTerminalScrollView(term);
if (host) host.dataset.scrollOwner = next.owner;
+ // Leaving the alternate screen ends the history this rail was counting;
+ // whatever it measured belongs to a screen that no longer exists.
+ if (next.owner !== "application") forgetMeasurements();
setView((current) => (sameView(current, next) ? current : next));
- }, [hostRef, terminalRef]);
+ }, [forgetMeasurements, hostRef, terminalRef]);
const scheduleSync = useCallback(() => {
if (frameRef.current !== null) return;
frameRef.current = requestAnimationFrame(sync);
}, [sync]);
+ /**
+ * Close the open run of relays.
+ *
+ * `assumeMoved` covers a reversal: the user turned around before the
+ * application had time to answer, so the screen in front of us proves
+ * nothing. Only a run the user actually stopped is allowed to declare an end.
+ */
+ const flushMeasure = useCallback(
+ (assumeMoved: boolean) => {
+ const pending = measureRef.current;
+ measureRef.current = null;
+ if (!pending) return;
+ window.clearTimeout(pending.timer);
+ const term = terminalRef.current;
+ if (!term) return;
+ const moved =
+ assumeMoved || screenMoved(pending.before, screenSignature(term));
+ trackerRef.current.settle(pending.direction, pending.notches, moved);
+ setEstimate(trackerRef.current.estimate());
+ },
+ [terminalRef],
+ );
+
+ /**
+ * Count scroll that has just been handed to an application-owned screen.
+ *
+ * Every route ends up here — this rail's grip, its arrow caps, its keys and
+ * the wheel the user rolls over the terminal itself — because a position
+ * measured from only some of them would be wrong the first time the user
+ * touched the other.
+ */
+ const noteRelay = useCallback(
+ (direction: -1 | 1, notches: number) => {
+ const term = terminalRef.current;
+ if (!term || notches <= 0) return;
+ if (terminalScrollOwner(term) !== "application") return;
+ trackerRef.current.advance(direction, notches);
+ setEstimate(trackerRef.current.estimate());
+
+ const pending = measureRef.current;
+ if (pending && pending.direction === direction) {
+ pending.notches += notches;
+ window.clearTimeout(pending.timer);
+ pending.timer = window.setTimeout(() => flushMeasure(false), SETTLE_MS);
+ return;
+ }
+ if (pending) flushMeasure(true);
+ measureRef.current = {
+ direction,
+ notches,
+ // Taken now, while the report is still travelling down the PTY: the
+ // screen cannot have answered inside this handler.
+ before: screenSignature(term),
+ timer: window.setTimeout(() => flushMeasure(false), SETTLE_MS),
+ };
+ },
+ [flushMeasure, terminalRef],
+ );
+
+ /** Relay to the application and count it, whichever protocol it speaks. */
+ const relayApplication = useCallback(
+ (direction: -1 | 1, notches: number) => {
+ const term = terminalRef.current;
+ if (!term) return;
+ const sent = scrollApplication(term, hostRef.current, direction, notches);
+ // Mouse-mode relays are wheel events on the terminal, so the listener
+ // below already counted them. The page-key fallback emits nothing a
+ // listener could see, so it reports itself here, converted to the same
+ // unit the wheel path counts in.
+ if ((term.modes?.mouseTrackingMode ?? "none") === "none" && sent > 0) {
+ noteRelay(direction, sent * applicationPageNotches(term.rows));
+ }
+ },
+ [hostRef, noteRelay, terminalRef],
+ );
+
+ useEffect(() => {
+ const host = hostRef.current;
+ if (!host) return;
+ const count = (event: WheelEvent) => {
+ const term = terminalRef.current;
+ if (!term) return;
+ const notches = wheelNotches(term, host, event);
+ if (notches > 0) noteRelay(event.deltaY < 0 ? -1 : 1, notches);
+ };
+ // Passive and on the host: every wheel that reaches this terminal — real or
+ // synthesised — is dispatched on the screen inside it and bubbles here.
+ host.addEventListener("wheel", count, { passive: true });
+ return () => host.removeEventListener("wheel", count);
+ }, [hostRef, noteRelay, terminalRef]);
+
+ useEffect(() => forgetMeasurements, [epoch, forgetMeasurements]);
+
useEffect(() => {
const term = terminalRef.current;
if (!term) {
@@ -189,39 +321,40 @@ export function PaneScrollRail({
[liveTrack, scheduleSync, terminalRef],
);
+ /**
+ * Drag an application grip to an absolute offset.
+ *
+ * The gesture states where the user wants to be and this sends the exact
+ * difference from where the count says they are — the same contract as the
+ * exact thumb, over a measured scale instead of a read one.
+ */
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();
+ if (track.height <= 0) return;
+ const measured = trackerRef.current.estimate();
+ const geometry = scrollThumbGeometry(current, track.height, {
+ estimate: measured,
+ });
+ const top = Math.min(
+ Math.max(0, track.height - geometry.height),
+ Math.max(0, clientY - track.top - drag.grabOffset),
+ );
+ const delta =
+ applicationOffsetAtThumbTop(measured, top, track.height) -
+ measured.offset;
+ if (delta !== 0) relayApplication(delta > 0 ? -1 : 1, Math.abs(delta));
+
+ // The grip follows the hand for the length of the gesture; on release the
+ // measured position takes the thumb back, which is where the count and
+ // the hand agree unless the application ran out of history on the way.
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`;
- }
+ if (thumb) thumb.style.top = `${top}px`;
},
- [hostRef, liveTrack, terminalRef],
+ [liveTrack, relayApplication, terminalRef],
);
const onPointerDown = useCallback(
@@ -236,7 +369,9 @@ export function PaneScrollRail({
event.stopPropagation();
onFocus?.();
- const geometry = scrollThumbGeometry(current, track.height);
+ const geometry = scrollThumbGeometry(current, track.height, {
+ estimate: trackerRef.current.estimate(),
+ });
const grabbedThumb = event.target === thumbRef.current;
const grabOffset = grabbedThumb
? event.clientY - track.top - geometry.top
@@ -245,7 +380,6 @@ export function PaneScrollRail({
pointerId: event.pointerId,
owner: current.owner,
grabOffset,
- lastY: event.clientY,
captured: false,
};
setDragging(true);
@@ -261,18 +395,11 @@ export function PaneScrollRail({
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),
- );
- }
+ // A click beside the grip means the same thing it means on any scrollbar
+ // now that there is a scale to aim at: go there.
+ if (!grabbedThumb) moveApplication(current, event.clientY);
},
- [hostRef, liveTrack, moveExact, onFocus, terminalRef],
+ [liveTrack, moveApplication, moveExact, onFocus, terminalRef],
);
const onPointerMove = useCallback(
@@ -304,7 +431,9 @@ export function PaneScrollRail({
const track = liveTrack();
if (term && thumb && track.height > 0) {
const current = readTerminalScrollView(term);
- const geometry = scrollThumbGeometry(current, track.height);
+ const geometry = scrollThumbGeometry(current, track.height, {
+ estimate: trackerRef.current.estimate(),
+ });
thumb.style.top = `${geometry.top}px`;
}
},
@@ -338,23 +467,13 @@ export function PaneScrollRail({
else if (event.key === "End") term.scrollToBottom();
else handled = false;
} else if (event.key === "ArrowUp") {
- scrollApplication(term, hostRef.current, -1, 1);
+ relayApplication(-1, 1);
} else if (event.key === "ArrowDown") {
- scrollApplication(term, hostRef.current, 1, 1);
+ relayApplication(1, 1);
} else if (event.key === "PageUp") {
- scrollApplication(
- term,
- hostRef.current,
- -1,
- applicationPageNotches(current.rows),
- );
+ relayApplication(-1, applicationPageNotches(current.rows));
} else if (event.key === "PageDown") {
- scrollApplication(
- term,
- hostRef.current,
- 1,
- applicationPageNotches(current.rows),
- );
+ relayApplication(1, applicationPageNotches(current.rows));
} else {
handled = false;
}
@@ -364,7 +483,7 @@ export function PaneScrollRail({
onFocus?.();
scheduleSync();
},
- [hostRef, onFocus, scheduleSync, terminalRef],
+ [onFocus, relayApplication, scheduleSync, terminalRef],
);
const scrollApplicationPage = useCallback(
@@ -373,30 +492,35 @@ export function PaneScrollRail({
if (!term) return;
const current = readTerminalScrollView(term);
if (current.owner !== "application") return;
- scrollApplication(
- term,
- hostRef.current,
- direction,
- applicationPageNotches(current.rows),
- );
+ relayApplication(direction, applicationPageNotches(current.rows));
onFocus?.();
scheduleSync();
},
- [hostRef, onFocus, scheduleSync, terminalRef],
+ [onFocus, relayApplication, scheduleSync, terminalRef],
);
const geometry = useMemo(
- () => (view ? scrollThumbGeometry(view, trackPx) : { top: 0, height: 0 }),
- [trackPx, view],
+ () =>
+ view ? scrollThumbGeometry(view, trackPx, { estimate }) : { top: 0, height: 0 },
+ [estimate, trackPx, view],
);
if (!view) return null;
const exact = view.owner === "terminal";
+ const applicationText = !estimate
+ ? "Application history; drag up or down to scroll"
+ : estimate.atBottom
+ ? "Application history, at the newest end"
+ : estimate.atTop
+ ? "Application history, at the oldest end"
+ : estimate.calibrated
+ ? `Application history, ${Math.round((1 - estimate.offset / estimate.span) * 100)}% from the oldest end`
+ : "Application history, position measured so far";
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";
+ : applicationText;
const shell = PANE_CHROME[appearance].shell;
return (
@@ -413,6 +537,15 @@ export function PaneScrollRail({
tabIndex={exact ? 0 : undefined}
data-testid={`pane-scroll-rail-${name}`}
data-scroll-mode={view.owner}
+ data-scroll-position={
+ exact
+ ? "exact"
+ : !estimate
+ ? "unmeasured"
+ : estimate.calibrated
+ ? "calibrated"
+ : "measuring"
+ }
title={valueText}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts
index 706e067dd7..73b3377319 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.test.ts
@@ -1,14 +1,19 @@
import type { Terminal } from "@xterm/xterm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
+ applicationOffsetAtThumbTop,
applicationPageNotches,
+ ApplicationScrollTracker,
bindTerminalScrollRegion,
forwardWheelToTerminal,
lineAtThumbTop,
readTerminalScrollView,
+ screenMoved,
+ screenSignature,
scrollApplication,
scrollThumbGeometry,
terminalScrollOwner,
+ wheelNotches,
} from "./terminalScrollSurface";
function write(term: Terminal, data: string): Promise<void> {
@@ -94,6 +99,110 @@ describe("terminalScrollSurface", () => {
expect(thumb.top).toBe(82);
});
+ it("draws a measured application position at both ends of the rail", () => {
+ const view = readTerminalScrollView(terminalDouble("any", "alternate"));
+ const tracker = new ApplicationScrollTracker();
+
+ // Nothing measured: the grip rests in the middle and says it is not a
+ // position, which is the only honest answer before the first scroll.
+ expect(scrollThumbGeometry(view, 200).top).toBe(82);
+
+ // Ten units of older, answered by a repaint.
+ tracker.advance(-1, 10);
+ tracker.settle(-1, 10, true);
+ const moving = tracker.estimate();
+ expect(moving.calibrated).toBe(false);
+ expect(scrollThumbGeometry(view, 200, { estimate: moving }).top).toBeCloseTo(
+ 164 * (1 - 10 / 40),
+ 5,
+ );
+
+ // Ten more the application does not answer: that is the oldest end, and it
+ // fixes the scale at the ten units that did move.
+ tracker.advance(-1, 10);
+ tracker.settle(-1, 10, false);
+ const top = tracker.estimate();
+ expect(top).toMatchObject({ offset: 10, span: 10, calibrated: true, atTop: true });
+ expect(scrollThumbGeometry(view, 200, { estimate: top }).top).toBe(0);
+
+ // Back down until it stops answering again: the newest end, not the middle.
+ tracker.advance(1, 4);
+ tracker.settle(1, 4, false);
+ const bottom = tracker.estimate();
+ expect(bottom).toMatchObject({ offset: 0, span: 10, atBottom: true });
+ expect(scrollThumbGeometry(view, 200, { estimate: bottom }).top).toBe(164);
+ });
+
+ it("maps a dragged application grip back to the offset it points at", () => {
+ const tracker = new ApplicationScrollTracker();
+ tracker.advance(-1, 60);
+ tracker.settle(-1, 60, true);
+ tracker.advance(-1, 10);
+ tracker.settle(-1, 10, false);
+ const estimate = tracker.estimate();
+
+ expect(estimate.span).toBe(60);
+ expect(applicationOffsetAtThumbTop(estimate, 0, 200)).toBe(60);
+ expect(applicationOffsetAtThumbTop(estimate, 164, 200)).toBe(0);
+ expect(applicationOffsetAtThumbTop(estimate, 82, 200)).toBe(30);
+ // Past either end of the track still means that end.
+ expect(applicationOffsetAtThumbTop(estimate, -50, 200)).toBe(60);
+ expect(applicationOffsetAtThumbTop(estimate, 900, 200)).toBe(0);
+ });
+
+ it("tells a ticking status line apart from a screen that actually moved", () => {
+ const before = Array.from({ length: 24 }, (_, row) => `row ${row}`);
+ const ticked = [...before];
+ ticked[23] = "esc to interrupt · 12s";
+
+ expect(screenMoved(before, ticked)).toBe(false);
+ expect(screenMoved(before, before.map((row) => `${row} scrolled`))).toBe(true);
+ expect(screenMoved([], [])).toBe(false);
+ });
+
+ it("reads the visible rows of the current viewport as the screen signature", () => {
+ const term = {
+ rows: 3,
+ modes: { mouseTrackingMode: "none" },
+ buffer: {
+ active: {
+ type: "normal",
+ baseY: 5,
+ viewportY: 2,
+ getLine: (index: number) => ({
+ translateToString: () => `line ${index}`,
+ }),
+ },
+ },
+ } as unknown as Terminal;
+
+ expect(screenSignature(term)).toEqual(["line 2", "line 3", "line 4"]);
+ });
+
+ it("counts a wheel in the whole rows xterm reports to the application", () => {
+ const host = document.createElement("div");
+ const screen = document.createElement("div");
+ screen.className = "xterm-screen";
+ screen.getBoundingClientRect = () => ({ height: 480 }) as DOMRect;
+ host.append(screen);
+ const term = terminalDouble("any", "alternate");
+
+ const line = new WheelEvent("wheel", {
+ deltaMode: WheelEvent.DOM_DELTA_LINE,
+ deltaY: -3,
+ });
+ const pixels = new WheelEvent("wheel", {
+ deltaMode: WheelEvent.DOM_DELTA_PIXEL,
+ deltaY: 100,
+ });
+ const still = new WheelEvent("wheel", { deltaY: 0 });
+
+ expect(wheelNotches(term, host, line)).toBe(3);
+ // 480px over 24 rows is a 20px cell, so 100px is five rows.
+ expect(wheelNotches(term, host, pixels)).toBe(5);
+ expect(wheelNotches(term, host, still)).toBe(0);
+ });
+
it("relays standard wheel reports through xterm for a mouse-aware coding TUI", () => {
const host = document.createElement("div");
const screen = document.createElement("div");
diff --git a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts
index acfbd07ff2..e914013492 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/terminalScrollSurface.ts
@@ -7,11 +7,19 @@
* * 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.
+ * The second case cannot be read, so it is MEASURED instead. Every unit of
+ * scroll this surface relays is counted, and the two ends announce themselves:
+ * a relay that leaves the visible screen unchanged is an end, because an
+ * application that could still scroll would have repainted. Reaching the older
+ * end therefore calibrates the whole travel, and reaching the newer end pins
+ * the offset back to zero, so both ends are exact and the distance between them
+ * is a bounded estimate rather than a guess.
+ *
+ * The distinction that matters against the earlier failed attempt: nothing here
+ * READS the application's screen. It compares two screens for equality and asks
+ * only "did this move", which no CLI has to opt into and no CLI can break by
+ * rewording its own output. Until the older end has been touched once the rail
+ * still says so (`ApplicationScrollEstimate.calibrated`).
*/
import type { Terminal } from "@xterm/xterm";
@@ -31,11 +39,45 @@ export interface ScrollThumbGeometry {
height: number;
}
+/** A measured application position, in the relay units this surface sends. */
+export interface ApplicationScrollEstimate {
+ /** Distance from the newest end. Zero means pinned to the bottom. */
+ offset: number;
+ /** Travel between the two ends; the working span while uncalibrated. */
+ span: number;
+ /** True once the older end has answered, which fixes `span` exactly. */
+ calibrated: boolean;
+ atTop: boolean;
+ atBottom: boolean;
+}
+
export const MIN_THUMB_PX = 28;
const MAX_RELAY_NOTCHES = 80;
const PAGE_UP = "\x1b[5~";
const PAGE_DOWN = "\x1b[6~";
+/**
+ * How much of the screen a relay must repaint before it counts as movement.
+ *
+ * Deliberately far above the noise floor: coding CLIs redraw a spinner, an
+ * elapsed timer or a status line every second or so, which is one or two rows.
+ * Real movement repaints nearly everything.
+ */
+const MOVED_ROW_RATIO = 0.25;
+
+/**
+ * The travel assumed before the older end has ever answered.
+ *
+ * Something has to be assumed or the thumb could not move at all on the first
+ * gesture. Roughly a handful of screens: large enough that a short scroll does
+ * not slam the thumb to the top, small enough to stay in the right half of the
+ * rail. The first contact with either end replaces it with a measurement.
+ */
+const PROVISIONAL_SPAN = 40;
+
+/** Fallback cell height when the pane has not been measured yet. */
+const FALLBACK_CELL_PX = 18;
+
function clamp(value: number, low: number, high: number): number {
return Math.min(high, Math.max(low, value));
}
@@ -67,20 +109,37 @@ export function readTerminalScrollView(term: Terminal): TerminalScrollView {
return { owner, rows, maxLine, line };
}
+export interface ThumbOptions {
+ /** Measured application position; omit for the uncontrolled centred grip. */
+ estimate?: ApplicationScrollEstimate | null;
+ minThumbPx?: number;
+}
+
+/** Height of the application grip, which no measurement can size truthfully. */
+function applicationGripHeight(track: number, minThumbPx: number): number {
+ return clamp(track * 0.18, Math.min(minThumbPx, track), Math.min(64, track));
+}
+
/**
- * Geometry for either an exact thumb or the centred application controller.
+ * Geometry for either an exact thumb or the measured application grip.
*/
export function scrollThumbGeometry(
view: TerminalScrollView,
trackPx: number,
- minThumbPx = MIN_THUMB_PX,
+ { estimate, minThumbPx = MIN_THUMB_PX }: ThumbOptions = {},
): 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 };
+ const height = applicationGripHeight(track, minThumbPx);
+ const travel = Math.max(0, track - height);
+ if (!estimate || estimate.span <= 0) return { top: travel / 2, height };
+ // Offset counts backwards from the newest end, so a zero offset belongs at
+ // the bottom of the rail — the same place an exact thumb sits when a
+ // terminal is scrolled fully down.
+ const reach = clamp(estimate.offset / estimate.span, 0, 1);
+ return { top: travel * (1 - reach), height };
}
if (view.maxLine === 0) return { top: 0, height: track };
@@ -110,6 +169,153 @@ export function lineAtThumbTop(
return Math.round(view.maxLine * (clamp(topPx, 0, travel) / travel));
}
+/** Map a dragged application grip back to the offset it is pointing at. */
+export function applicationOffsetAtThumbTop(
+ estimate: ApplicationScrollEstimate,
+ topPx: number,
+ trackPx: number,
+ minThumbPx = MIN_THUMB_PX,
+): number {
+ const track = Math.max(0, trackPx);
+ if (track === 0 || estimate.span <= 0) return estimate.offset;
+ const travel = Math.max(0, track - applicationGripHeight(track, minThumbPx));
+ if (travel === 0) return estimate.offset;
+ const reach = 1 - clamp(topPx, 0, travel) / travel;
+ return Math.round(estimate.span * reach);
+}
+
+/**
+ * The visible rows, as plain strings, for comparing one screen against another.
+ *
+ * Never inspected for meaning — only compared — so this stays true for a CLI
+ * this project has never seen.
+ */
+export function screenSignature(term: Terminal): string[] {
+ const active = term.buffer?.active;
+ if (!active?.getLine) return [];
+ const rows = Math.max(1, finiteWhole(term.rows));
+ const top = finiteWhole(active.viewportY);
+ const lines: string[] = [];
+ for (let index = 0; index < rows; index += 1) {
+ lines.push(active.getLine(top + index)?.translateToString(true) ?? "");
+ }
+ return lines;
+}
+
+/** Did the screen really move, or did a status line just tick over? */
+export function screenMoved(
+ before: readonly string[],
+ after: readonly string[],
+ ratio = MOVED_ROW_RATIO,
+): boolean {
+ const rows = Math.max(before.length, after.length);
+ if (rows === 0) return false;
+ let changed = 0;
+ for (let index = 0; index < rows; index += 1) {
+ if ((before[index] ?? "") !== (after[index] ?? "")) changed += 1;
+ }
+ return changed / rows >= ratio;
+}
+
+/**
+ * How many relay units a wheel event is worth.
+ *
+ * xterm converts a wheel into whole rows before reporting it to the
+ * application, so rows are the unit this surface counts in — including for the
+ * wheels the user rolls over the terminal itself, which never pass through
+ * `scrollApplication`.
+ */
+export function wheelNotches(
+ term: Terminal,
+ host: HTMLElement | null,
+ event: WheelEvent,
+): number {
+ const rows = Math.max(1, finiteWhole(term.rows));
+ const magnitude = Math.abs(event.deltaY);
+ if (magnitude === 0) return 0;
+ if (typeof WheelEvent !== "undefined" && event.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
+ return Math.max(1, Math.round(magnitude * rows));
+ }
+ if (typeof WheelEvent !== "undefined" && event.deltaMode === WheelEvent.DOM_DELTA_LINE) {
+ return Math.max(1, Math.round(magnitude));
+ }
+ const screen = host?.querySelector<HTMLElement>(".xterm-screen");
+ const measured = screen ? screen.getBoundingClientRect().height / rows : 0;
+ const cell = measured > 1 ? measured : FALLBACK_CELL_PX;
+ return Math.max(1, Math.round(magnitude / cell));
+}
+
+/**
+ * The measured position of an application-owned screen.
+ *
+ * Pure state: the caller decides when a relay has settled and whether the
+ * screen moved, which keeps every timer out of this module and every terminal
+ * out of the tests.
+ */
+export class ApplicationScrollTracker {
+ private offset = 0;
+ private span = 0;
+ private calibrated = false;
+
+ /** Forget everything — a new process owns a screen this has never seen. */
+ reset(): void {
+ this.offset = 0;
+ this.span = 0;
+ this.calibrated = false;
+ }
+
+ estimate(): ApplicationScrollEstimate {
+ // Uncalibrated, the working span keeps a margin above the distance already
+ // travelled. Without it the thumb would pin itself to the top the moment
+ // the user scrolls further than the assumption, and stay there while the
+ // screen is still moving.
+ const span = this.calibrated
+ ? this.span
+ : Math.max(Math.ceil(this.offset * 1.2), PROVISIONAL_SPAN);
+ return {
+ offset: Math.min(this.offset, span),
+ span,
+ calibrated: this.calibrated,
+ atTop: this.calibrated && this.span > 0 && this.offset >= this.span,
+ atBottom: this.offset === 0,
+ };
+ }
+
+ /**
+ * Book a relay the moment it is sent, before the application has answered.
+ *
+ * The thumb has to follow the hand during a drag, and a drag asks for an
+ * absolute offset — both need the counted position to be current rather than
+ * one settle-window behind. `settle` takes it back if the screen stayed put.
+ */
+ advance(direction: -1 | 1, notches: number): void {
+ const count = Math.max(0, Math.floor(notches));
+ if (count === 0) return;
+ this.offset = Math.max(0, this.offset - direction * count);
+ this.span = Math.max(this.span, this.offset);
+ }
+
+ /**
+ * Close a settled run of relays.
+ *
+ * `moved` false is the load-bearing case: the application was asked to scroll
+ * and did not repaint, so it has nothing left that way. Older means the
+ * distance counted so far IS the whole travel; newer means the offset is
+ * zero. Either way the advance booked for that run was fiction.
+ */
+ settle(direction: -1 | 1, notches: number, moved: boolean): void {
+ if (moved) return;
+ const count = Math.max(0, Math.floor(notches));
+ if (direction < 0) {
+ this.offset = Math.max(0, this.offset - count);
+ this.span = this.offset;
+ this.calibrated = this.offset > 0;
+ } else {
+ this.offset = 0;
+ }
+ }
+}
+
/** 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.