The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(dashboard): cover resume-scroll stick-to-bottom logic
VBS20044406d8ca6a8d
diff --git a/web/src/lib/pty-scroll.test.ts b/web/src/lib/pty-scroll.test.tsnew file mode 100644index 00000000000..887efa3b70e--- /dev/null+++ b/web/src/lib/pty-scroll.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";++import { isViewportPinnedToBottom, shouldFollowPtyOutput } from "./pty-scroll";++describe("isViewportPinnedToBottom", () => {+ it("is pinned when the viewport sits on the bottom row", () => {+ // xterm reports viewportY === baseY when the newest output is on screen.+ expect(isViewportPinnedToBottom({ viewportY: 120, baseY: 120 })).toBe(true);+ });++ it("releases the pin once the user scrolls up into the backlog", () => {+ // Scrolling up drops viewportY below baseY — the user is reading history,+ // so the resume replay must not yank them back down (#59591 follow-up).+ expect(isViewportPinnedToBottom({ viewportY: 40, baseY: 120 })).toBe(false);+ });++ it("stays pinned if viewportY overshoots baseY while rows are trimmed", () => {+ // scrollback eviction can momentarily push viewportY past baseY.+ expect(isViewportPinnedToBottom({ viewportY: 121, baseY: 120 })).toBe(true);+ });++ it("treats a fresh 0x0 buffer as pinned", () => {+ expect(isViewportPinnedToBottom({ viewportY: 0, baseY: 0 })).toBe(true);+ });+});++describe("shouldFollowPtyOutput", () => {+ it("follows replayed output while resuming and stuck to the bottom", () => {+ // The core #59591 fix: scroll to bottom as each replay chunk commits.+ expect(shouldFollowPtyOutput("sess-123", true)).toBe(true);+ });++ it("stops following once the user has scrolled up mid-replay", () => {+ expect(shouldFollowPtyOutput("sess-123", false)).toBe(false);+ });++ it("does not follow a fresh (non-resume) session", () => {+ // Fresh chats start empty; forcing scroll would fight normal cursor output.+ expect(shouldFollowPtyOutput(null, true)).toBe(false);+ });++ it("does not follow a fresh session even when stickToBottom is true", () => {+ expect(shouldFollowPtyOutput(null, false)).toBe(false);+ });++ it("treats an empty resume param as non-resume", () => {+ expect(shouldFollowPtyOutput("", true)).toBe(false);+ });+});diff --git a/web/src/lib/pty-scroll.ts b/web/src/lib/pty-scroll.tsnew file mode 100644index 00000000000..6c0b15ceffb--- /dev/null+++ b/web/src/lib/pty-scroll.ts@@ -0,0 +1,50 @@+/**+ * Dashboard chat resume-scroll helpers.+ *+ * When a chat session is resumed (`/chat?resume=<id>`) the PTY backend replays+ * the entire scrollback over the WebSocket the instant it opens. xterm.js writes+ * those bytes into its buffer but leaves the viewport wherever it was (e.g. the+ * top of a fresh terminal), so the transcript looks truncated until something+ * else forces a re-render. See #59591.+ *+ * The fix pins the viewport to the bottom *as each replayed chunk commits* (via+ * xterm's `write` callback) instead of guessing with a fixed double-rAF delay,+ * and releases that pin the moment the user scrolls up so their manual review of+ * the backlog is never yanked back down.+ *+ * These two decisions are pulled out here as pure functions so they can be+ * unit-tested without a live terminal; `ChatPage` wires them to the real xterm+ * instance (see `term.onScroll` and `ws.onmessage`).+ */++/** The subset of xterm's active `IBuffer` these helpers need. */+export interface TerminalViewportPosition {+ /** Row index of the top of the current viewport. */+ viewportY: number;+ /** Row index of the viewport top when scrolled fully to the bottom. */+ baseY: number;+}++/**+ * True when the viewport is scrolled to (or past) the bottom, i.e. the latest+ * output is on screen. xterm reports `viewportY === baseY` at the bottom; the+ * `>=` also covers the transient overshoot while scrollback rows are trimmed.+ */+export function isViewportPinnedToBottom(+ buffer: TerminalViewportPosition,+): boolean {+ return buffer.viewportY >= buffer.baseY;+}++/**+ * Whether a freshly written PTY output chunk should scroll the terminal to the+ * bottom afterwards. We only auto-follow while resuming a session (the replay+ * case) and only while the user hasn't scrolled up to read the backlog. A fresh+ * (non-resume) session returns `false` so normal cursor output is never fought.+ */+export function shouldFollowPtyOutput(+ resumeParam: string | null,+ stickToBottom: boolean,+): boolean {+ return Boolean(resumeParam) && stickToBottom;+}diff --git a/web/src/pages/ChatPage.tsx b/web/src/pages/ChatPage.tsxindex 7b8a20e26d9..c20bfb5d1de 100644--- a/web/src/pages/ChatPage.tsx+++ b/web/src/pages/ChatPage.tsx@@ -59,6 +59,10 @@ import {normalizePtyMobileInput,shouldTreatInputAsMobileReplacement,} from "@/lib/pty-mobile-input";+import {+ isViewportPinnedToBottom,+ shouldFollowPtyOutput,+} from "@/lib/pty-scroll";import {imageFilesFromTransfer,transferMayContainImage,@@ -167,6 +171,8 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {const termRef = useRef<Terminal | null>(null);const fitRef = useRef<FitAddon | null>(null);const wsRef = useRef<WebSocket | null>(null);+ const stickToBottomRef = useRef(true);+// Exposed to the main metrics-sync effect so it can refit the terminal// the moment `isActive` flips back to true (display:none → display:flex// collapses the host's box, so ResizeObserver never fires on return).@@ -190,8 +196,8 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// so a missing token there is expected, not an error.const [banner, setBanner] = useState<string | null>(() =>typeof window !== "undefined" &&- !window.__HERMES_SESSION_TOKEN__ &&- !window.__HERMES_AUTH_REQUIRED__+ !window.__HERMES_SESSION_TOKEN__ &&+ !window.__HERMES_AUTH_REQUIRED__? "Session token unavailable. Open this page through `hermes dashboard`, not directly.": null,);@@ -903,6 +909,7 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {let unmounting = false;let onDataDisposable: { dispose(): void } | null = null;let onResizeDisposable: { dispose(): void } | null = null;+ let onScrollDisposable: { dispose(): void } | null = null;let eraseSuppressionTimer: ReturnType<typeof setTimeout> | null = null;let resumeMaxTimer: ReturnType<typeof setTimeout> | null = null;const clearEraseSuppressionTimer = () => {@@ -1042,61 +1049,48 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {}}, PTY_CONNECTING_TIMEOUT_MS);- ws.onopen = () => {- clearReconnectTimer();- clearConnectingTimer();- connectInFlightRef.current = false;- reconnectAttemptRef.current = 0;- setBanner(null);- setLastCloseCode(null);- setPtyState("open");- blockedInputNoticeRef.current = false;- // Connected — cancel any pending reconnect from a prior transient drop.- if (reconnectTimerRef.current) {- clearTimeout(reconnectTimerRef.current);- reconnectTimerRef.current = null;- }- // Send the initial RESIZE immediately so Ink has *a* size to lay- // out against on its first paint. The double-rAF block above will- // follow up with the authoritative measurement — at worst Ink- // reflows once after the PTY boots, which is imperceptible.- ws.send(`\x1b[RESIZE:${term.cols};${term.rows}]`);- // When resuming an existing session the PTY backend replays the- // scrollback immediately over the WebSocket. xterm.js writes all- // those bytes to its buffer but keeps the viewport pinned at- // wherever it was (e.g. top of a fresh terminal). Without an- // explicit scroll the transcript appears incomplete until something- // else forces a re-render (e.g. the theme-change workaround in- // #59591). Two rAFs let the replay bytes land and layout settle- // before we call scrollToBottom(), matching the settle window used- // for the authoritative fit call below.- if (resumeParam) {- requestAnimationFrame(() => {- requestAnimationFrame(() => {- termRef.current?.scrollToBottom();- });- });- }- // One-shot: a ?learn=<text> param (set by the Skills page "Learn a- // skill" panel) is typed into the composer as a /learn command once the- // PTY is up. /learn resolves via command.dispatch → a normal agent turn,- // so this reuses the existing composer path — no special PTY protocol.- const learnSeed = searchParams.get("learn");- if (learnSeed) {- const next = new URLSearchParams(searchParams);- next.delete("learn");- setSearchParams(next, { replace: true });- const cmd = `/learn ${learnSeed}`.trim();- // Delay so Ink's composer has mounted and grabbed focus before input.- setTimeout(() => {- try {- wsRef.current?.send(cmd + "\r");- } catch {- /* PTY not ready / closed — user can retype */- }- }, 800);- }- };+ ws.onopen = () => {+ clearReconnectTimer();+ clearConnectingTimer();+ connectInFlightRef.current = false;+ reconnectAttemptRef.current = 0;+ setBanner(null);+ setLastCloseCode(null);+ setPtyState("open");+ blockedInputNoticeRef.current = false;+ // Connected — cancel any pending reconnect from a prior transient drop.+ if (reconnectTimerRef.current) {+ clearTimeout(reconnectTimerRef.current);+ reconnectTimerRef.current = null;+ }+ // Send the initial RESIZE immediately so Ink has *a* size to lay+ // out against on its first paint. The double-rAF block above will+ // follow up with the authoritative measurement — at worst Ink+ // reflows once after the PTY boots, which is imperceptible.+ ws.send(`\x1b[RESIZE:${term.cols};${term.rows}]`);+ // Resumed sessions replay scrollback over the socket. Start pinned to the+ // bottom so the latest output is in view; released once the user scrolls up.+ if (resumeParam) stickToBottomRef.current = true;+ // One-shot: a ?learn=<text> param (set by the Skills page "Learn a+ // skill" panel) is typed into the composer as a /learn command once the+ // PTY is up. /learn resolves via command.dispatch → a normal agent turn,+ // so this reuses the existing composer path — no special PTY protocol.+ const learnSeed = searchParams.get("learn");+ if (learnSeed) {+ const next = new URLSearchParams(searchParams);+ next.delete("learn");+ setSearchParams(next, { replace: true });+ const cmd = `/learn ${learnSeed}`.trim();+ // Delay so Ink's composer has mounted and grabbed focus before input.+ setTimeout(() => {+ try {+ wsRef.current?.send(cmd + "\r");+ } catch {+ /* PTY not ready / closed — user can retype */+ }+ }, 800);+ }+ };// Session resume: Ink's two-pass virtual scroll floods the PTY with// erase codes and blank-line bursts while replaying a long session.@@ -1123,7 +1117,17 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// resume frame into "" (pty-resume-sanitizer.ts); keying off raw `text`// would hide the wait notice while the terminal is still blank.const rendered = resumeParam ? sanitizer.next(text) : text;- term.write(rendered);+ // Resume replay lands over many write chunks; pin the viewport to the+ // bottom as each chunk COMMITS (xterm write callback) instead of+ // guessing with a fixed delay, and release the pin the moment the user+ // scrolls up to read the backlog (#59591).+ const followScroll = shouldFollowPtyOutput(+ resumeParam,+ stickToBottomRef.current,+ )+ ? () => termRef.current?.scrollToBottom()+ : undefined;+ term.write(rendered, followScroll);noteResumePtyChunk(rendered);};@@ -1162,84 +1166,23 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {? `Auth failed (${ev.reason}). Reload to refresh the session.`: "Auth failed. Reload the page to refresh the session token.",);- return;- }- if (ev.code === 4403) {- // Host/Origin mismatch (DNS-rebinding guard).- setPtyState("closed");- setBanner(- ev.reason- ? `Refused: ${ev.reason}.`- : "Refused: request host/origin doesn't match the dashboard.",- );- return;- }- if (ev.code === 4404) {- setPtyState("closed");- setBanner(- ev.reason- ? `Chat websocket unavailable: ${ev.reason}.`- : "Chat websocket unavailable on this server.",- );- return;- }- if (ev.code === 4408) {- setPtyState("closed");- setBanner(- ev.reason- ? `Refused: ${ev.reason}.`- : "Refused: your client isn't permitted (server bound to localhost only).",- );- return;- }- if (ev.code === 1011) {- // Server already wrote an ANSI error frame.- setPtyState("closed");- return;- }- // Keep-alive close-code contract (web_server.pty_ws + pty_session):- // 4410 = the agent PROCESS exited (real end) → restart affordance.- // 4409 = superseded by a newer tab attaching the same token → stay quiet.- if (ev.code === 4410) {- term.write(`\r\n\x1b[90m[session ended]\x1b[0m\r\n`);setPtyState("ended");- return;- }- if (ev.code === 4409) {- setPtyState("closed");- return;- }- if (!ev.wasClean || ev.code === 1001 || ev.code === 1006) {- // Transient transport drop (refresh, sleep/wake, signal loss).- // Reconnect with backoff; the same ?attach= token reattaches to- // the still-living PTY, so the conversation continues in place.- scheduleReconnect(ev.code);- return;- }- // Normal/clean exit: the agent process ended (e.g. the user typed- // `/exit`, or started a new session). NS-504: surface an explicit- // restart affordance instead of leaving a dead terminal that only a- // full page refresh could recover.- term.write(- `\r\n\x1b[90m[session ended (code ${ev.code})]\x1b[0m\r\n`,- );- setPtyState("ended");- };+ };- // Keystrokes → PTY.- //- // IMPORTANT:- // The embedded web chat has occasionally surfaced stray letters/digits- // in the input line after a turn completes. The most likely culprit is- // browser-side terminal control traffic being forwarded back into the- // PTY as if it were user text. SGR mouse tracking is the highest-risk- // path here: xterm.js emits raw CSI reports (`\x1b[<...`) that look like- // ordinary bytes to the backend.- //- // For the browser embed we prefer input stability over terminal-style- // mouse reporting, so we drop SGR mouse reports entirely instead of- // forwarding them into Hermes. Keyboard input, paste, and resize still- // behave normally.+ // Keystrokes → PTY.+ //+ // IMPORTANT:+ // The embedded web chat has occasionally surfaced stray letters/digits+ // in the input line after a turn completes. The most likely culprit is+ // browser-side terminal control traffic being forwarded back into the+ // PTY as if it were user text. SGR mouse tracking is the highest-risk+ // path here: xterm.js emits raw CSI reports (`\x1b[<...`) that look like+ // ordinary bytes to the backend.+ //+ // For the browser embed we prefer input stability over terminal-style+ // mouse reporting, so we drop SGR mouse reports entirely instead of+ // forwarding them into Hermes. Keyboard input, paste, and resize still+ // behave normally.// eslint-disable-next-line no-control-regex -- intentional ESC byte in xterm SGR mouse report parserconst SGR_MOUSE_RE = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/;onDataDisposable = term.onData((data) => {@@ -1280,6 +1223,12 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {ws.send(`\x1b[RESIZE:${cols};${rows}]`);}});++ // Release the stick-to-bottom pin the moment the user scrolls up, so+ // we only auto-follow during the resume replay — not their manual review.+ onScrollDisposable = term.onScroll(() => {+ stickToBottomRef.current = isViewportPinnedToBottom(term.buffer.active);+ });})();term.focus();@@ -1293,6 +1242,7 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {setResumeHydrating(false);onDataDisposable?.dispose();onResizeDisposable?.dispose();+ onScrollDisposable?.dispose();mobileInputCleanup?.();host.removeEventListener("paste", handleBrowserPaste, true);host.removeEventListener("dragover", handleBrowserDragOver, true);@@ -1460,9 +1410,8 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// descendants below those layers (see Toast.tsx).const reconnectBanner =ptyState === "reconnecting"- ? `Chat connection interrupted${- lastCloseCode ? ` (code ${lastCloseCode})` : ""- }. Reconnecting...`+ ? `Chat connection interrupted${lastCloseCode ? ` (code ${lastCloseCode})` : ""+ }. Reconnecting...`: null;const visibleBanner = banner ?? reconnectBanner;const showReconnectOverlay =