The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tui): simplify native mode paths
brooklyn!7e35460ac278
diff --git a/ui-tui/scripts/bench-native-history.tsx b/ui-tui/scripts/bench-native-history.tsxindex 1d8a2dd7b2d..0549e73cc78 100644--- a/ui-tui/scripts/bench-native-history.tsx+++ b/ui-tui/scripts/bench-native-history.tsx@@ -3,15 +3,13 @@// Run from ui-tui:// npx tsx scripts/bench-native-history.tsx --warmups=1 --samples=3 --items=100,1000,10000//-// Native terminal scrolling is handled by the terminal emulator after rows are-// written, so it has no app-side scroll operation to time. This measures the-// work that differs: initial history mount, a long-history rerender, memory,-// and terminal output. The virtual path also reports its app-side scroll cost.+// Native scrolling is handled by the terminal after rows are written, so this+// compares the work before scrolling begins: mount, rerender, memory, and output.import { PassThrough } from 'stream'import { Box, renderSync, ScrollBox, type ScrollBoxHandle, Text } from '@hermes/ink'-import React, { useLayoutEffect, useRef } from 'react'+import React from 'react'import { useVirtualHistory } from '../src/hooks/useVirtualHistory.js'@@ -31,16 +29,12 @@ interface Sample {heapDeltaBytes: number | nullmountMs: numberrerenderMs: number- scrollMs: number | nullterminalBytes: numberterminalWrites: number}-interface HarnessProps {- items: readonly Item[]- expose?: React.MutableRefObject<ScrollBoxHandle | null>- scrollRef?: React.MutableRefObject<ScrollBoxHandle | null>-}+type ItemsProps = { items: readonly Item[] }+type VirtualProps = ItemsProps & { scrollRef: React.MutableRefObject<ScrollBoxHandle | null> }class CountingStream extends PassThrough {columns = COLUMNS@@ -72,7 +66,7 @@ function makeItems(count: number): Item[] {}))}-function NativeHarness({ items }: HarnessProps) {+function NativeHarness({ items }: ItemsProps) {return (<Box flexDirection="column" width="100%">{items.map(item => (@@ -84,7 +78,7 @@ function NativeHarness({ items }: HarnessProps) {)}-function VirtualHarness({ expose, items, scrollRef }: HarnessProps) {+function VirtualHarness({ items, scrollRef }: VirtualProps) {const virtual = useVirtualHistory(scrollRef!, items, COLUMNS, {coldStartCount: 30,estimateHeight: index => items[index]?.height ?? 1,@@ -92,10 +86,6 @@ function VirtualHarness({ expose, items, scrollRef }: HarnessProps) {overscan: 20})- useLayoutEffect(() => {- expose!.current = scrollRef!.current- }, [expose, scrollRef])-return (<ScrollBox flexDirection="column" height={ROWS} ref={scrollRef} stickyScroll><Box flexDirection="column" width="100%">@@ -116,23 +106,23 @@ async function runSample(mode: 'native' | 'virtual', itemCount: number): Promiseconst stderr = new CountingStream()const stdin = new PassThrough()const scrollRef = { current: null as ScrollBoxHandle | null }- const exposedScrollRef = { current: null as ScrollBoxHandle | null }- let items = makeItems(itemCount)- const heapBefore = process.memoryUsage?.().heapUsed ?? null- const mountStart = performance.now()- const instance = renderSync(++ const items = makeItems(itemCount)+ const renderHarness = (nextItems: readonly Item[]) =>mode === 'native' ? (- <NativeHarness items={items} />+ <NativeHarness items={nextItems} />) : (- <VirtualHarness expose={exposedScrollRef} items={items} scrollRef={scrollRef} />- ),- {- patchConsole: false,- stderr: stderr as unknown as NodeJS.WriteStream,- stdin: stdin as unknown as NodeJS.ReadStream,- stdout: stdout as unknown as NodeJS.WriteStream- }- )+ <VirtualHarness items={nextItems} scrollRef={scrollRef} />+ )++ const heapBefore = process.memoryUsage?.().heapUsed ?? null+ const mountStart = performance.now()+ const instance = renderSync(renderHarness(items), {+ patchConsole: false,+ stderr: stderr as unknown as NodeJS.WriteStream,+ stdin: stdin as unknown as NodeJS.ReadStream,+ stdout: stdout as unknown as NodeJS.WriteStream+ })await settle()const mountMs = performance.now() - mountStart@@ -140,31 +130,14 @@ async function runSample(mode: 'native' | 'virtual', itemCount: number): Promiseindex === items.length - 1 ? { ...item, text: `${item.text} rerender` } : item)const rerenderStart = performance.now()- instance.rerender(- mode === 'native' ? (- <NativeHarness items={rerenderItems} />- ) : (- <VirtualHarness expose={exposedScrollRef} items={rerenderItems} scrollRef={scrollRef} />- )- )+ instance.rerender(renderHarness(rerenderItems))await settle()const rerenderMs = performance.now() - rerenderStart- items = rerenderItems-- let scrollMs: number | null = null- if (mode === 'virtual' && exposedScrollRef.current) {- const scrollStart = performance.now()- exposedScrollRef.current.scrollTo(Math.max(0, itemCount - ROWS))- await settle(8)- scrollMs = performance.now() - scrollStart- }-const heapAfter = process.memoryUsage?.().heapUsed ?? nullconst sample = {heapDeltaBytes: heapBefore === null || heapAfter === null ? null : heapAfter - heapBefore,mountMs,rerenderMs,- scrollMs,terminalBytes: stdout.bytes,terminalWrites: stdout.writes}@@ -217,7 +190,6 @@ function summarize(samples: Sample[]) {heapDeltaBytes: distribution(samples.flatMap(sample => sample.heapDeltaBytes ?? [])),mountMs: distribution(samples.map(sample => sample.mountMs)),rerenderMs: distribution(samples.map(sample => sample.rerenderMs)),- scrollMs: distribution(samples.flatMap(sample => sample.scrollMs ?? [])),terminalBytes: distribution(samples.map(sample => sample.terminalBytes)),terminalWrites: distribution(samples.map(sample => sample.terminalWrites))}diff --git a/ui-tui/src/__tests__/terminalModes.test.ts b/ui-tui/src/__tests__/terminalModes.test.tsindex dee266083ec..e22ecd56e00 100644--- a/ui-tui/src/__tests__/terminalModes.test.ts+++ b/ui-tui/src/__tests__/terminalModes.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import {+ clearNativeTuiFrame,isPaintableHex,resetTerminalModes,setTerminalBackground,@@ -9,6 +10,17 @@ import {} from '../lib/terminalModes.js'describe('terminal mode reset', () => {+ it('clears the native frame only on TTY streams', () => {+ const write = vi.fn()+ const tty = { isTTY: true, write } as unknown as NodeJS.WriteStream+ const pipe = { isTTY: false, write: vi.fn() } as unknown as NodeJS.WriteStream++ expect(clearNativeTuiFrame(tty)).toBe(true)+ expect(write).toHaveBeenCalledWith('\x1b[2J\x1b[H')+ expect(clearNativeTuiFrame(pipe)).toBe(false)+ expect(pipe.write).not.toHaveBeenCalled()+ })+it('writes reset sequence to TTY streams without fds', () => {const write = vi.fn()diff --git a/ui-tui/src/components/appLayout.tsx b/ui-tui/src/components/appLayout.tsxindex 0b080b75100..5ceac38a648 100644--- a/ui-tui/src/components/appLayout.tsx+++ b/ui-tui/src/components/appLayout.tsx@@ -366,6 +366,19 @@ const ComposerPane = memo(function ComposerPane({const endInputDrag = () => inputMouseRef.current?.end()+ const floatingOverlayProps = {+ cols: composer.cols,+ compIdx: composer.compIdx,+ completions: composer.completions,+ onActiveSessionClose: actions.closeLiveSession,+ onActiveSessionSelect: actions.activateLiveSession,+ onModelSelect: actions.onModelSelect,+ onNewLiveSession: actions.newLiveSession,+ onNewPromptSession: actions.newPromptSession,+ onResumeSelect: actions.resumeById,+ pagerPageSize: composer.pagerPageSize+ }+return (<NoSelectflexDirection="column"@@ -411,21 +424,7 @@ const ComposerPane = memo(function ComposerPane({marginTop={nativeMode ? 0 : ui.statusBar === 'top' ? 0 : 1}position={nativeMode ? undefined : 'relative'}>- {!nativeMode && (- <FloatingOverlays- cols={composer.cols}- compIdx={composer.compIdx}- completions={composer.completions}- nativeMode={false}- onActiveSessionClose={actions.closeLiveSession}- onActiveSessionSelect={actions.activateLiveSession}- onModelSelect={actions.onModelSelect}- onNewLiveSession={actions.newLiveSession}- onNewPromptSession={actions.newPromptSession}- onResumeSelect={actions.resumeById}- pagerPageSize={composer.pagerPageSize}- />- )}+ {!nativeMode && <FloatingOverlays {...floatingOverlayProps} nativeMode={false} />}{!nativeMode && composer.input === '?' && !composer.inputBuf.length && <HelpHint t={ui.theme} />}@@ -493,21 +492,7 @@ const ComposerPane = memo(function ComposerPane({)}</Box>- {nativeMode && (- <FloatingOverlays- cols={composer.cols}- compIdx={composer.compIdx}- completions={composer.completions}- nativeMode- onActiveSessionClose={actions.closeLiveSession}- onActiveSessionSelect={actions.activateLiveSession}- onModelSelect={actions.onModelSelect}- onNewLiveSession={actions.newLiveSession}- onNewPromptSession={actions.newPromptSession}- onResumeSelect={actions.resumeById}- pagerPageSize={composer.pagerPageSize}- />- )}+ {nativeMode && <FloatingOverlays {...floatingOverlayProps} nativeMode />}{nativeMode && composer.input === '?' && !composer.inputBuf.length && <HelpHint nativeMode t={ui.theme} />}diff --git a/ui-tui/src/entry.tsx b/ui-tui/src/entry.tsxindex b055bbde431..c9f5c48e055 100644--- a/ui-tui/src/entry.tsx+++ b/ui-tui/src/entry.tsx@@ -13,7 +13,7 @@ import { formatBytes, type HeapDumpResult, performHeapDump } from './lib/memory.import { type MemorySnapshot, startMemoryMonitor } from './lib/memoryMonitor.js'import { openExternalUrl } from './lib/openExternalUrl.js'import { recordParentLifecycle } from './lib/parentLog.js'-import { NATIVE_TUI_EXIT_RESET, resetTerminalModes } from './lib/terminalModes.js'+import { clearNativeTuiFrame, resetTerminalModes } from './lib/terminalModes.js'if (!process.stdin.isTTY) {console.log('hermes-tui: no TTY')@@ -39,11 +39,7 @@ resetTerminalModes()process.on('exit', () => {resetTerminalModes()if (NATIVE_MODE) {- try {- process.stdout.write(NATIVE_TUI_EXIT_RESET)- } catch {- // stdout may already be closed during terminal teardown.- }+ clearNativeTuiFrame()}})diff --git a/ui-tui/src/hooks/useVirtualHistory.ts b/ui-tui/src/hooks/useVirtualHistory.tsindex 817a06321ee..4db11d9be64 100644--- a/ui-tui/src/hooks/useVirtualHistory.ts+++ b/ui-tui/src/hooks/useVirtualHistory.ts@@ -442,8 +442,8 @@ export function useVirtualHistory(// is cheap (unmount = remove fiber, no parse).const dStart = useDeferredValue(start)const dEnd = useDeferredValue(end)- let effStart = start < dStart ? dStart : start- let effEnd = end > dEnd ? dEnd : end+ let effStart = nativeMode ? 0 : start < dStart ? dStart : start+ let effEnd = nativeMode ? n : end > dEnd ? dEnd : end// Inverted range (large jump with deferred value lagging) or sticky snap// (scrollToBottom needs the tail mounted NOW so maxScroll lands on content,@@ -467,7 +467,7 @@ export function useVirtualHistory(// wider than either bound alone. Trim the far edge by viewport position// (not pendingDelta direction — that flips mid-settle under concurrent// scheduling and yanks scrollTop).- if (effEnd - effStart > maxMounted && vp > 0) {+ if (!nativeMode && effEnd - effStart > maxMounted && vp > 0) {const mid = (offsets[effStart]! + offsets[effEnd]!) / 2if (top < mid) {diff --git a/ui-tui/src/lib/terminalModes.ts b/ui-tui/src/lib/terminalModes.tsindex 5b7f99bb3b1..e6f71473702 100644--- a/ui-tui/src/lib/terminalModes.ts+++ b/ui-tui/src/lib/terminalModes.ts@@ -21,7 +21,18 @@ export const TERMINAL_MODE_RESET ='\x1b[0m' + // attributes'\x1b[?25h' // cursor visible-export const NATIVE_TUI_EXIT_RESET = '\x1b[2J\x1b[H'+export function clearNativeTuiFrame(stream: ResettableStream = process.stdout): boolean {+ if (!stream.isTTY) {+ return false+ }++ try {+ stream.write('\x1b[2J\x1b[H')+ return true+ } catch {+ return false+ }+}type ResettableStream = Pick<NodeJS.WriteStream, 'isTTY' | 'write'> & {fd?: number