Skip to content
8 changes: 4 additions & 4 deletions ui-tui/packages/hermes-ink/src/ink/components/ScrollBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ export type ScrollBoxHandle = {
*/
isSticky: () => boolean
/**
* Subscribe to imperative scroll changes (scrollTo/scrollBy/scrollToBottom).
* Does NOT fire for stickyScroll updates done by the Ink renderer — those
* happen during Ink's render phase after React has committed. Callers that
* care about the sticky case should treat "at bottom" as a fallback.
* Subscribe to scroll viewport changes. Fires for imperative scroll changes
* (scrollTo/scrollBy/scrollToBottom) and for renderer-computed scroll bounds
* changes such as content growth or terminal resize. Callers use this to
* keep virtualized ranges aligned with the currently visible viewport.
*/
subscribe: (listener: () => void) => () => void
/**
Expand Down
26 changes: 25 additions & 1 deletion ui-tui/packages/hermes-ink/src/ink/log-update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ const stdoutOnly = (diff: ReturnType<LogUpdate['render']>) =>
.map(p => (p as { type: 'stdout'; content: string }).content)
.join('')

const hasDecstbm = (text: string) => /\x1b\[\d+;\d+r/.test(text)
const ESC = '\u001b'
const hasDecstbm = (text: string) => new RegExp(`${ESC}\\[\\d+;\\d+r`).test(text)

describe('LogUpdate.render diff contract', () => {
it('emits only changed cells when most rows match', () => {
Expand Down Expand Up @@ -87,6 +88,25 @@ describe('LogUpdate.render diff contract', () => {
expect(stdoutOnly(diff)).toContain('shorterrownow')
})

it('height growth emits a clearTerminal patch before repainting', () => {
const w = 20
const prevH = 3
const nextH = 6

const prev = mkScreen(w, prevH)
paint(prev, 0, 'old rows')

const next = mkScreen(w, nextH)
paint(next, 0, 'new rows')
next.damage = { x: 0, y: 0, width: w, height: nextH }

const log = new LogUpdate({ isTTY: true, stylePool })
const diff = log.render(mkFrame(prev, w, prevH), mkFrame(next, w, nextH), true, false)

expect(diff.some(p => p.type === 'clearTerminal')).toBe(true)
expect(stdoutOnly(diff)).toContain('newrows')
})

it('drift repro: identical prev/next emits no heal, even when the physical terminal is stale', () => {
// Load-bearing theory for the rapid-resize scattered-letter bug: if the
// physical terminal has stale cells that prev.screen doesn't know about
Expand Down Expand Up @@ -167,10 +187,12 @@ describe('LogUpdate.render diff contract', () => {
paint(next, 1, 'row one')

const prevFrame = mkFrame(prev, w, h)

const nextFrame: Frame = {
...mkFrame(next, w, h),
scrollHint: { top: 1, bottom: 4, delta: 1 }
}

const log = new LogUpdate({ isTTY: true, stylePool })
const diff = log.render(prevFrame, nextFrame, true, true)

Expand All @@ -187,10 +209,12 @@ describe('LogUpdate.render diff contract', () => {
paint(next, 1, 'row one')

const prevFrame = mkFrame(prev, w, h)

const nextFrame: Frame = {
...mkFrame(next, w, h),
scrollHint: { top: 1, bottom: 5, delta: 1 }
}

const log = new LogUpdate({ isTTY: true, stylePool })
const diff = log.render(prevFrame, nextFrame, true, true)

Expand Down
12 changes: 5 additions & 7 deletions ui-tui/packages/hermes-ink/src/ink/log-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,12 @@ export class LogUpdate {
const startTime = performance.now()
const stylePool = this.options.stylePool

// Since we assume the cursor is at the bottom on the screen, we only need
// to clear when the viewport gets shorter (i.e. the cursor position drifts)
// or when it gets thinner (and text wraps). We _could_ figure out how to
// not reset here but that would involve predicting the current layout
// _after_ the viewport change which means calcuating text wrapping.
// Resizing is a rare enough event that it's not practically a big issue.
// Terminal hosts can reflow/preserve old cells on any resize, including
// height-only growth. A partial diff can then leave stale transcript rows
// or cut off bordered content even when our virtual scrollTop is correct.
// Resizing is rare enough that a full repaint is the safer tradeoff.
if (
next.viewport.height < prev.viewport.height ||
next.viewport.height !== prev.viewport.height ||
(prev.viewport.width !== 0 && next.viewport.width !== prev.viewport.width)
) {
return fullResetSequence_CAUSES_FLICKER(next, 'resize', stylePool)
Expand Down
38 changes: 30 additions & 8 deletions ui-tui/packages/hermes-ink/src/ink/render-node-to-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -706,12 +706,22 @@ function renderNodeToOutput(
const content = node.childNodes.find(c => (c as DOMElement).yogaNode) as DOMElement | undefined

const contentYoga = content?.yogaNode
// scrollHeight is the intrinsic height of the content wrapper.
// Do NOT add getComputedTop() — that's the wrapper's offset
// within the viewport (equal to the scroll container's
// paddingTop), and innerHeight already subtracts padding, so
// including it double-counts padding and inflates maxScroll.
const scrollHeight = contentYoga?.getComputedHeight() ?? 0
// scrollHeight is the intrinsic height of the content wrapper, but
// after terminal resizes Yoga can leave tall descendants overflowing
// that wrapper. Use the deepest direct child bottom so sticky-bottom
// math can still reach the real final rendered row.
let scrollHeight = Math.ceil(contentYoga?.getComputedHeight() ?? 0)

if (content) {
for (const child of content.childNodes) {
const childYoga = (child as DOMElement).yogaNode

if (childYoga) {
scrollHeight = Math.max(scrollHeight, Math.ceil(childYoga.getComputedTop() + childYoga.getComputedHeight()))
}
}
}

// Capture previous scroll bounds BEFORE overwriting — the at-bottom
// follow check compares against last frame's max.
const prevScrollHeight = node.scrollHeight ?? scrollHeight
Expand Down Expand Up @@ -862,7 +872,12 @@ function renderNodeToOutput(
scrollDrainNode = node
}

if ((node.scrollTop ?? 0) !== scrollTopBeforeFollow || node.stickyScroll !== stickyBeforeFollow) {
if (
(node.scrollTop ?? 0) !== scrollTopBeforeFollow ||
node.stickyScroll !== stickyBeforeFollow ||
scrollHeight !== prevScrollHeight ||
innerHeight !== prevInnerHeight
Comment thread
OutThisLife marked this conversation as resolved.
Resolved
) {
node.notifyScrollChange?.()
}

Expand Down Expand Up @@ -891,7 +906,14 @@ function renderNodeToOutput(
const regionTop = Math.floor(y + contentYoga.getComputedTop())
const regionBottom = regionTop + innerHeight - 1

if (cached?.y === y && cached.height === height && innerHeight > 0 && Math.abs(delta) < innerHeight) {
if (
cached?.x === x &&
cached.y === y &&
cached.width === width &&
cached.height === height &&
innerHeight > 0 &&
Math.abs(delta) < innerHeight
) {
hint = { top: regionTop, bottom: regionBottom, delta }
scrollHint = hint
} else {
Expand Down
141 changes: 134 additions & 7 deletions ui-tui/src/__tests__/virtualHistoryOffsetCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { Box, renderSync, ScrollBox, type ScrollBoxHandle, Text } from '@hermes/
import React, { useLayoutEffect, useRef } from 'react'
import { describe, expect, it } from 'vitest'

import { useVirtualHistory } from '../hooks/useVirtualHistory.js'
import { useVirtualHistory, virtualHistorySnapshotKey } from '../hooks/useVirtualHistory.js'

interface Item {
height: number
heightAfterResize?: number
key: string
}

Expand Down Expand Up @@ -49,13 +50,28 @@ const viewportIsMounted = (items: readonly Item[], virtualHistory: ReturnType<ty
return top >= span.top && bottom <= span.bottom
}

function Harness({ expose, items }: { expose: React.MutableRefObject<Exposed | null>; items: readonly Item[] }) {
const itemHeightForColumns = (item: Item | undefined, columns: number) =>
columns >= 80 ? (item?.heightAfterResize ?? item?.height ?? 1) : (item?.height ?? 1)

function Harness({
columns = 80,
expose,
height = 10,
items,
maxMounted = 16
}: {
columns?: number
expose: React.MutableRefObject<Exposed | null>
height?: number
items: readonly Item[]
maxMounted?: number
}) {
const scrollRef = useRef<ScrollBoxHandle | null>(null)

const virtualHistory = useVirtualHistory(scrollRef, items, 80, {
const virtualHistory = useVirtualHistory(scrollRef, items, columns, {
coldStartCount: 16,
estimateHeight: index => items[index]?.height ?? 1,
maxMounted: 16,
estimateHeight: index => itemHeightForColumns(items[index], columns),
maxMounted,
overscan: 2
})

Expand All @@ -65,7 +81,7 @@ function Harness({ expose, items }: { expose: React.MutableRefObject<Exposed | n

return React.createElement(
ScrollBox,
{ flexDirection: 'column', height: 10, ref: scrollRef, stickyScroll: true },
{ flexDirection: 'column', height, ref: scrollRef, stickyScroll: true },
React.createElement(
Box,
{ flexDirection: 'column', width: '100%' },
Expand All @@ -75,7 +91,11 @@ function Harness({ expose, items }: { expose: React.MutableRefObject<Exposed | n
.map(item =>
React.createElement(
Box,
{ height: item.height, key: item.key, ref: virtualHistory.measureRef(item.key) },
{
height: itemHeightForColumns(item, columns),
key: item.key,
ref: virtualHistory.measureRef(item.key)
},
React.createElement(Text, null, item.key)
)
),
Expand All @@ -85,6 +105,113 @@ function Harness({ expose, items }: { expose: React.MutableRefObject<Exposed | n
}

describe('useVirtualHistory offset cache reuse', () => {
it('includes viewport height in the external-store snapshot key', () => {
const base = {
getPendingDelta: () => 0,
getScrollTop: () => 20,
isSticky: () => false
}

const short = virtualHistorySnapshotKey({
...base,
getViewportHeight: () => 5
} as ScrollBoxHandle)

const tall = virtualHistorySnapshotKey({
...base,
getViewportHeight: () => 25
} as ScrollBoxHandle)

expect(short).not.toBe(tall)
})

it('remounts enough tail rows after the scroll viewport grows', async () => {
const items = Array.from({ length: 100 }, (_, index) => ({ height: 1, key: `item-${index}` }))
const expose = { current: null as Exposed | null }
const streams = makeStreams()

const instance = renderSync(React.createElement(Harness, { expose, height: 4, items, maxMounted: 80 }), {
patchConsole: false,
stderr: streams.stderr as NodeJS.WriteStream,
stdin: streams.stdin as NodeJS.ReadStream,
stdout: streams.stdout as NodeJS.WriteStream
})

try {
await delay(20)
instance.rerender(React.createElement(Harness, { expose, height: 9, items, maxMounted: 80 }))
await delay(80)

expect(viewportIsMounted(items, expose.current!.virtualHistory, expose.current!.scroll!)).toBe(true)
} finally {
instance.unmount()
instance.cleanup()
}
})

it('recomputes tail coverage when wrapped rows shrink after a width resize', async () => {
const items = Array.from({ length: 100 }, (_, index) => ({
height: 4,
heightAfterResize: 1,
key: `item-${index}`
}))

const expose = { current: null as Exposed | null }
const streams = makeStreams()

const instance = renderSync(
React.createElement(Harness, { columns: 40, expose, height: 10, items, maxMounted: 80 }),
{
patchConsole: false,
stderr: streams.stderr as NodeJS.WriteStream,
stdin: streams.stdin as NodeJS.ReadStream,
stdout: streams.stdout as NodeJS.WriteStream
}
)

try {
await delay(20)
instance.rerender(React.createElement(Harness, { columns: 80, expose, height: 10, items, maxMounted: 80 }))
await delay(80)

const resizedItems = items.map(item => ({ height: item.heightAfterResize!, key: item.key }))

expect(viewportIsMounted(resizedItems, expose.current!.virtualHistory, expose.current!.scroll!)).toBe(true)
} finally {
instance.unmount()
instance.cleanup()
}
})

it('keeps sticky scroll at the bottom when one tall tail row resizes', async () => {
const items = [{ height: 90, heightAfterResize: 50, key: 'tail' }]
const expose = { current: null as Exposed | null }
const streams = makeStreams()

const instance = renderSync(
React.createElement(Harness, { columns: 70, expose, height: 18, items, maxMounted: 80 }),
{
patchConsole: false,
stderr: streams.stderr as NodeJS.WriteStream,
stdin: streams.stdin as NodeJS.ReadStream,
stdout: streams.stdout as NodeJS.WriteStream
}
)

try {
await delay(20)
instance.rerender(React.createElement(Harness, { columns: 120, expose, height: 36, items, maxMounted: 80 }))
await delay(80)

const scroll = expose.current!.scroll!

expect(scroll.getScrollTop()).toBe(scroll.getScrollHeight() - scroll.getViewportHeight())
} finally {
instance.unmount()
instance.cleanup()
}
})

it('recomputes offsets after a mounted row height changes', async () => {
const tall = [
{ height: 6, key: 'a' },
Expand Down
14 changes: 12 additions & 2 deletions ui-tui/src/app/useMainApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,8 @@ export function useMainApp(gw: GatewayClient) {
}, [])

const virtualRows = useMemo<TranscriptRow[]>(
() => historyItems.map((msg, index) => ({ index, key: messageId(msg), msg })),
[historyItems, messageId]
() => historyItems.map((msg, index) => ({ index, key: `${messageId(msg)}:c${cols}`, msg })),
[cols, historyItems, messageId]
Comment thread
OutThisLife marked this conversation as resolved.
Resolved
)

const detailsLayoutKey = useMemo(() => {
Expand Down Expand Up @@ -424,10 +424,20 @@ export function useMainApp(gw: GatewayClient) {

let timer: ReturnType<typeof setTimeout> | undefined

// Resize reflows wrapped lines; if the user was pinned to the tail we need
// to re-snap once React has remeasured. virtualRows is keyed on cols so
// every column change forces a fresh measurement pass before this fires.
const onResize = () => {
const wasSticky = scrollRef.current?.isSticky() ?? false

clearTimeout(timer)
timer = setTimeout(() => {
timer = undefined

if (wasSticky) {
Comment thread
OutThisLife marked this conversation as resolved.
Resolved
scrollRef.current?.scrollToBottom()
}

void rpc<TerminalResizeResponse>('terminal.resize', { cols: stdout.columns ?? 80, session_id: ui.sid })
}, 100)
}
Expand Down
4 changes: 2 additions & 2 deletions ui-tui/src/banner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ const colorize = (art: string[], gradient: readonly number[], c: ThemeColors): L
return art.map((text, i) => [p[gradient[i]!] ?? c.muted, text])
}

export const LOGO_WIDTH = 98
export const CADUCEUS_WIDTH = 30
export const LOGO_WIDTH = Math.max(...LOGO_ART.map(line => line.length))
export const CADUCEUS_WIDTH = Math.max(...CADUCEUS_ART.map(line => line.length))

export const logo = (c: ThemeColors, customLogo?: string): Line[] =>
customLogo ? parseRichMarkup(customLogo) : colorize(LOGO_ART, LOGO_GRADIENT, c)
Expand Down
4 changes: 2 additions & 2 deletions ui-tui/src/components/appLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ const TranscriptPane = memo(function TranscriptPane({

{row.msg.kind === 'intro' ? (
<Box flexDirection="column" paddingTop={1}>
<Banner t={ui.theme} />
<Banner maxWidth={Math.max(1, composer.cols - 2)} t={ui.theme} />

{row.msg.info && <SessionPanel info={row.msg.info} sid={ui.sid} t={ui.theme} />}
{row.msg.info && <SessionPanel info={row.msg.info} maxWidth={Math.max(1, composer.cols - 2)} sid={ui.sid} t={ui.theme} />}
</Box>
) : row.msg.kind === 'panel' && row.msg.panelData ? (
<Panel sections={row.msg.panelData.sections} t={ui.theme} title={row.msg.panelData.title} />
Expand Down
Loading
Loading