Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion src/pepper_cli/tui/thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
from textual.app import ComposeResult
from textual.widget import Widget

#: Refreshes an older page's scroll-past waits through for the new rows to be measured.
_KEEP_PLACE_TRIES = 5


class ThreadScroll(VerticalScroll):
"""The scrolling body. ↑/↓ select a message (for ``r``) instead of scrolling a line;
Expand Down Expand Up @@ -102,6 +105,10 @@ def __init__(self) -> None:
super().__init__(id="thread")
self._unseen = 0
self._was_pinned = True
#: Bumped when a different conversation is shown, so a keep-place retry left over
#: from the previous one stands down. Not by every ``show``: a live refresh of the same
#: conversation must not cancel the scroll past an older page it has not reached yet.
self._conversation = 0

def compose(self) -> ComposeResult:
with ThreadScroll(id="thread-scroll"):
Expand Down Expand Up @@ -139,11 +146,24 @@ def show(
stick = reset or (self.pinned and not prepended)
scroller = self.scroller
old_height, old_y = scroller.virtual_size.height, scroller.scroll_y
if reset:
self._conversation += 1
conversation = self._conversation
self.query_one("#thread-body", Static).update(body)
if prepended and not reset:

def keep_place() -> None:
def keep_place(tries: int = _KEEP_PLACE_TRIES) -> None:
if self._conversation != conversation or scroller.scroll_y != old_y:
# Another conversation was opened, or the reader scrolled, while this
# waited: either one owns the position now.
return
grown = scroller.virtual_size.height - old_height
if grown <= 0 and tries > 1:
# The refresh this waited for can land before the layout that measures
# the new rows (a loaded loop); scrolling by 0 would leave the reader at
# the top of the longer thread. Wait for the next one.
scroller.call_after_refresh(keep_place, tries - 1)
return
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
scroller.scroll_to(y=old_y + max(grown, 0), animate=False)

scroller.call_after_refresh(keep_place)
Comment on lines +155 to 169

@vycari-review vycari-review Bot Nov 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 · VR-9a84a806 · Older-page keep-place still lands at the top when layout lags past the retry budget

On a very slow machine, if the older page still isn't laid out after five screen refreshes, the view still jumps to the top of the thread. The fix waits for a set number of refreshes rather than for the new rows' height.

Reply Fixed in <sha> or Disputed: with a reason.

Details for agents: evidence, failure scenario, verification, proving test

keep_place waits a fixed count of call_after_refresh callbacks (_KEEP_PLACE_TRIES = 5) for virtual_size.height to grow, then scrolls by max(grown, 0). The wait is counted in refresh callbacks, not in measured layout. If the new rows are still unmeasured after the 5th callback, grown is 0 and the scroll is to old_y, i.e. the top of the longer thread, which is the exact bug this PR claims to fix. The patch narrows the window; it does not make the scroll depend on the measurement.

Evidence: Read thread.py:142-161. Retry is bounded by tries > 1 (line 150) and the fallback is scroll_to(old_y + max(grown, 0)) (line 156). Callers: app.py:936-942 and app.py:1829 (prepended=bool(added)). No wall-clock or layout-based wait exists. Textual sources are not in the checkout, so I could not confirm how many layout passes a call_after_refresh cycle actually spans; the claim rests only on the bounded count in this file.

Failure scenario

User is at the top of a thread and scrolls up, triggering an older page (app.py:1829 passes prepended=True). On a heavily loaded machine the Static body's new height is not laid out within the 5 scheduled refreshes. keep_place runs on the 5th callback with grown == 0, scrolls to old_y, and the reader is left at the top of the longer thread with the same lines no longer in view.

How this was verified (read-only-reasoning)

I read thread.py:142-161. The retry is bounded at 5 and the fallback is scroll_to(old_y + max(grown, 0)). I did not open the app.py callers; I took them from the candidate's evidence. Textual's layout timing is not in the checkout, so I could not check how many layouts a refresh spans. Reachable from: ThreadView.show(prepended=True), called from the app older-page load path.

Proving test

Unit test on ThreadView: mount, show a short thread, then show a prepended longer body while patching virtual_size so the height only grows after the 6th call_after_refresh callback. Assert scroll_y equals the old offset plus the added height. On head this fails because keep_place gives up after 5 tries and scrolls by 0.

lens concurrency-time · symbol ThreadView.show

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declined: an unbounded wait has no end in the case where the prepended rows really add no height, and a time-based wait would read the wall clock in a path the tests drive by refresh. Five refreshes is several times what the merge-queue repro needed (it failed with zero retries and passed with one). If a reader still lands at the top, the view is no worse than before this PR, and the new scroll-guard means a reader who moves isn't overridden.


Generated by Claude Code

Comment thread
vycari-review[bot] marked this conversation as resolved.
Resolved
Expand Down
116 changes: 116 additions & 0 deletions tests/test_tui_parity.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@

from __future__ import annotations

import inspect
import threading
from datetime import UTC, datetime
from typing import TYPE_CHECKING

import pytest
from textual.geometry import Size
from textual.widget import Widget

from pepper_cli.tui import app as tui_app
from pepper_cli.tui import rows, state
Expand Down Expand Up @@ -329,6 +332,119 @@ async def test_older_rows_keep_the_view_where_it_was() -> None:
await until(pilot, lambda: scroller.scroll_y > 0) # not left at the top


def _older_thread_server() -> ts.FakeServer:
server = ts.standard_server()
_a1(
server,
*(
ts.message(f"m{i:02d}", f"2026-09-16T10:{i:02d}:00+00:00", f"body {i}")
for i in range(14)
),
)
return server


async def test_keep_place_retries_until_the_older_rows_are_measured(monkeypatch) -> None:
"""The retry branch, driven by hand: the first callback runs before the layout that
measures the older rows, waits, and the next one scrolls past them. Out of tries, it
stops waiting."""
app = tui_app.PepperApp(_older_thread_server().client())
async with app.run_test(size=(100, 14)) as pilot:
await _open_a1(app, pilot, "body 13")
thread = app.thread
scroller = thread.scroller
scroller.scroll_y = 0
await pilot.pause()
held: list = []
scrolled: list[float] = []

def hold(cb, *_a, **_k) -> None:
# Only keep-place's own callbacks: the app may schedule others meanwhile.
if getattr(cb, "__name__", "") == "keep_place":
held.append(cb)

monkeypatch.setattr(scroller, "call_after_refresh", hold)
monkeypatch.setattr(scroller, "scroll_to", lambda *, y, **_: scrolled.append(y))
# Hold the measured height where it was, as a loaded loop does until its next layout.
real = inspect.getattr_static(Widget, "virtual_size")
old = scroller.virtual_size
measured = [old]
monkeypatch.setattr(
type(scroller),
"virtual_size",
property(lambda _w: measured[0], lambda w, v: real.__set__(w, v)),
raising=False,
)
# Read here, not assumed 0: the app may itself have loaded an older page by now.
at = scroller.scroll_y
thread.show("\n".join(f"older {i}" for i in range(40)), prepended=True)
keep_place = held.pop()
keep_place() # not measured yet: grown is 0
assert scrolled == [] # it did not scroll by 0
retry = held.pop() # it waits for the next refresh instead
measured[0] = Size(old.width, old.height + 12) # that layout measures the rows
retry()
assert scrolled == [at + 12] # scrolled past exactly the rows added above
measured[0] = old
keep_place(1) # out of tries with nothing measured: scrolls by 0, waits no longer
assert scrolled == [at + 12, at]
assert held == []


async def test_a_reset_stands_down_a_pending_keep_place(monkeypatch) -> None:
"""A keep-place retry from an older page must not move a conversation shown after it."""
app = tui_app.PepperApp(_older_thread_server().client())
async with app.run_test(size=(100, 14)) as pilot:
await _open_a1(app, pilot, "body 13")
thread = app.thread
scroller = thread.scroller
scroller.scroll_y = 0
await pilot.pause()
held: list = []
monkeypatch.setattr(scroller, "call_after_refresh", lambda cb, *a, **k: held.append(cb))
# Read here, not assumed 0: the app may itself have loaded an older page by now.
at = scroller.scroll_y
longer = "\n".join(f"older {i}" for i in range(40)) + "\n" + body_text(app)
thread.show(longer, prepended=True)
stale = next(cb for cb in reversed(held) if getattr(cb, "__name__", "") == "keep_place")
monkeypatch.undo()
thread.show("\n".join(f"other {i}" for i in range(120)), reset=True)
await until(pilot, lambda: scroller.scroll_y == scroller.max_scroll_y > 0)
# Back where the stale one started, so only its conversation tells it apart; with no
# await in between, nothing else gets to move the view.
scroller.scroll_y = at
scrolled: list[float] = []
monkeypatch.setattr(scroller, "scroll_to", lambda *, y, **_: scrolled.append(y))
stale(1) # its last try, where it would otherwise scroll whatever it measures
assert scrolled == []


async def test_a_scroll_made_while_keep_place_waits_is_not_undone() -> None:
"""VR-6b3a8f9f: the scroll past older rows waits a refresh or more; a reader who moves
in that window keeps the place they moved to."""
server = ts.standard_server()
_a1(
server,
*(
ts.message(f"m{i:02d}", f"2026-09-16T10:{i:02d}:00+00:00", f"body {i}")
for i in range(14)
),
)
app = tui_app.PepperApp(server.client())
async with app.run_test(size=(100, 14)) as pilot:
await _open_a1(app, pilot, "body 13")
thread = app.thread
scroller = thread.scroller
scroller.scroll_to(y=0, animate=False)
await pilot.pause()
longer = "\n".join(f"older {i}" for i in range(40)) + "\n" + body_text(app)
thread.show(longer, prepended=True)
scroller.scroll_y = 3 # the reader moves before keep_place runs
for _ in range(8):
await pilot.pause()
assert scroller.scroll_y == 3


async def test_o_opens_the_first_link_and_never_a_non_web_url() -> None:
server = ts.standard_server()
opened: list[str] = []
Expand Down
Loading