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): draw a pane's real scroll position instead of a centred grip
Ruben Lütke084ebd2d69be
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsxindex f9aca64125..bebf07c2e3 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx@@ -3,8 +3,10 @@ import { act, fireEvent, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Terminal } from "@xterm/xterm";import { PaneScrollbar } from "./PaneScrollbar";+import { SETTLE_MS } from "./paneAppScroll";const REGION = { top: 0, bottom: 300, left: 0, right: 400 };+const TRACK_PX = 300;interface FakeOptions {type?: "normal" | "alternate";@@ -14,6 +16,11 @@ interface FakeOptions {mouseTrackingMode?: string;}+/** A screen of agent output — rows recognisable enough to be tracked. */+function transcript(from: number, count: number): string[] {+ return Array.from({ length: count }, (_, i) => `line ${from + i} of output`);+}+function fakeTerminal({type = "normal",length = 1000,@@ -22,11 +29,21 @@ function fakeTerminal({mouseTrackingMode = "none",}: FakeOptions = {}) {const noop = () => ({ dispose() {} });- return {+ let content = transcript(1, rows);+ const term = {rows,modes: { mouseTrackingMode },buffer: {- active: { type, length, viewportY, baseY: length - rows },+ active: {+ type,+ length,+ viewportY,+ baseY: length - rows,+ getLine: (index: number) =>+ index >= 0 && index < content.length+ ? { translateToString: () => content[index] }+ : undefined,+ },onBufferChange: noop,},onScroll: noop,@@ -35,6 +52,13 @@ function fakeTerminal({scrollToLine: vi.fn(),scrollLines: vi.fn(),} as unknown as Terminal;+ return {+ term,+ /** What the CLI repaints after it handled a relayed wheel notch. */+ show(next: string[]) {+ content = next;+ },+ };}function Harness({ term }: { term: Terminal }) {@@ -66,13 +90,25 @@ function reachForTheBar() {});}+function thumbTop(): number {+ return parseFloat(+ screen.getByTestId("pane-scrollbar-thumb-Dana").style.top || "0",+ );+}++function thumbHeight(): number {+ return parseFloat(+ screen.getByTestId("pane-scrollbar-thumb-Dana").style.height || "0",+ );+}+describe("PaneScrollbar", () => {beforeEach(() => {// jsdom measures nothing, and both the hover zone and the thumb's size are// pure geometry — so the two measurements the component takes are staged.Object.defineProperty(HTMLElement.prototype, "clientHeight", {configurable: true,- value: 300,+ value: TRACK_PX,});HTMLElement.prototype.getBoundingClientRect = () =>({@@ -90,7 +126,7 @@ describe("PaneScrollbar", () => {});it("stays out of the way until the pointer reaches for it", () => {- render(<Harness term={fakeTerminal()} />);+ render(<Harness term={fakeTerminal().term} />);expect(screen.queryByTestId("pane-scrollbar-Dana")).toBeNull();@@ -105,7 +141,7 @@ describe("PaneScrollbar", () => {it("fades out again once the pointer leaves the edge", () => {vi.useFakeTimers();try {- render(<Harness term={fakeTerminal()} />);+ render(<Harness term={fakeTerminal().term} />);reachForTheBar();fireEvent.mouseMove(screen.getByTestId("region"), {clientX: 40,@@ -124,53 +160,106 @@ describe("PaneScrollbar", () => {expect(bar.className).toContain("pointer-events-none");});- it("gives a Claude-Code-style pane a bar the terminal cannot provide", () => {- // Alternate screen + mouse tracking: no scrollback in the terminal at all,- // which is why the native viewport scrollbar was dead in these panes.+ /*+ * The reported bug, at the level a user meets it. Alternate screen + mouse+ * tracking means the terminal holds no scrollback to read a position from —+ * and a pane showing the agent's newest output must still draw its thumb at+ * the BOTTOM. It used to draw a short bright marking halfway up the track,+ * which reads as "you are in the middle" to everyone who has ever used a+ * scrollbar.+ */+ it("puts a Claude-Code-style pane's thumb at the live end", () => {render(<Harness- term={fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- })}+ term={+ fakeTerminal({+ type: "alternate",+ length: 24,+ mouseTrackingMode: "any",+ }).term+ }/>,);reachForTheBar();- const bar = screen.getByTestId("pane-scrollbar-Dana");- expect(bar.dataset.mode).toBe("app");-- // And it must not look like a position while it is at it. A short thumb- // centred in the track was read as "you are halfway up" by a pane sitting- // at the live end of Claude Code's transcript — so the grip spans the- // track, and only its marking sits in the middle.- const thumb = screen.getByTestId("pane-scrollbar-thumb-Dana");- expect(thumb.style.top).toBe("0px");- expect(thumb.style.height).toBe("300px");- expect(screen.getByTestId("pane-scrollbar-grip-Dana")).toBeTruthy();+ expect(screen.getByTestId("pane-scrollbar-Dana").dataset.mode).toBe("app");+ expect(thumbTop() + thumbHeight()).toBe(TRACK_PX);+ // And nothing is drawn on the thumb that could be read as a position of+ // its own.+ expect(screen.queryByTestId("pane-scrollbar-grip-Dana")).toBeNull();});- it("draws no grip marking where the thumb's position IS the answer", () => {- render(<Harness term={fakeTerminal({ length: 1000 })} />);+ /*+ * And it moves, because the position is measured rather than assumed: the+ * screen's content travelling down the pane IS the user going back through+ * the agent's own history.+ */+ it("moves the thumb up as the agent's screen scrolls back", () => {+ vi.useFakeTimers();+ try {+ const pane = fakeTerminal({+ type: "alternate",+ length: 24,+ mouseTrackingMode: "any",+ });+ render(<Harness term={pane.term} />);+ reachForTheBar();+ const atLiveEnd = thumbTop();- reachForTheBar();+ fireEvent.wheel(document.querySelector(".xterm-screen")!, {+ deltaY: -1,+ deltaMode: 1,+ });+ pane.show([...transcript(-3, 4), ...transcript(1, 20)]);+ act(() => vi.advanceTimersByTime(SETTLE_MS));- expect(screen.getByTestId("pane-scrollbar-Dana").dataset.mode).toBe(- "scrollback",- );- expect(screen.queryByTestId("pane-scrollbar-grip-Dana")).toBeNull();+ expect(thumbTop()).toBeLessThan(atLiveEnd);+ expect(screen.getByTestId("pane-scrollbar-Dana").dataset.shown).toBe(+ "true",+ );+ } finally {+ vi.useRealTimers();+ }+ });++ /*+ * A full-screen application with no history at all says so by not moving, and+ * then gets no bar rather than a thumb filling its own track.+ */+ it("takes the bar away from an app that turns out not to scroll", () => {+ vi.useFakeTimers();+ try {+ const pane = fakeTerminal({+ type: "alternate",+ length: 24,+ mouseTrackingMode: "any",+ });+ render(<Harness term={pane.term} />);+ reachForTheBar();++ fireEvent.wheel(document.querySelector(".xterm-screen")!, {+ deltaY: -1,+ deltaMode: 1,+ });+ act(() => vi.advanceTimersByTime(SETTLE_MS));++ expect(screen.queryByTestId("pane-scrollbar-Dana")).toBeNull();+ } finally {+ vi.useRealTimers();+ }});it("hands wheel turns over the bar to the CLI that owns the screen", () => {render(<Harness- term={fakeTerminal({- type: "alternate",- length: 24,- mouseTrackingMode: "any",- })}+ term={+ fakeTerminal({+ type: "alternate",+ length: 24,+ mouseTrackingMode: "any",+ }).term+ }/>,);reachForTheBar();@@ -188,7 +277,7 @@ describe("PaneScrollbar", () => {});it("scrolls the viewport itself when the terminal holds the history", () => {- const term = fakeTerminal({ length: 1000 });+ const { term } = fakeTerminal({ length: 1000 });render(<Harness term={term} />);reachForTheBar();diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsxindex c10c046c0e..1b85c5ffd6 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx@@ -10,11 +10,11 @@* comes within reach of the pane's right edge, and while you are scrolled* back through history — and is otherwise invisible.* 2. **It only worked for half the CLIs.** Why, and what this does about it,- * is in ./paneScroll — in short: Claude Code runs on the alternate screen- * with mouse tracking, so the terminal holds no scrollback to drag through- * and the wheel belongs to the CLI. That pane gets a full-track grip which- * relays wheel notches to Claude Code, rather than a short thumb whose very- * shape would claim a position nobody can know.+ * is in ./paneScroll and ./paneAppScroll — in short: Claude Code runs on the+ * alternate screen with mouse tracking, so the terminal holds no scrollback+ * to read a position from and the wheel belongs to the CLI. That pane's+ * position is measured from how its screen moves instead, and its thumb is+ * drawn from that measurement like any other.** The bar is an overlay, not a layout box: xterm reserves a gutter on the right* for the scrollbar it thinks it has, and the bar sits in that gutter, so@@ -31,15 +31,19 @@ import type { Terminal } from "@xterm/xterm";import { cn } from "@/lib/utils";import type { TerminalAppearance } from "./terminalThemes";import {- GRIP_MARKER_PX,IDLE_STATE,- jogNotches,lineForThumbTop,readScrollState,relayWheelNotch,thumbGeometry,type PaneScrollState,} from "./paneScroll";+import {+ AT_LIVE_END,+ notchesForLines,+ trackAppScroll,+ type AppScrollPosition,+} from "./paneAppScroll";/** How close to the pane's right edge the pointer reveals the bar. */const HOT_ZONE_PX = 28;@@ -50,6 +54,15 @@ const HIDE_DELAY_MS = 260;/** How long the bar stays up after scrolling back through history. */const FLASH_MS = 900;+function sameState(a: PaneScrollState, b: PaneScrollState): boolean {+ return (+ a.mode === b.mode &&+ a.total === b.total &&+ a.rows === b.rows &&+ a.top === b.top+ );+}+interface PaneScrollbarProps {/** Pane call-sign — used for labels and test ids. */name: string;@@ -86,12 +99,18 @@ export function PaneScrollbar({const [nearEdge, setNearEdge] = useState(false);const [flashing, setFlashing] = useState(false);const [dragging, setDragging] = useState(false);- // Live grip offset in `app` mode: the grip follows the drag and springs back.- const [jogPx, setJogPx] = useState(0);+ // Where the thumb is while it is held. The application answers a relayed+ // notch a network round trip later, so a thumb drawn only from the+ // measurement would lag behind the pointer holding it.+ const [dragTopPx, setDragTopPx] = useState<number | null>(null);+ // What ./paneAppScroll has measured of a CLI that holds its own history.+ const [position, setPosition] = useState<AppScrollPosition>(AT_LIVE_END);const shown = nearEdge || flashing || dragging;const stateRef = useRef(state);stateRef.current = state;+ const positionRef = useRef(position);+ positionRef.current = position;// ------------------------------------------------------------------ hoveruseEffect(() => {@@ -131,6 +150,22 @@ export function PaneScrollbar({};}, [regionRef]);+ // -------------------------------------------------- measure an app's scroll+ // Runs whether the bar is visible or not, and costs nothing until a wheel+ // actually turns: a bar that only started measuring when it appeared would+ // come up knowing nothing about a pane the user scrolled a minute ago.+ useEffect(() => {+ const host = hostRef.current;+ if (!host) return;+ return trackAppScroll({ host, getTerminal, onChange: setPosition });+ }, [hostRef, getTerminal, epoch]);++ // A fresh terminal is a fresh transcript — carrying a measured position over+ // a restart would put the thumb somewhere in a history that no longer exists.+ useEffect(() => {+ setPosition(AT_LIVE_END);+ }, [epoch]);+// ------------------------------------------------- flash while scrolled back// Deliberately NOT "flash on any scroll": a pane pinned to the bottom scrolls// on every line an agent prints, and a bar that lit up for each of them would@@ -153,6 +188,27 @@ export function PaneScrollbar({};}, [getTerminal, epoch]);+ // The same flash for an app-mode pane, which produces no xterm scroll event+ // at all: the only sign that somebody is reading history is the measurement+ // moving away from the live end. The timer is held in a ref rather than+ // cleared per effect run, because a measurement that lands back AT the live+ // end must let the flash run out — not cancel it and leave the bar up.+ const flashTimer = useRef<number | undefined>(undefined);+ useEffect(() => {+ if (position.offset === 0) return;+ setFlashing(true);+ if (flashTimer.current !== undefined) window.clearTimeout(flashTimer.current);+ flashTimer.current = window.setTimeout(() => setFlashing(false), FLASH_MS);+ }, [position]);+ useEffect(+ () => () => {+ if (flashTimer.current !== undefined) {+ window.clearTimeout(flashTimer.current);+ }+ },+ [],+ );+// ---------------------------------------------------------------- metrics// Only while the bar is on screen. A hidden bar needs no numbers, and reading// them on every frame of a busy pane is exactly the kind of work the grid@@ -165,16 +221,8 @@ export function PaneScrollbar({let frame: number | undefined;const sync = () => {frame = undefined;- const next = readScrollState(term);- const previous = stateRef.current;- if (- next.mode !== previous.mode ||- next.total !== previous.total ||- next.rows !== previous.rows ||- next.top !== previous.top- ) {- setState(next);- }+ const next = readScrollState(term, positionRef.current);+ if (!sameState(next, stateRef.current)) setState(next);const track = trackRef.current;if (track) {const height = track.clientHeight;@@ -197,6 +245,18 @@ export function PaneScrollbar({};}, [shown, getTerminal, epoch]);+ // A new measurement moves the thumb even on a pane that renders nothing —+ // an app scrolled back through its own history repaints once and then sits+ // still, and the effect above would never hear about it. Only once something+ // HAS been measured, so an untouched pane keeps the bar out of the document+ // entirely rather than mounting it invisible.+ useEffect(() => {+ const term = getTerminal();+ if (!term || position === AT_LIVE_END) return;+ const next = readScrollState(term, position);+ setState((current) => (sameState(current, next) ? current : next));+ }, [position, getTerminal, epoch]);+// The track's height decides the thumb's, and it is only knowable once the// track is in the document. Measured on every commit rather than from the// metrics effect above, because a pane whose agent is idle emits no render@@ -232,24 +292,35 @@ export function PaneScrollbar({const startY = event.clientY;const geometry = thumbGeometry(current, height);const startTop = geometry?.topPx ?? 0;+ const travel = Math.max(0, height - (geometry?.heightPx ?? 0));+ // Where the drag began in the history, and how many notches have been+ // relayed towards its target so far. Counted against the START rather+ // than against the live measurement, so a reading that lands mid-drag+ // cannot make the same notch be sent twice.+ const startLine = current.top;+ const step = positionRef.current.linesPerNotch;let sentNotches = 0;const target = event.currentTarget;target.setPointerCapture(event.pointerId);setDragging(true);+ setDragTopPx(startTop);const onMove = (move: PointerEvent) => {- const delta = move.clientY - startY;+ const topPx = Math.min(+ Math.max(startTop + (move.clientY - startY), 0),+ travel,+ );+ setDragTopPx(topPx);+ const line = lineForThumbTop(topPx, height, current);if (current.mode === "app") {- const wanted = jogNotches(delta);+ const wanted = notchesForLines(line - startLine, step);if (wanted !== sentNotches) {relay(wanted - sentNotches);sentNotches = wanted;}- setJogPx(delta);return;}- const line = lineForThumbTop(startTop + delta, height, current);term.scrollToLine?.(line);};const onUp = () => {@@ -258,7 +329,7 @@ export function PaneScrollbar({target.removeEventListener("pointerup", onUp);target.removeEventListener("pointercancel", onUp);setDragging(false);- setJogPx(0);+ setDragTopPx(null);};target.addEventListener("pointermove", onMove);@@ -269,8 +340,7 @@ export function PaneScrollbar({);// A click on the empty part of the track pages towards it, the way every- // other scrollbar does. In `app` mode there is no "towards it" to aim at, so- // one page of wheel notches goes to the CLI instead.+ // other scrollbar does.const onTrackPointerDown = useCallback((event: React.PointerEvent<HTMLDivElement>) => {const term = getTerminal();@@ -282,15 +352,18 @@ export function PaneScrollbar({const rect = track.getBoundingClientRect();const geometry = thumbGeometry(current, rect.height);if (!geometry) return;- const pages = Math.max(1, current.rows - 1);- // In `app` mode the grip covers the whole track, so this is all but- // unreachable — and where it is, aiming at the track's own middle is the- // only meaningful "up or down": the grip's position holds no answer.- const pivot =- current.mode === "app" ? rect.height / 2 : geometry.topPx;- const down = event.clientY - rect.top > pivot;- if (current.mode === "app") relay(down ? pages : -pages);- else term.scrollLines?.(down ? pages : -pages);+ const page = Math.max(1, current.rows - 1);+ const down = event.clientY - rect.top > geometry.topPx;+ if (current.mode === "app") {+ relay(+ notchesForLines(+ down ? page : -page,+ positionRef.current.linesPerNotch,+ ),+ );+ } else {+ term.scrollLines?.(down ? page : -page);+ }},[getTerminal, relay],);@@ -308,7 +381,7 @@ export function PaneScrollbar({);// ----------------------------------------------------------------- render- const geometry = thumbGeometry(state, trackPx, jogPx);+ const geometry = thumbGeometry(state, trackPx);if (state.mode === "none") return null;const light = appearance === "light";@@ -322,12 +395,12 @@ export function PaneScrollbar({aria-orientation="vertical"aria-label={state.mode === "app"- ? `Scroll ${name} — drag to move through the agent's own history`+ ? `Scroll ${name} — moves through the agent's own history`: `Scroll ${name}`}aria-valuemin={0}- aria-valuemax={state.mode === "app" ? 0 : maxTop}- aria-valuenow={state.mode === "app" ? 0 : Math.min(state.top, maxTop)}+ aria-valuemax={maxTop}+ aria-valuenow={Math.min(state.top, maxTop)}data-testid={`pane-scrollbar-${name}`}data-mode={state.mode}data-shown={shown ? "true" : "false"}@@ -355,31 +428,11 @@ export function PaneScrollbar({dragging ? "cursor-grabbing" : "transition-[top] duration-75",)}style={{- top: geometry.topPx,+ top: dragTopPx ?? geometry.topPx,height: geometry.heightPx,- // A full-track bar is the shape for "no position to report", so it- // is drawn faintly — the bright part is the marking on it, which- // is a handle rather than a claim. See ./paneScroll.- background: `rgb(var(--jarvis-yellow) / ${- geometry.markerPx === undefined ? strength : dragging ? 0.24 : 0.14- })`,+ background: `rgb(var(--jarvis-yellow) / ${strength})`,}}- >- {geometry.markerPx !== undefined && (- <div- data-testid={`pane-scrollbar-grip-${name}`}- className={cn(- "pointer-events-none absolute left-0 w-full rounded-full",- dragging ? undefined : "transition-[top] duration-150",- )}- style={{- top: geometry.markerPx,- height: Math.min(GRIP_MARKER_PX, geometry.heightPx),- background: `rgb(var(--jarvis-yellow) / ${strength})`,- }}- />- )}- </div>+ />)}</div>);diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.test.tsnew file mode 100644index 0000000000..653e7553ea--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.test.ts@@ -0,0 +1,421 @@+import { describe, expect, it, vi } from "vitest";+import type { Terminal } from "@xterm/xterm";+import {+ AT_LIVE_END,+ BURST_MS,+ MAX_LINES_PER_NOTCH,+ SETTLE_MS,+ appScrollExtent,+ appTakesWheel,+ applyShift,+ detectShift,+ notchesForLines,+ trackAppScroll,+ visibleRows,+ type AppScrollPosition,+} from "./paneAppScroll";++/** A screen of an agent transcript — long enough to identify itself again. */+function transcript(from: number, count: number): string[] {+ return Array.from({ length: count }, (_, i) => `line ${from + i} of output`);+}++function fakeTerminal(rows: string[], mouseTrackingMode = "any"): Terminal {+ return {+ rows: rows.length,+ modes: { mouseTrackingMode },+ buffer: {+ active: {+ type: "alternate",+ length: rows.length,+ viewportY: 0,+ baseY: 0,+ getLine: (index: number) =>+ index >= 0 && index < rows.length+ ? { translateToString: () => rows[index] }+ : undefined,+ },+ },+ } as unknown as Terminal;+}++describe("visibleRows", () => {+ it("reads the screen the user is looking at", () => {+ expect(visibleRows(fakeTerminal(transcript(1, 3)))).toEqual([+ "line 1 of output",+ "line 2 of output",+ "line 3 of output",+ ]);+ });++ it("degrades to an empty screen rather than throwing", () => {+ expect(visibleRows(null)).toEqual([]);+ expect(visibleRows({} as Terminal)).toEqual([]);+ // An xterm build without `getLine` must not take a wheel handler down.+ expect(+ visibleRows({+ rows: 4,+ buffer: { active: { viewportY: 0 } },+ } as unknown as Terminal),+ ).toEqual([]);+ });+});++describe("detectShift", () => {+ it("sees a screen that did not move, spinner and all", () => {+ const before = [...transcript(1, 8), "Fermenting… 3m 23s"];+ const after = [...transcript(1, 8), "Fermenting… 3m 41s"];++ expect(detectShift(before, after)).toBe(0);+ });++ /*+ * The measurement the whole feature rests on: scrolling back two lines pushes+ * the content DOWN the screen, and that distance IS how much further from the+ * live end the user now is.+ */+ it("measures how far the content travelled when scrolled back", () => {+ const before = transcript(10, 10);+ const after = [...transcript(8, 2), ...transcript(10, 8)];++ expect(detectShift(before, after)).toBe(2);+ });++ it("measures a move back towards newer output as a negative shift", () => {+ const before = transcript(10, 10);+ const after = [...transcript(13, 7), ...transcript(20, 3)];++ expect(detectShift(before, after)).toBe(-3);+ });++ /*+ * A coding agent pins its prompt box and status line to the bottom of the+ * screen, so those rows match at a shift of zero no matter what the transcript+ * above them did. They must not be able to outvote the part that moved.+ */+ it("is not fooled by rows the application pins to the bottom", () => {+ const box = ["> type here", "bypass permissions on"];+ const before = [...transcript(10, 10), ...box];+ const after = [...transcript(9, 1), ...transcript(10, 9), ...box];++ expect(detectShift(before, after)).toBe(1);+ });++ it("refuses to guess from a screen with nothing on it", () => {+ expect(detectShift(["", "", "a", ""], ["", "", "", "a"])).toBeNull();+ expect(detectShift(transcript(1, 2), transcript(1, 2))).toBeNull();+ });++ it("refuses to guess when the screen was replaced outright", () => {+ expect(detectShift(transcript(1, 10), transcript(500, 10))).toBeNull();+ });+});++describe("applyShift", () => {+ it("moves away from the live end by exactly what was measured", () => {+ const next = applyShift(AT_LIVE_END, 3, -1);++ expect(next.offset).toBe(3);+ // One notch moved three lines, so that is what a notch is worth here.+ expect(next.linesPerNotch).toBe(3);+ // Three lines of history are now proven to exist — and possibly more.+ expect(next).toMatchObject({ span: 3, spanKnown: false });+ });++ it("pins the top down when a scroll back moves nothing", () => {+ const scrolled: AppScrollPosition = {+ offset: 42,+ span: 42,+ spanKnown: false,+ linesPerNotch: 3,+ };++ expect(applyShift(scrolled, 0, -1)).toMatchObject({+ offset: 42,+ span: 42,+ spanKnown: true,+ });+ });++ /*+ * The reading the reported bug turned on: a pane at the newest output must be+ * drawn at the newest output. A scroll down that moves nothing says so exactly,+ * whatever the accumulated arithmetic had drifted to.+ */+ it("snaps back to zero when a scroll down moves nothing", () => {+ const drifted: AppScrollPosition = {+ offset: 7,+ span: 200,+ spanKnown: true,+ linesPerNotch: 3,+ };++ expect(applyShift(drifted, 0, 1)).toMatchObject({+ offset: 0,+ span: 200,+ spanKnown: true,+ });+ });++ it("learns nothing about a notch from a move that hit the end", () => {+ const near: AppScrollPosition = {+ offset: 0,+ span: 0,+ spanKnown: false,+ linesPerNotch: 3,+ };++ // Four notches asked for, one line delivered: the history ran out mid-burst,+ // so this says nothing about how far one notch goes.+ expect(applyShift(near, 1, -4).linesPerNotch).toBe(3);+ });++ it("keeps a notch's measured size within reason", () => {+ expect(applyShift(AT_LIVE_END, 900, -1).linesPerNotch).toBe(+ MAX_LINES_PER_NOTCH,+ );+ });++ /*+ * "Nothing moved" and "we could not tell" look the same in a sum and mean+ * opposite things: one is the end of the history, the other is a measurement+ * that failed. Only the first may ever pin an end down.+ */+ it("falls back to what was sent without claiming an end", () => {+ const known: AppScrollPosition = {+ offset: 0,+ span: 90,+ spanKnown: true,+ linesPerNotch: 3,+ };++ expect(applyShift(known, null, -4)).toMatchObject({+ offset: 12,+ spanKnown: true,+ linesPerNotch: 3,+ });+ expect(applyShift(known, null, 4)).toMatchObject({ offset: 0 });+ });++ it("gives up a top it turns out to be able to scroll past", () => {+ const stale: AppScrollPosition = {+ offset: 90,+ span: 90,+ spanKnown: true,+ linesPerNotch: 3,+ };++ // The transcript grew while the user sat in it, so the old top was not one.+ expect(applyShift(stale, 6, -2)).toMatchObject({+ offset: 96,+ span: 96,+ spanKnown: false,+ });+ });++ it("never lets a position run below the live end", () => {+ expect(applyShift(AT_LIVE_END, -40, 4).offset).toBe(0);+ });+});++describe("appScrollExtent", () => {+ /*+ * Before anybody has scrolled, the size of the history is unknown but the+ * position is not: the application is showing its newest output. So the thumb+ * rests at the BOTTOM — which is the reading the reported bug was missing —+ * and is sized by an assumed screenful above it.+ */+ it("puts an unscrolled pane at the bottom of its track", () => {+ expect(appScrollExtent(AT_LIVE_END, 30)).toEqual({ total: 60, top: 30 });+ });++ it("draws the real proportions once the top has been found", () => {+ const known: AppScrollPosition = {+ offset: 0,+ span: 400,+ spanKnown: true,+ linesPerNotch: 3,+ };++ expect(appScrollExtent(known, 24)).toEqual({ total: 424, top: 400 });+ expect(appScrollExtent({ ...known, offset: 400 }, 24)).toEqual({+ total: 424,+ top: 0,+ });+ expect(appScrollExtent({ ...known, offset: 200 }, 24)).toEqual({+ total: 424,+ top: 200,+ });+ });++ it("reports no history at all for an app measured as having none", () => {+ const flat: AppScrollPosition = {+ offset: 0,+ span: 0,+ spanKnown: true,+ linesPerNotch: 1,+ };++ // total === rows, which is how ./paneScroll knows to take the bar away.+ expect(appScrollExtent(flat, 24)).toEqual({ total: 24, top: 0 });+ });+});++describe("notchesForLines", () => {+ it("converts a distance in lines into wheel notches", () => {+ expect(notchesForLines(9, 3)).toBe(3);+ expect(notchesForLines(-9, 3)).toBe(-3);+ expect(notchesForLines(4, 3)).toBe(1);+ // A nonsense step must not produce an infinite relay.+ expect(notchesForLines(6, 0)).toBe(6);+ });+});++describe("appTakesWheel", () => {+ it("is the one test that decides which world a pane is in", () => {+ expect(appTakesWheel(fakeTerminal([], "any"))).toBe(true);+ expect(appTakesWheel(fakeTerminal([], "none"))).toBe(false);+ expect(appTakesWheel(null)).toBe(false);+ });+});++describe("trackAppScroll", () => {+ function wheel(host: HTMLElement, deltaY: number, deltaMode = 1) {+ host+ .querySelector(".xterm-screen")!+ .dispatchEvent(+ new WheelEvent("wheel", { bubbles: true, deltaY, deltaMode }),+ );+ }++ function stage(rows: string[], mouseTrackingMode = "any") {+ const host = document.createElement("div");+ const screen = document.createElement("div");+ screen.className = "xterm-screen";+ host.appendChild(screen);+ document.body.appendChild(host);++ let term = fakeTerminal(rows, mouseTrackingMode);+ let position = AT_LIVE_END;+ const stop = trackAppScroll({+ host,+ getTerminal: () => term,+ onChange: (update) => {+ position = update(position);+ },+ });+ return {+ host,+ stop,+ show: (next: string[]) => {+ term = fakeTerminal(next, mouseTrackingMode);+ },+ get position() {+ return position;+ },+ };+ }++ it("measures the position from a wheel turn the CLI answered", () => {+ vi.useFakeTimers();+ try {+ const pane = stage(transcript(10, 10));++ wheel(pane.host, -1);+ pane.show([...transcript(7, 3), ...transcript(10, 7)]);+ vi.advanceTimersByTime(SETTLE_MS);++ expect(pane.position).toMatchObject({ offset: 3, linesPerNotch: 3 });+ pane.stop();+ } finally {+ vi.useRealTimers();+ }+ });++ it("reads the end of the history off a turn that changed nothing", () => {+ vi.useFakeTimers();+ try {+ const pane = stage(transcript(10, 10));++ wheel(pane.host, -1);+ vi.advanceTimersByTime(SETTLE_MS);++ expect(pane.position).toMatchObject({ span: 0, spanKnown: true });+ pane.stop();+ } finally {+ vi.useRealTimers();+ }+ });++ /*+ * A held-down wheel would otherwise move the screen further than one screenful+ * between snapshots, leaving nothing for the two to be lined up by.+ */+ it("measures a long burst before it runs off the end of the screen", () => {+ vi.useFakeTimers();+ try {+ const pane = stage(transcript(10, 10));+ wheel(pane.host, -1);+ pane.show([...transcript(8, 2), ...transcript(10, 8)]);++ // The wheel never stops long enough for the quiet timer to fire, so only+ // the burst deadline can produce a reading.+ for (let i = 0; i < 5; i += 1) {+ vi.advanceTimersByTime(SETTLE_MS - 40);+ wheel(pane.host, -1);+ }++ expect(pane.position.offset).toBe(2);+ pane.stop();+ } finally {+ vi.useRealTimers();+ }+ });++ it("only learns a notch's size from notches it sent itself", () => {+ vi.useFakeTimers();+ try {+ const pane = stage(transcript(10, 10));++ // A mouse wheel in pixel mode: the driver's idea of a notch, not ours.+ wheel(pane.host, -120, 0);+ pane.show([...transcript(4, 6), ...transcript(10, 4)]);+ vi.advanceTimersByTime(SETTLE_MS);++ expect(pane.position.offset).toBe(6);+ expect(pane.position.linesPerNotch).toBe(AT_LIVE_END.linesPerNotch);+ pane.stop();+ } finally {+ vi.useRealTimers();+ }+ });++ it("leaves a pane whose terminal owns its scrollback alone", () => {+ vi.useFakeTimers();+ try {+ const pane = stage(transcript(10, 10), "none");++ wheel(pane.host, -1);+ vi.advanceTimersByTime(BURST_MS);++ expect(pane.position).toBe(AT_LIVE_END);+ pane.stop();+ } finally {+ vi.useRealTimers();+ }+ });++ it("leaves no timer running behind a pane that goes away", () => {+ vi.useFakeTimers();+ try {+ const pane = stage(transcript(10, 10));+ wheel(pane.host, -1);++ pane.stop();++ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.ts b/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.tsnew file mode 100644index 0000000000..a8d9131dd9--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/paneAppScroll.ts@@ -0,0 +1,341 @@+/**+ * Where a full-screen CLI sits in ITS OWN history — measured, not guessed.+ *+ * ## The problem this exists to solve+ *+ * A CLI that takes the mouse (Claude Code and every other Ink-style agent UI)+ * keeps its transcript to itself: the terminal's buffer holds one screen, the+ * wheel is forwarded to the application, and nothing xterm can be asked reveals+ * how far back the user has scrolled. See ./paneScroll for the full measurement.+ *+ * The first answer to that was to draw no position at all — a bar spanning the+ * whole track with a small marking parked in its middle, meaning "there is no+ * position here". It did not read that way. The full-track bar is drawn faintly+ * by design, so the marking is the only part anyone actually sees, and a short+ * bright shape halfway up a track says exactly one thing in the only grammar+ * scrollbars have: *you are in the middle*. Reported 2026-07-27 by a pane+ * sitting at the live end of its transcript. Refusing to answer with the shape+ * an answer is given in is not refusing to answer.+ *+ * ## So the position is measured, from the one thing that is observable+ *+ * The application will not tell us where it is, but it will SHOW us: scroll it+ * and the lines on screen move. That movement is the measurement.+ *+ * Around every burst of wheel events the screen is snapshotted before and after,+ * and {@link detectShift} recovers how far the content travelled by finding the+ * row offset that lines the two snapshots up. From there:+ *+ * * content moved **down** → the user went back into history; the distance from+ * the live end grows by exactly that many lines,+ * * content did **not move** although a scroll was asked for → an end of the+ * history was reached, which is how both the top (the extent becomes known)+ * and the bottom (the distance is truly zero) are pinned down exactly,+ * * how far one wheel notch moves the application is itself learned from the+ * same measurement, so dragging the thumb can aim.+ *+ * Nothing here is assumed about which CLI is running, what it draws, or what its+ * keys do. It is the same technique a screen reader uses to follow a TUI, and it+ * works on any application that scrolls its own output.+ *+ * ## What it is honest about+ *+ * Before anyone has scrolled, the extent of the history is genuinely unknown —+ * so it is treated as "at least one more screen above", which draws a half-track+ * thumb resting at the BOTTOM. That is a claim about size, made openly and+ * corrected by the first real measurement; it is not a claim about position, and+ * the position it does show — you are at the newest output — is the true one.+ * A full-screen application with no history at all (a dashboard, a pager on a+ * short file) reveals itself on the first scroll attempt that moves nothing, and+ * its pane loses the bar entirely.+ */+import type { Terminal } from "@xterm/xterm";++/**+ * True when the running application receives wheel events itself.+ *+ * The one test that decides which of the two worlds a pane is in — see+ * ./paneScroll, which re-exports this. It lives here because everything on this+ * side of the line depends on it, and a shared module may not import back into+ * the one that imports it.+ */+export function appTakesWheel(term: Terminal | null): boolean {+ const tracking = term?.modes?.mouseTrackingMode;+ return Boolean(tracking) && tracking !== "none";+}++export interface AppScrollPosition {+ /** Lines between the top of the screen and the live end. 0 = newest output. */+ offset: number;+ /** How much history is known to exist above the live end, in lines. */+ span: number;+ /**+ * True once a scroll towards older output moved nothing: `span` is then the+ * real top of the transcript rather than a lower bound.+ */+ spanKnown: boolean;+ /** Lines the application moves per wheel notch, as measured. */+ linesPerNotch: number;+}++/** What a pane is before anybody has scrolled it: showing the newest output. */+export const AT_LIVE_END: AppScrollPosition = {+ offset: 0,+ span: 0,+ spanKnown: false,+ linesPerNotch: 1,+};++/**+ * Fewest recognisable rows two screens need before they may be compared.+ *+ * A near-empty screen matches itself at every offset, so a shift measured off+ * one would be noise presented as a position.+ */+export const MIN_COMPARABLE_ROWS = 4;++/** Longest jump one notch may be credited with — a guard against a bad match. */+export const MAX_LINES_PER_NOTCH = 12;++function clamp(value: number, low: number, high: number): number {+ return value < low ? low : value > high ? high : value;+}++/** Rows carrying enough text to identify themselves again after a scroll. */+function identifiable(text: string): boolean {+ return text.trim().length > 2;+}++/**+ * The lines currently on screen, top row first.+ *+ * Defensive like the rest of this area: an xterm build without `getLine`, or a+ * pane whose terminal is not up yet, yields an empty screen rather than throwing+ * inside an event handler.+ */+export function visibleRows(term: Terminal | null): string[] {+ const buffer = term?.buffer?.active;+ const rows = term?.rows ?? 0;+ if (!term || !buffer || rows < 1 || typeof buffer.getLine !== "function") {+ return [];+ }+ const base = buffer.viewportY ?? 0;+ const lines: string[] = [];+ for (let i = 0; i < rows; i += 1) {+ const line = buffer.getLine(base + i);+ lines.push(line ? line.translateToString(true).trimEnd() : "");+ }+ return lines;+}++/**+ * How far the screen's content travelled between two snapshots.+ *+ * Positive means the content moved DOWN the screen — older lines appeared above+ * it — which is what scrolling back through a history looks like. Null means the+ * two screens have too little in common to compare, which happens when a pane+ * repaints completely or scrolls further than one screenful at a time.+ *+ * The offset that lines up the most rows wins, with a tie going to the smallest+ * movement, so a screen where only a spinner changed reads as "did not move"+ * rather than as an arbitrary shift. Rows an application pins to the bottom —+ * the prompt box and status line of a coding agent — match at zero and nowhere+ * else, so they raise every candidate's floor equally and never decide the+ * outcome as long as the scrolling region is the larger part of the screen.+ */+export function detectShift(+ before: string[],+ after: string[],+): number | null {+ const anchors = before.filter(identifiable).length;+ if (before.length < MIN_COMPARABLE_ROWS || anchors < MIN_COMPARABLE_ROWS) {+ return null;+ }++ const reach = Math.max(before.length, after.length) - 1;+ let best = 0;+ let bestScore = -1;+ for (let shift = -reach; shift <= reach; shift += 1) {+ let score = 0;+ for (let i = 0; i < before.length; i += 1) {+ const j = i + shift;+ if (j < 0 || j >= after.length) continue;+ if (identifiable(before[i]) && before[i] === after[j]) score += 1;+ }+ if (+ score > bestScore ||+ (score === bestScore && Math.abs(shift) < Math.abs(best))+ ) {+ best = shift;+ bestScore = score;+ }+ }+ return bestScore >= MIN_COMPARABLE_ROWS ? best : null;+}++/**+ * Fold one burst of scrolling into a position.+ *+ * `intent` is the wheel direction that was asked for, in `deltaY` signs —+ * positive towards newer output. `observed` is what {@link detectShift} saw, or+ * null when the screens could not be compared; an unmeasurable burst falls back+ * to what was SENT, and deliberately claims no end of the history, because+ * "nothing moved" and "we could not tell" must never collapse into each other.+ */+export function applyShift(+ position: AppScrollPosition,+ observed: number | null,+ intent: number,+): AppScrollPosition {+ const towardsOlder = intent < 0;+ const moved = observed ?? -intent * position.linesPerNotch;++ let offset = Math.max(0, position.offset + moved);+ let span = position.span;+ let spanKnown = position.spanKnown;+ let linesPerNotch = position.linesPerNotch;++ if (observed !== null && intent !== 0) {+ if (observed === 0) {+ // A scroll that moved nothing is an end of the history — the only exact+ // fix this measurement ever gets, and worth more than any accumulated sum.+ if (towardsOlder) {+ span = offset;+ spanKnown = true;+ } else {+ offset = 0;+ }+ } else if (Math.abs(observed) >= Math.abs(intent)) {+ // Only an unclamped move says anything about a notch's size: one that ran+ // into the end of the history moved less than the application would have.+ linesPerNotch = clamp(+ Math.round(Math.abs(observed) / Math.abs(intent)),+ 1,+ MAX_LINES_PER_NOTCH,+ );+ }+ }++ // Scrolling past a top we thought we knew means we never knew it — the+ // transcript grew, or the earlier reading was wrong.+ if (offset > span) {+ span = offset;+ if (observed === null || observed !== 0 || !towardsOlder) spanKnown = false;+ }++ return { offset, span, spanKnown, linesPerNotch };+}++/**+ * The buffer arithmetic a scrollbar needs for a measured position.+ *+ * Returns the numbers a plain scrollback pane would report — total lines and+ * the line at the top of the viewport — so both kinds of pane draw their thumb+ * through exactly the same geometry.+ */+export function appScrollExtent(+ position: AppScrollPosition,+ rows: number,+): { total: number; top: number } {+ const reached = Math.max(position.span, position.offset);+ // While the top is unfound, one more screenful is assumed to exist above:+ // enough for the thumb to have somewhere to travel, never enough to pretend+ // the user is anywhere but where they are.+ const span = position.spanKnown ? reached : reached + rows;+ return { total: span + rows, top: span - Math.min(position.offset, span) };+}++/** Wheel notches that move an application `lines` towards newer output. */+export function notchesForLines(+ lines: number,+ linesPerNotch: number,+): number {+ return Math.round(lines / Math.max(1, linesPerNotch));+}++/** Quiet time after the last wheel event before the screen is re-measured. */+export const SETTLE_MS = 120;++/**+ * Longest a burst may run before it is measured anyway.+ *+ * A held-down scroll would otherwise move the screen further than one screenful+ * between snapshots, leaving the two with nothing in common and the measurement+ * with nothing to work from.+ */+export const BURST_MS = 260;++export interface AppScrollTrackerOptions {+ /** The xterm host every wheel event for this pane passes through. */+ host: HTMLElement;+ getTerminal: () => Terminal | null;+ onChange: (next: (previous: AppScrollPosition) => AppScrollPosition) => void;+}++/**+ * Watch a pane's wheel traffic and keep its measured position up to date.+ *+ * Returns the teardown. Attached in the capture phase so it sees the wheel+ * whether the user turned it over the terminal or the scrollbar relayed it, and+ * passively so it can never interfere with the event xterm is about to encode+ * for the application.+ */+export function trackAppScroll({+ host,+ getTerminal,+ onChange,+}: AppScrollTrackerOptions): () => void {+ let before: string[] | null = null;+ let intent = 0;+ let notchesOnly = true;+ let quiet: number | undefined;+ let deadline: number | undefined;++ const settle = () => {+ if (quiet !== undefined) window.clearTimeout(quiet);+ if (deadline !== undefined) window.clearTimeout(deadline);+ quiet = undefined;+ deadline = undefined;++ const snapshot = before;+ const asked = intent;+ const synthetic = notchesOnly;+ before = null;+ intent = 0;+ notchesOnly = true;+ if (!snapshot || asked === 0) return;++ const observed = detectShift(snapshot, visibleRows(getTerminal()));+ onChange((previous) => {+ const next = applyShift(previous, observed, asked);+ // A notch's size may only be learned from notches we sent ourselves: a+ // mouse wheel reports whatever its driver feels like, so counting its+ // events as notches would teach the drag the wrong step.+ return synthetic ? next : { ...next, linesPerNotch: previous.linesPerNotch };+ });+ };++ const onWheel = (event: WheelEvent) => {+ const term = getTerminal();+ // A pane whose terminal owns its scrollback needs none of this: its+ // viewport already reports the truth.+ if (!appTakesWheel(term) || event.deltaY === 0) return;+ if (!before) before = visibleRows(term);+ intent += event.deltaY > 0 ? 1 : -1;+ // Our own relays are emitted as exactly one line in line mode — see+ // `relayWheelNotch` in ./paneScroll.+ if (event.deltaMode !== 1 || Math.abs(event.deltaY) !== 1) {+ notchesOnly = false;+ }+ if (quiet !== undefined) window.clearTimeout(quiet);+ quiet = window.setTimeout(settle, SETTLE_MS);+ if (deadline === undefined) deadline = window.setTimeout(settle, BURST_MS);+ };++ host.addEventListener("wheel", onWheel, { capture: true, passive: true });+ return () => {+ if (quiet !== undefined) window.clearTimeout(quiet);+ if (deadline !== undefined) window.clearTimeout(deadline);+ host.removeEventListener("wheel", onWheel, { capture: true });+ };+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.ts b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.tsindex 3d5d807c0d..8d6775a6f5 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.test.ts@@ -1,16 +1,13 @@import { describe, expect, it } from "vitest";import type { Terminal } from "@xterm/xterm";import {- GRIP_MARKER_PX,- GRIP_TRAVEL_PX,- JOG_STEP_PX,MIN_THUMB_PX,- jogNotches,lineForThumbTop,readScrollState,relayWheelNotch,thumbGeometry,} from "./paneScroll";+import { AT_LIVE_END, type AppScrollPosition } from "./paneAppScroll";interface FakeOptions {type?: "normal" | "alternate";@@ -34,6 +31,19 @@ function fakeTerminal({} as unknown as Terminal;}+/** An app-mode pane whose history has been measured end to end. */+function measured(+ overrides: Partial<AppScrollPosition> = {},+): AppScrollPosition {+ return {+ offset: 0,+ span: 400,+ spanKnown: true,+ linesPerNotch: 3,+ ...overrides,+ };+}+describe("readScrollState", () => {it("reports scrollback for a terminal that holds its own history", () => {const state = readScrollState(fakeTerminal({ length: 100, rows: 24 }));@@ -56,10 +66,10 @@ describe("readScrollState", () => {it("reports app mode for a full-screen CLI that took the mouse", () => {const state = readScrollState(fakeTerminal({ type: "alternate", mouseTrackingMode: "any", rows: 30 }),+ measured({ offset: 120 }),);- expect(state.mode).toBe("app");- expect(state.rows).toBe(30);+ expect(state).toEqual({ mode: "app", total: 430, rows: 30, top: 280 });});/*@@ -80,24 +90,49 @@ describe("readScrollState", () => {rows: 24,viewportY: 4,}),+ measured({ offset: 200 }),);expect(state.mode).toBe("app");- // No leftover position from the frozen viewport: the grip encodes none.- expect(state.top).toBe(0);- expect(thumbGeometry(state, 400)).toEqual({- topPx: 0,- heightPx: 400,- markerPx: 189,- });+ // Not one number from the frozen viewport: the position is the measured one.+ expect(state).toMatchObject({ total: 424, rows: 24, top: 200 });+ });++ /*+ * The reported bug, in one assertion. A pane showing an agent's newest output+ * must draw its thumb AT THE BOTTOM — even before anyone has scrolled it, when+ * the size of the history is still unknown.+ */+ it("puts an unscrolled app-mode pane at the live end", () => {+ const state = readScrollState(+ fakeTerminal({ type: "alternate", mouseTrackingMode: "any", rows: 30 }),+ AT_LIVE_END,+ );+ const geometry = thumbGeometry(state, 300)!;++ expect(geometry.topPx + geometry.heightPx).toBe(300);+ });++ /*+ * A full-screen application with no history of its own — a dashboard, a pager+ * on a short file — proves it the first time a scroll moves nothing. From then+ * on it gets no bar rather than a thumb filling its own track.+ */+ it("takes the bar away from an app measured as having no history", () => {+ const state = readScrollState(+ fakeTerminal({ type: "alternate", mouseTrackingMode: "any" }),+ measured({ span: 0 }),+ );++ expect(state.mode).toBe("none");});it("stays away from a full-screen app that did not take the mouse", () => {// Relaying a wheel notch to one of those would arrive in its input as the// raw escape sequence, so no bar is the correct answer.- expect(- readScrollState(fakeTerminal({ type: "alternate" })).mode,- ).toBe("none");+ expect(readScrollState(fakeTerminal({ type: "alternate" })).mode).toBe(+ "none",+ );});it("survives a terminal that is not built yet", () => {@@ -123,58 +158,36 @@ describe("thumbGeometry", () => {const state = readScrollState(fakeTerminal({ length: 124, rows: 24, viewportY: 100 }),);- const geometry = thumbGeometry(state, 400);+ const geometry = thumbGeometry(state, 400)!;- expect(geometry).not.toBeNull();- expect(geometry!.topPx + geometry!.heightPx).toBe(400);+ expect(geometry.topPx + geometry.heightPx).toBe(400);});/*- * The bug this shape exists to prevent: a fixed 44px grip centred in the- * track was read — by the only grammar scrollbars have — as "you are halfway- * up", while the pane sat at the live end of Claude Code's transcript. A bar- * that spans the track cannot be read that way in either direction.+ * The bug this shape exists to prevent, from the other side. A short bright+ * shape halfway up a track says "you are in the middle" in the only grammar+ * scrollbars have — so an app-mode pane draws its thumb from a real measured+ * position, through this same geometry, rather than parking a marking in the+ * middle and hoping to be read as saying nothing.*/- it("spans the whole track in app mode — no length of it means a position", () => {- const state = readScrollState(- fakeTerminal({ type: "alternate", mouseTrackingMode: "any" }),- );-- expect(thumbGeometry(state, 300)).toEqual({- topPx: 0,- heightPx: 300,- markerPx: 139,+ it("draws an app-mode pane through the very same geometry", () => {+ const term = fakeTerminal({+ type: "alternate",+ mouseTrackingMode: "any",+ rows: 24,});- });- it("lets the app-mode marking follow a drag, within its travel", () => {- const state = readScrollState(- fakeTerminal({ type: "alternate", mouseTrackingMode: "any" }),- );-- const dragged = thumbGeometry(state, 300, 40);- // The bar itself never moves — only its marking, as drag feedback.- expect(dragged?.topPx).toBe(0);- expect(dragged?.heightPx).toBe(300);- expect(dragged?.markerPx).toBe(179);- // A long drag keeps relaying wheel notches, but the marking stops moving:- // running it to the track's end would restore the very "you are here" read- // the full-track bar is here to refuse.- expect(thumbGeometry(state, 300, 9000)?.markerPx).toBe(- 139 + GRIP_TRAVEL_PX,+ expect(thumbGeometry(readScrollState(term, measured()), 400)).toEqual(+ thumbGeometry(+ readScrollState(fakeTerminal({ length: 424, rows: 24, viewportY: 400 })),+ 400,+ ),);- });-- it("keeps the app-mode marking inside a track shorter than itself", () => {- const state = readScrollState(- fakeTerminal({ type: "alternate", mouseTrackingMode: "any" }),- );-- expect(thumbGeometry(state, GRIP_MARKER_PX - 8)).toEqual({- topPx: 0,- heightPx: GRIP_MARKER_PX - 8,- markerPx: 0,- });+ // And the top of the history is the top of the track.+ expect(+ thumbGeometry(readScrollState(term, measured({ offset: 400 })), 400)+ ?.topPx,+ ).toBe(0);});it("draws nothing when there is nothing to scroll", () => {@@ -199,14 +212,15 @@ describe("lineForThumbTop", () => {expect(lineForThumbTop(-500, 400, state)).toBe(0);expect(lineForThumbTop(5000, 400, state)).toBe(1000);});-});-describe("jogNotches", () => {- it("converts a drag distance into whole wheel notches", () => {- expect(jogNotches(0)).toBe(0);- expect(jogNotches(JOG_STEP_PX - 1)).toBe(0);- expect(jogNotches(JOG_STEP_PX * 3)).toBe(3);- expect(jogNotches(-JOG_STEP_PX * 2)).toBe(-2);+ it("answers for an app-mode pane too, so its thumb can be dragged", () => {+ const state = readScrollState(+ fakeTerminal({ type: "alternate", mouseTrackingMode: "any", rows: 24 }),+ measured({ offset: 400 }),+ );++ expect(lineForThumbTop(0, 400, state)).toBe(0);+ expect(lineForThumbTop(400, 400, state)).toBe(400);});});@@ -230,7 +244,8 @@ describe("relayWheelNotch", () => {expect(seen).toHaveLength(1);// Lines, not pixels: xterm divides a pixel delta by the row height and// carries the remainder, so a synthetic pixel delta can round to no lines- // at all and be dropped before it is ever encoded.+ // at all and be dropped before it is ever encoded. It is also how+ // ./paneAppScroll recognises a notch it sent itself.expect(seen[0].deltaMode).toBe(1);expect(seen[0].deltaY).toBe(-1);});diff --git a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.ts b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.tsindex 2c3b1aa57b..53d2bb5e2f 100644--- a/jarvis/ui/web/frontend/src/components/agentic/paneScroll.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/paneScroll.ts@@ -40,35 +40,45 @@* looking at, and any proportional thumb drawn from it is a lie. So the check* below reads the mouse FIRST and the buffer type second.*- * Hence two modes, and a scrollbar that reads which one it is in:+ * Hence two sources for one and the same picture:** * `scrollback` — the terminal holds the history and the wheel (Codex, a plain- * shell). The thumb is proportional and exact, and dragging it moves the- * viewport.+ * shell). Position and extent are read straight off xterm's buffer.* * `app` — the application took the mouse, so it holds the history (Claude- * Code). There is no honest position to draw, so the bar becomes a full-track- * grip: dragging it relays wheel notches to the CLI, which scrolls itself.- * * `none` — nothing to scroll (a fresh pane, or a full-screen app that does- * not take the mouse). The bar stays away instead of drawing a dead track.- *- * ## A short bar in the middle of a track IS a position claim- *- * `app` mode first drew a fixed 44px grip centred in the track, on the reasoning- * that a grip which never moves cannot be lying. It was — just in a language the- * code was not reading. Every scrollbar anyone has ever used says "you are here"- * with exactly that shape, so a pane parked at the live end of Claude Code's- * transcript showed a thumb halfway up its track and was read, correctly by the- * only grammar available, as "you are halfway up". Abstaining from a claim is- * not the same as saying nothing when the shape you abstain with is the shape- * the claim is made in.- *- * So the grip now fills the track end to end — the universal "there is no- * position here" — carrying a small marking that shows it can be grabbed and- * follows a drag for feedback. The bar occupies the whole track in either- * direction, which is the one arrangement no scrollbar has ever used to mean- * "somewhere in the middle".+ * Code). Position and extent are MEASURED from how far the screen's content+ * moves when it is scrolled — see ./paneAppScroll.+ * * `none` — nothing to scroll (a fresh pane, or a full-screen app measured as+ * having no history at all). The bar stays away instead of drawing a dead+ * track.+ *+ * ## Both modes draw the same thumb, because both now know the same things+ *+ * `app` mode used to draw a fixed grip centred in the track instead of a+ * position, on the reasoning that a shape which never moves cannot lie. It+ * lied anyway — just in a language the code was not reading. Every scrollbar+ * anyone has ever used says "you are here" with exactly that shape, so a pane+ * parked at the live end of Claude Code's transcript showed a marking halfway+ * up its track and was read, correctly by the only grammar available, as "you+ * are halfway up" (reported 2026-07-27). Abstaining from a claim is not the+ * same as saying nothing when the shape you abstain with is the shape the+ * claim is made in.+ *+ * The fix was not a different shape but a real answer: ./paneAppScroll measures+ * the application's position from its own screen, so `app` mode has a genuine+ * line count to report and the geometry below is shared, unconditionally. The+ * only thing still specific to `app` mode is HOW a drag is carried out —+ * relayed wheel notches instead of a viewport call — because that is the only+ * language the application listens in.*/import type { Terminal } from "@xterm/xterm";+import {+ appScrollExtent,+ appTakesWheel,+ AT_LIVE_END,+ type AppScrollPosition,+} from "./paneAppScroll";++export { appTakesWheel };/** Which of the two scrolling worlds a pane is in — see the file header. */export type PaneScrollMode = "scrollback" | "app" | "none";@@ -86,14 +96,6 @@ export interface PaneScrollState {export interface ThumbGeometry {topPx: number;heightPx: number;- /**- * `app` mode only: where the grip's marking sits inside the bar. The bar- * itself spans the whole track and says nothing about position, so this is- * drag feedback and a "you can grab this" hint, never a location in a- * history. Absent in `scrollback` mode, where the bar's own position is the- * information.- */- markerPx?: number;}export const IDLE_STATE: PaneScrollState = {@@ -106,15 +108,6 @@ export const IDLE_STATE: PaneScrollState = {/** A thumb shorter than this is impossible to grab in a tall pane. */export const MIN_THUMB_PX = 26;-/** Height of the marking on the `app`-mode grip. Encodes no position. */-export const GRIP_MARKER_PX = 22;--/** How far the `app`-mode marking may travel from centre while dragged. */-export const GRIP_TRAVEL_PX = 60;--/** Drag distance that relays one wheel notch in `app` mode. */-export const JOG_STEP_PX = 12;-function clamp(value: number, low: number, high: number): number {return value < low ? low : value > high ? high : value;}@@ -122,11 +115,18 @@ function clamp(value: number, low: number, high: number): number {/*** Read a pane's scroll situation off the live terminal.*+ * `position` is what ./paneAppScroll has measured of an application that holds+ * its own history; it is ignored for a pane whose terminal holds the scrollback+ * itself, where xterm's buffer is the better answer.+ ** Defensive by design: this runs against whatever xterm build the app was* bundled with, and a missing field must degrade to "nothing to scroll" rather* than throw inside a render.*/-export function readScrollState(term: Terminal | null): PaneScrollState {+export function readScrollState(+ term: Terminal | null,+ position: AppScrollPosition = AT_LIVE_END,+): PaneScrollState {const buffer = term?.buffer?.active;const rows = term?.rows ?? 0;if (!term || !buffer || rows < 1) return IDLE_STATE;@@ -135,9 +135,16 @@ export function readScrollState(term: Terminal | null): PaneScrollState {const top = buffer.viewportY ?? 0;// The mouse first — see the file header. An application holding the wheel- // holds the history with it, in EITHER buffer, and the viewport it left- // behind must not be drawn as though it were that history.- if (appTakesWheel(term)) return { mode: "app", total: rows, rows, top: 0 };+ // holds the history with it, in EITHER buffer, so the viewport it left behind+ // is ignored in favour of what the measurement found.+ if (appTakesWheel(term)) {+ const extent = appScrollExtent(position, rows);+ // A measurement that found no history at all — a dashboard, a pager on a+ // short file — takes the bar away rather than drawing a thumb that fills+ // its own track.+ if (extent.total <= rows) return IDLE_STATE;+ return { mode: "app", total: extent.total, rows, top: extent.top };+ }// Alternate buffer without the mouse: the application draws the whole screen// and there is nothing to relay a wheel notch to — the escape sequence would@@ -148,38 +155,13 @@ export function readScrollState(term: Terminal | null): PaneScrollState {return IDLE_STATE;}-/** True when the running application receives wheel events itself. */-export function appTakesWheel(term: Terminal | null): boolean {- const tracking = term?.modes?.mouseTrackingMode;- return Boolean(tracking) && tracking !== "none";-}--/**- * Where to draw the thumb inside a track of `trackPx`, or null for no bar.- *- * In `app` mode `offsetPx` is the live drag offset: the bar stays put — it- * spans the whole track — and its marking follows the pointer while it is held,- * returning to the middle when it is let go.- */+/** Where to draw the thumb inside a track of `trackPx`, or null for no bar. */export function thumbGeometry(state: PaneScrollState,trackPx: number,- offsetPx = 0,): ThumbGeometry | null {if (trackPx <= 0) return null;-- if (state.mode === "app") {- const markerHeight = Math.min(GRIP_MARKER_PX, trackPx);- const centre = (trackPx - markerHeight) / 2;- const travel = clamp(offsetPx, -GRIP_TRAVEL_PX, GRIP_TRAVEL_PX);- return {- topPx: 0,- heightPx: trackPx,- markerPx: Math.round(clamp(centre + travel, 0, trackPx - markerHeight)),- };- }-- if (state.mode !== "scrollback" || state.total <= state.rows) return null;+ if (state.mode === "none" || state.total <= state.rows) return null;const heightPx = Math.min(trackPx,@@ -197,18 +179,13 @@ export function lineForThumbTop(state: PaneScrollState,): number {const geometry = thumbGeometry(state, trackPx);- if (!geometry || state.mode !== "scrollback") return state.top;+ if (!geometry) return state.top;const span = trackPx - geometry.heightPx;const maxTop = state.total - state.rows;if (span <= 0 || maxTop <= 0) return 0;return Math.round(clamp(topPx / span, 0, 1) * maxTop);}-/** How many wheel notches a drag of `deltaPx` is worth in `app` mode. */-export function jogNotches(deltaPx: number): number {- return Math.trunc(deltaPx / JOG_STEP_PX);-}-/*** Hand one wheel notch to the application running in `host`.*@@ -218,6 +195,9 @@ export function jogNotches(deltaPx: number): number {* report accordingly. Writing the bytes ourselves would mean guessing, and a* guess wrong by one protocol arrives in the CLI's prompt as garbage.*+ * Emitted in LINE mode with a delta of exactly one, which is also how+ * ./paneAppScroll recognises its own relays and learns what a notch is worth.+ ** `direction` is +1 to scroll down (towards newer output), -1 for up.*/export function relayWheelNotch(