Skip to content

Commit f22b723

Browse files
nexxelnrekram1-node
authored andcommitted
fix(tui): stop older history from flashing when scrolling up
Pin the viewport when older history publishes or hidden rows mount, then compensate for their height in the content-resize handler before painting. Include group-boundary loads that a scroll-triggered request can join. Keep OpenTUI 0.8's native layout callbacks and disclosure anchors, with a separate resize listener and cleanup for history compensation. Record every frame of history reveal at wide and narrow terminal sizes. Fixes anomalyco#45976
1 parent 3960ebb commit f22b723

5 files changed

Lines changed: 145 additions & 31 deletions

File tree

‎packages/tui/src/routes/session/history.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ export function createHistoryPrepend(input: {
22
sessionID: () => string
33
more: (sessionID: string) => boolean
44
loadMore: (sessionID: string) => Promise<void>
5-
height: () => number
65
afterLayout: (continuation: () => void) => void
76
active: (sessionID: string) => boolean
87
scrollBy: (amount: number) => void
@@ -23,15 +22,14 @@ export function createHistoryPrepend(input: {
2322
if (!input.more(sessionID)) return false
2423
const current = { scrollBy, continuation }
2524
pending = current
26-
const before = input.height()
2725
void input.loadMore(sessionID).then(
2826
() =>
2927
input.afterLayout(() => {
3028
if (pending !== current) return
3129
const after = pending.after
3230
pending = undefined
3331
if (!input.active(sessionID)) return
34-
input.scrollBy(input.height() - before + current.scrollBy)
32+
input.scrollBy(current.scrollBy)
3533
current.continuation?.()
3634
after?.()
3735
}),
@@ -52,7 +50,7 @@ export function createHistoryPrepend(input: {
5250
},
5351
after(continuation: () => void) {
5452
if (!pending) return continuation()
55-
// A jump supersedes deferred scrolling, but must wait for anchor compensation.
53+
// A jump supersedes deferred scrolling, but must wait until the prepended page is laid out.
5654
pending.scrollBy = 0
5755
pending.after = continuation
5856
},

‎packages/tui/src/routes/session/index.tsx‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,8 @@ export function Session(props: {
290290
(id) => {
291291
if (id === sessionID) setRowsSynced(true)
292292
},
293+
// A scroll-triggered history load joins this boundary load instead of publishing its own page.
294+
() => pinAbove(),
293295
)
294296
const boundaries = createMemo(() => messageBoundaryIDs(rows, messages()))
295297
const anchors = createTimelineAnchors()
@@ -385,6 +387,7 @@ export function Session(props: {
385387
firstJump()?.()
386388
if (!scroll || scroll.isDestroyed) return
387389
scroll.verticalScrollBar.off("change", updateAwayFromBottom)
390+
scroll.content.off("resize", pinResize)
388391
saveScrollAnchor(true)
389392
})
390393
const [prompt, setPrompt] = createSignal<PromptRef>()
@@ -404,6 +407,26 @@ export function Session(props: {
404407
})
405408
}
406409

410+
// Older rows inserted above the reader grow the content from the top. Scrolling past them after
411+
// layout instead of during it draws one frame at the stale offset, flashing the oldest inserted row.
412+
let pinned: { height: number } | undefined
413+
const pinResize = () => {
414+
if (!pinned) return
415+
// Sticky scroll has already moved a reader who follows the bottom to the new bottom.
416+
if (!scroll.stickyScroll || scroll.scrollTop < scroll.scrollHeight - scroll.viewport.height)
417+
scroll.scrollBy(scroll.scrollHeight - pinned.height)
418+
pinned.height = scroll.scrollHeight
419+
}
420+
/** Treats content growth until layout settles as rows inserted above the reader. */
421+
const pinAbove = () => {
422+
if (!scroll || scroll.isDestroyed) return
423+
const pin = { height: scroll.scrollHeight }
424+
pinned = pin
425+
afterLayout(() => {
426+
if (pinned === pin) pinned = undefined
427+
})
428+
}
429+
407430
// Tail-first transcript mounting: only the newest rows mount when the session opens. Older rows
408431
// mount on demand near the top, keeping inactive tabs cheap to tear down. While the reader stays
409432
// at the bottom the hidden span follows appends; leaving the bottom pins it to preserve the viewport.
@@ -426,16 +449,18 @@ export function Session(props: {
426449
sessionID: () => route.sessionID,
427450
more: (id) => data.session.message.more(id),
428451
loadMore: async (id) => {
429-
await data.session.message.loadMore(id)
452+
const beforePublish = () => {
453+
if (route.sessionID === id) pinAbove()
454+
}
455+
await data.session.message.loadMore(id, { beforePublish })
430456
await completeGroupBoundary({
431457
rows,
432458
messages: () => data.session.message.list(id).length,
433459
more: () => data.session.message.more(id),
434-
loadMore: () => data.session.message.loadMore(id),
460+
loadMore: () => data.session.message.loadMore(id, { beforePublish }),
435461
active: () => route.sessionID === id,
436462
})
437463
},
438-
height: () => scroll.scrollHeight,
439464
afterLayout,
440465
active: (id) => route.sessionID === id && Boolean(scroll && !scroll.isDestroyed),
441466
scrollBy: (amount) => {
@@ -449,11 +474,11 @@ export function Session(props: {
449474
if (revealingOlderRows || !scroll || scroll.isDestroyed || scroll.scrollTop > scroll.viewport.height) return false
450475
if (current === 0) return prependHistory(scrollBy)
451476
revealingOlderRows = true
452-
const before = scroll.scrollHeight
453477
scroll.stickyScroll = false
478+
pinAbove()
454479
setHiddenRows(rowsBefore(weights(), current, TRANSCRIPT_BACKFILL_CHUNK))
455480
afterLayout(() => {
456-
scroll.scrollBy(scroll.scrollHeight - before + scrollBy)
481+
scroll.scrollBy(scrollBy)
457482
scroll.stickyScroll = !navigationMessage()
458483
revealingOlderRows = false
459484
})
@@ -1513,6 +1538,7 @@ export function Session(props: {
15131538
scroll = r
15141539
props.scrollRef?.(r)
15151540
scroll.verticalScrollBar.on("change", updateAwayFromBottom)
1541+
scroll.content.on("resize", pinResize)
15161542
}}
15171543
viewportOptions={{
15181544
paddingRight: showScrollbar() ? 1 : 0,

‎packages/tui/src/routes/session/rows.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,11 @@ export async function completeGroupBoundary(input: {
4444
}
4545
}
4646

47-
export function createSessionRows(sessionID: Accessor<string>, onSynced?: (sessionID: string) => void) {
47+
export function createSessionRows(
48+
sessionID: Accessor<string>,
49+
onSynced?: (sessionID: string) => void,
50+
beforePublish?: () => void,
51+
) {
4852
const data = useData()
4953
const client = useClient()
5054
const config = useConfig()
@@ -131,7 +135,7 @@ export function createSessionRows(sessionID: Accessor<string>, onSynced?: (sessi
131135
rows,
132136
messages: () => data.session.message.list(id).length,
133137
more: () => data.session.message.more(id),
134-
loadMore: () => data.session.message.loadMore(id),
138+
loadMore: () => data.session.message.loadMore(id, { beforePublish }),
135139
active: () => sessionID() === id,
136140
}).catch(() => undefined)
137141
if (sessionID() === id) onSynced?.(id)

‎packages/tui/test/cli/tui/session-history.test.ts‎

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
11
import { expect, test } from "bun:test"
22
import { createHistoryPrepend } from "../../../src/routes/session/history"
33

4-
test("loads older history and preserves the visible scroll anchor", async () => {
5-
let height = 100
4+
test("loads older history and applies the deferred scroll after layout", async () => {
65
let resolveLoad: (() => void) | undefined
76
const scrolled: number[] = []
87
const prepend = createHistoryPrepend({
98
sessionID: () => "session-1",
109
more: () => true,
1110
loadMore: () =>
1211
new Promise<void>((resolve) => {
13-
resolveLoad = () => {
14-
height = 160
15-
resolve()
16-
}
12+
resolveLoad = resolve
1713
}),
18-
height: () => height,
1914
afterLayout: (continuation) => continuation(),
2015
active: (sessionID) => sessionID === "session-1",
2116
scrollBy: (amount) => scrolled.push(amount),
@@ -27,7 +22,7 @@ test("loads older history and preserves the visible scroll anchor", async () =>
2722
await Promise.resolve()
2823
await Promise.resolve()
2924

30-
expect(scrolled).toEqual([56])
25+
expect(scrolled).toEqual([-4])
3126
})
3227

3328
test("releases the history load after a failed request", async () => {
@@ -39,7 +34,6 @@ test("releases the history load after a failed request", async () => {
3934
attempts++
4035
return Promise.reject(new Error("offline"))
4136
},
42-
height: () => 100,
4337
afterLayout: (continuation) => continuation(),
4438
active: () => true,
4539
scrollBy: () => undefined,
@@ -63,7 +57,6 @@ test("does not move a different session after history loads", async () => {
6357
new Promise<void>((resolve) => {
6458
resolveLoad = resolve
6559
}),
66-
height: () => 160,
6760
afterLayout: (continuation) => continuation(),
6861
active: (sessionID) => current === sessionID,
6962
scrollBy: (amount) => scrolled.push(amount),
@@ -86,32 +79,29 @@ test("continues navigation after the prepended page is laid out", async () => {
8679
loadMore: async () => {
8780
events.push("loaded")
8881
},
89-
height: () => 100,
9082
afterLayout: (continuation) => {
9183
events.push("layout")
9284
continuation()
9385
},
9486
active: () => true,
95-
scrollBy: () => events.push("anchored"),
87+
scrollBy: () => events.push("scrolled"),
9688
})
9789

9890
expect(prepend(0, () => events.push("continued"))).toBe(true)
9991
await Promise.resolve()
10092
await Promise.resolve()
10193

102-
expect(events).toEqual(["loaded", "layout", "anchored", "continued"])
94+
expect(events).toEqual(["loaded", "layout", "scrolled", "continued"])
10395
})
10496

10597
test.each(["success", "failure", "cancel", "takeover"])("settles superseded prepend navigation (%s)", async (mode) => {
10698
const load = Promise.withResolvers<void>()
10799
const layout: (() => void)[] = []
108100
const events: (number | string)[] = []
109-
let height = 100
110101
const prepend = createHistoryPrepend({
111102
sessionID: () => "session-1",
112103
more: () => true,
113104
loadMore: () => load.promise,
114-
height: () => height,
115105
afterLayout: (continuation) => layout.push(continuation),
116106
active: () => true,
117107
scrollBy: (amount) => events.push(amount),
@@ -122,15 +112,12 @@ test.each(["success", "failure", "cancel", "takeover"])("settles superseded prep
122112
if (mode === "cancel" || mode === "takeover") prepend.cancel()
123113
if (mode === "takeover") expect(prepend(-8)).toBe(true)
124114
if (mode === "failure") load.reject(new Error("offline"))
125-
if (mode !== "failure") {
126-
height = 160
127-
load.resolve()
128-
}
115+
if (mode !== "failure") load.resolve()
129116
await Promise.resolve()
130117
expect(events).toEqual(mode === "failure" ? ["jump"] : [])
131118
layout.shift()?.()
132119
expect(events).toEqual(
133-
mode === "failure" ? ["jump"] : mode === "success" ? [60, "jump"] : mode === "takeover" ? [52] : [60],
120+
mode === "failure" ? ["jump"] : mode === "success" ? [0, "jump"] : mode === "takeover" ? [-8] : [0],
134121
)
135122
prepend.after(() => events.push("idle"))
136123
expect(events.at(-1)).toBe("idle")
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { expect, test } from "bun:test"
2+
import { createTestRenderer, TestRecorder } from "@opentui/core/testing"
3+
import { Effect, FileSystem } from "effect"
4+
import { Global } from "@opencode/util/global"
5+
import type { SessionMessageInfo } from "@opencode/client"
6+
import { createEventStream, createFetch, directory, json } from "./fixture/tui-client"
7+
import { tmpdir } from "./fixture/fixture"
8+
import { waitForHighlightedFrame } from "./fixture/frame"
9+
10+
// The whole-app fixture needs the package's 30-second budget for its cold app import.
11+
test.each([100, 48])(
12+
"scrolling up into older history never flashes the inserted rows at width %s",
13+
async (width) => {
14+
await using state = await tmpdir()
15+
const setup = await createTestRenderer({ width, height: 30, kittyKeyboard: true })
16+
await setup.renderer.setupTerminal()
17+
setup.renderer.start()
18+
const session = {
19+
id: "ses_history_reveal",
20+
title: "History reveal",
21+
projectID: "proj_test",
22+
location: { directory },
23+
cost: 0,
24+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
25+
time: { created: 0, updated: 0 },
26+
}
27+
const model = { providerID: "fixture", id: "fixture" }
28+
const messages: SessionMessageInfo[] = Array.from({ length: 60 }, (_, turn) => [
29+
{ type: "user" as const, id: `user-${turn}`, text: `Turn ${turn} prompt`, time: { created: turn * 10 } },
30+
{
31+
type: "assistant" as const,
32+
id: `answer-${turn}`,
33+
agent: "build",
34+
model,
35+
finish: "stop" as const,
36+
time: { created: turn * 10 + 1, completed: turn * 10 + 2 },
37+
content: [{ type: "text" as const, text: `Turn ${turn} answer` }],
38+
},
39+
]).flat()
40+
// The first page (turns 40-59) overfills the mounted tail, so scrolling up first mounts its hidden
41+
// rows, then loads turns 30-39 from the server. Both insert rows above the reader.
42+
const calls = createFetch((url) => {
43+
if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
44+
if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
45+
if (url.pathname === `/api/session/${session.id}/message`) {
46+
const cursor = url.searchParams.get("cursor")
47+
const end = Number(cursor ?? messages.length)
48+
const start = Math.max(0, end - (cursor ? Number(url.searchParams.get("limit")) : 40))
49+
return json({ data: messages.slice(start, end).toReversed(), cursor: start ? { next: String(start) } : {} })
50+
}
51+
if (
52+
url.pathname === `/api/session/${session.id}/inbox` ||
53+
url.pathname === `/api/session/${session.id}/permission`
54+
)
55+
return json({ data: [] })
56+
}, createEventStream())
57+
const server = Bun.serve({ port: 0, idleTimeout: 0, fetch: (request) => calls.fetch(request) })
58+
const { run } = await import("../src/app")
59+
const task = Effect.runPromise(
60+
run({
61+
app: { name: "test", version: "test", channel: "test" },
62+
server: { endpoint: { url: server.url.toString() } },
63+
config: { get: async () => ({ animations: false, tabs: { enabled: false } }), update: async () => ({}) },
64+
packages: { prepare: async () => ({ directory: "" }) },
65+
args: { sessionID: session.id },
66+
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
67+
log: () => {},
68+
}).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
69+
)
70+
try {
71+
await waitForHighlightedFrame(setup, (frame) => frame.includes("Turn 59 answer"))
72+
await setup.waitForVisualIdle({ quietFrames: 3 })
73+
const recorder = new TestRecorder(setup.renderer)
74+
recorder.rec()
75+
for (let step = 0; step < 200 && !setup.captureCharFrame().includes("Turn 39 answer"); step++) {
76+
await setup.mockMouse.scroll(30, 10, "up")
77+
await setup.renderOnce()
78+
}
79+
await setup.waitForVisualIdle({ quietFrames: 3 })
80+
recorder.stop()
81+
82+
// A wheel tick moves less than one turn, so the earliest turn on screen steps down by at most one
83+
// per frame. A frame drawn before the inserted rows are scrolled past shows their first turn, and
84+
// the next frame jumps back to the reader.
85+
const turns = recorder.recordedFrames.map((frame) =>
86+
Math.min(...[...frame.frame.matchAll(/Turn (\d+) (?:prompt|answer)/g)].map((match) => Number(match[1]))),
87+
)
88+
expect(turns.at(-1)).toBeLessThanOrEqual(39)
89+
expect(
90+
turns.filter((turn, index) => index > 0 && (turn > turns[index - 1] || turn < turns[index - 1] - 1)),
91+
).toEqual([])
92+
} finally {
93+
setup.renderer.destroy()
94+
await task
95+
await server.stop()
96+
}
97+
},
98+
30000,
99+
)

0 commit comments

Comments
 (0)