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
4 changes: 4 additions & 0 deletions src/toad/client/history_pager.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,10 @@ def finish_source_work(self, operation: WorkingTranscript) -> None:
self.publish_core(TranscriptSourceWorkFinished())
if all(history.state.accepts_source_work for history in self.window.histories):
self.window.reader_position.source_settled(self.window)
# Work handed over while this held the source; what arrives while it runs is owed
# to that operation in turn, so a burst's last revision is always read.
for work in tuple(operation.owed.values()):
self.schedule_source_work(work)

def resume_source(self) -> None:
self._source_state = self._source_state.resume()
Expand Down
11 changes: 11 additions & 0 deletions src/toad/client/history_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,17 @@ def __init__(self, source: TranscriptState, owner):
self.reader_revision = owner.window.scroll_revision
# The screen asked for rows beyond an edge while this work held the source.
self.edges_wait = False
# Work handed over while this held the source, run once it ends (`owed`).
self.owed: dict[object, Callable[[], Awaitable[object]]] = {}

def schedule_work(self, owner, work) -> SourceWork:
"""Work arriving while this holds the source runs once it ends, once per kind: a
refresh reads everything new, so two owed refreshes are one. Returned as deferred, it
was dropped by callers that never retried, and a burst's last messages stayed unread
until something else changed (a phone-speed burst left 6 of 20 undrawn)."""
key = (work.func, work.args) if isinstance(work, partial) else work
self.owed[key] = work
return DEFERRED_WORK

def rows_published(self, owner) -> None:
self.source.rows_published(owner)
Expand Down
5 changes: 4 additions & 1 deletion src/toad/qt/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -1319,6 +1319,10 @@ def scrolled(self, value: int) -> None:
fires `respond_to_scroll` once on the transition out of Dragging. The
at_end/follows_tail transitions here stay — they're cheap state flips
and consumers (jump bar + anchor) need to see them during drag."""
# Every offset pins, the window's own as well as the reader's: a glide down into a tall
# arrival moves the top row into it, and returning before this left the arrival's header
# unpinned until the reader scrolled (Tristan, Android, 2026-11-18).
self.repin_header()
if self._restoring:
return
if self.at_end and not self.follows_tail:
Expand All @@ -1327,7 +1331,6 @@ def scrolled(self, value: int) -> None:
self.release_anchor()
elif not self.follows_tail:
self.reader_position = RowPosition(value)
self.repin_header()
if self._scroller_dragging:
self._drag_skipped_ticks += 1
return
Expand Down
9 changes: 5 additions & 4 deletions src/toad/qt/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,17 @@ def __init__(self, entry: MenuEntry, menu: QtMenu, chosen: Callable[[MenuEntry],
self.label = ElidedLine(menu.row_text(entry))
self.label.setParent(self._button)
text.addWidget(self.label)
lines = 1
if entry.description and not menu.input_modality.describes_inline():
description = ElidedLine(entry.description)
description.setParent(self._button)
description.setEnabled(False) # the theme's muted text, as a secondary line
text.addWidget(description)
lines = 2
inner.addLayout(text, 1)
margins = inner.contentsMargins()
height = lines * self.fontMetrics().lineSpacing() + margins.top() + margins.bottom()
# The row is as tall as its lines need, as the layout measures them (each line's own
# minimum, margins included), never less than a touch target. An explicit minimum
# overrides the layout's own: one summed from line spacing gave each line 12 px of a
# 17 px font and cut every descender on the phone (`qt_drive menu_text`).
height = inner.totalMinimumSize().height()
self._button.setMinimumHeight(max(44, menu.input_modality.row_height, height))

def _fire(self) -> None:
Expand Down
88 changes: 87 additions & 1 deletion tools/qt_drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,35 @@ async def run(self) -> None:
assert not facts["shown"], "the message's own header is on the top row, yet a copy is pinned"


class TallArrivalScenario(StickyScenario):
summary = ("open TARGET (#scratch) following its end; SENDER (scratch-live-pipeline) posts one "
"message taller than the window; once the window glides down into it, its header "
"must be pinned over the top row without the reader scrolling")

async def run(self) -> None:
self.app.resize(int(os.environ.get("WIDTH", 412)), 915)
target = os.environ.get("TARGET", "#scratch")
sender = os.environ.get("SENDER", "scratch-live-pipeline")
await self.open_named(target)
window = self.page.messages
await until(lambda: window.follows_tail, "following the end")
stamp = time.strftime("%H:%M:%S")
body = "\n".join(f"tall arrival {stamp} line {line}" for line in range(120))
process = await asyncio.create_subprocess_exec(
"agent-comms", "send", "--from", sender, "--to", target, "--type", "info", "--body", body,
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE)
_, error = await process.communicate()
assert process.returncode == 0, error.decode(errors="replace")[-300:]
await until(lambda: any(f"tall arrival {stamp} line 119" in fragment.clipboard_text
for fragment in window.model_rows.fragments), "the tall message's row")
await until(lambda: window.glide is None and window.follows_tail, "the glide landed on the end")
await asyncio.sleep(0.5)
facts = self.pinned()
self.report("1-tall-arrived", **facts)
assert facts["shown"], "a tall arrival fills the window, yet its header is not pinned"
assert sender in facts["text"], f"pinned {facts['text']!r} is not {sender}'s header"


class EscapeScenario(Scenario):
summary = ("in the scratch-live-pipeline thread, then #comms: scroll off the tail, press Escape in "
"the composer, and report the view back on its latest row (BackToBottomAction, bound on "
Expand Down Expand Up @@ -913,6 +942,35 @@ async def run(self) -> None:
self.report("3-notice", notices=app.float_layer.shown_notices(), shown=app.float_layer.isVisible())


class MenuTextScenario(Scenario):
summary = ("open the menu at WIDTH (412) and fail when any of its lines is drawn in less height "
"than its font's full height: the descenders of a description line were cut on the phone")

async def run(self) -> None:
from pyqt_reactive.widgets.fitted_text import FittedText
self.app.resize(int(os.environ.get("WIDTH", 412)), 915)
await self.listed()
self.app.menu_panel.input_modality = TouchInput # the phone's: each description is a second line
self.app.menu.click()
await asyncio.sleep(0.5)
lines = [line for row in self.app.menu_panel.findChildren(QtMenuRow)
for line in row.findChildren(FittedText)]
clipped = [(line.text()[:30], line.contentsRect().height(), line.fontMetrics().height())
for line in lines if line.contentsRect().height() < line.fontMetrics().height()]
if lines:
line = lines[0]
button = line.parentWidget()
print("line geometry:", dict(height=line.height(), contents=line.contentsRect().height(),
margins=(line.contentsMargins().top(), line.contentsMargins().bottom()),
minimum=line.minimumSizeHint().height(), button=button.height(),
button_minimum=button.minimumHeight(), panel_sheet=self.app.menu_panel.styleSheet()[:300],
app_sheet_label=[rule[:120] for rule in QApplication.instance().styleSheet().split("}") if "QLabel" in rule][:4]),
flush=True)
self.report("1-menu", lines=len(lines), clipped=clipped[:6])
assert lines, "the menu shows no lines"
assert not clipped, f"{len(clipped)} menu lines drawn shorter than their font: {clipped[:3]}"


class FeedbackScenario(Scenario):
summary = ("the reader's feedback at a Pixel 8a's width: the wait a slow thread open shows in place, "
"#comms' first page loading, an operation's wait floating over the page, a notice that "
Expand Down Expand Up @@ -2013,9 +2071,22 @@ async def run(self) -> None:
started = time.monotonic()
original = HistoryRows.show

first_shown: dict[str, float] = {} # a row's full text, when it first showed
# When Core's revisions reach this app: the pace a burst can show at, at best.
from toad.client.connection import CoordinationAccess
revisions: list[float] = []
observed = CoordinationAccess.revision_observed

def revision_arrived(access, result, observing):
revisions.append(time.monotonic() - started)
return observed(access, result, observing)
CoordinationAccess.revision_observed = revision_arrived

def recorded(model, fragments):
before = {self.label(fragment) for fragment in model.fragments}
original(model, fragments)
for fragment in model.fragments:
first_shown.setdefault(fragment.clipboard_text, time.monotonic() - started)
after = {self.label(fragment) for fragment in model.fragments}
if model is not view.messages.model_rows:
print(f"show on another model: {type(model).__name__} rows={len(model.fragments)}", flush=True)
Expand Down Expand Up @@ -2066,6 +2137,8 @@ def sample() -> None:
else (target, "user"))
sender = os.environ.get("SENDER", sender)
refused: list[str] = []
posted: dict[int, float] = {} # when each post's send returned, s after start
burst = int(os.environ.get("BURST", "3")) # how many the sender posts at once

async def post(index: int) -> None:
# Under a CPU-throttled drive, the sender runs in a scope of its own (SENDER_SCOPE=1):
Expand All @@ -2076,6 +2149,7 @@ async def post(index: int) -> None:
"--body", f"arrival reply {index} {stamp}",
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE)
_, error = await process.communicate()
posted[index] = time.monotonic() - started
if process.returncode: # A refused post is a failed walk, never a quiet one.
refused.append(error.decode(errors="replace").strip()[-200:])
# How long each arrival-handling call holds the loop: the pager's publish into the rows,
Expand Down Expand Up @@ -2105,7 +2179,7 @@ def wrapper(*arguments, **options):
await asyncio.sleep(0.5)
top = window.indexAt(window.viewport().rect().topLeft())
reading = (self.label(top.data(HistoryRows.FRAGMENT)), window.visualRect(top).top())
posts = [asyncio.ensure_future(post(index)) for index in range(3)]
posts = [asyncio.ensure_future(post(index)) for index in range(burst)]
for index in range(0 if scrolled_up else 3):
composer.editor.setPlainText(f"arrival send {index} {stamp}")
composer.submit()
Expand All @@ -2129,6 +2203,18 @@ def wrapper(*arguments, **options):
by_text: dict[str, list[str]] = {}
for label, marks in appeared.items():
by_text.setdefault(label.rsplit(" #", 1)[0], []).extend(f"{mark}{label[-5:]}" for mark in marks)
# Each posted message's wait: from its send returning to its row first showing.
shown_at = {index: min((at for text, at in first_shown.items()
if f"arrival reply {index} {stamp}" in text), default=None)
for index in posted}
print("posted at (s):", sorted(round(at, 2) for at in posted.values()), flush=True)
print("revisions arrived (s):", [round(at, 2) for at in revisions if at > min(posted.values(), default=0) - 1], flush=True)
CoordinationAccess.revision_observed = observed
print("shown at (s):", sorted(round(at, 2) for at in shown_at.values() if at is not None), flush=True)
waits = sorted(round(shown_at[index] - posted[index], 2) for index in posted if shown_at[index] is not None)
print(f"burst of {burst}: {len(waits)} shown; wait from send to row (s): "
f"median {waits[len(waits) // 2] if waits else None}, max {waits[-1] if waits else None}; "
f"never shown {[index for index in posted if shown_at[index] is None]}", flush=True)
# A message that leaves the rows after it showed, or shows under two keys, flickers.
flicker = {text: sorted(marks, key=lambda mark: float(mark[1:].split("#")[0]))
for text, marks in by_text.items() if stamp in text and len(marks) > 1}
Expand Down
Loading