Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(chat): keep older-page paging anchored to the reader's position

cyhba610f80ea06
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index d329c09fa..c34c63611 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -67,6 +67,7 @@ import {
insertMessageOrdered,
reconcileWorkbenchClaimedDeliveries,
} from '../../lib/transcriptOrder';
+import { pickScrollAnchor } from '../../lib/transcriptScrollAnchor';
import { AgentRoutePicker } from './AgentRoutePicker';
import {
archiveSessionShortcutLabel,
@@ -3473,6 +3474,10 @@ const Transcript: React.FC<TranscriptProps> = ({
const anchorRef = useRef<{ el: HTMLElement; top: number } | null>(null);
const lastSessionRef = useRef<string | null>(null);
const [showJump, setShowJump] = useState(false);
+ // Whether the transcript is actually scrollable. Measured by the same
+ // ResizeObserver that owns the anchor restore, so it needs no observer of its
+ // own and is fresh in the commit that changes the content's height.
+ const [historyOverflows, setHistoryOverflows] = useState(false);
const loadOlderRef = useRef(onLoadOlder);
const reloadLatestRef = useRef(onReloadLatest);
// Load ONE older page per scroll gesture, not a cascade. The top threshold can
@@ -3545,12 +3550,19 @@ const Transcript: React.FC<TranscriptProps> = ({
/>
) : null;
const empty = messages.length === 0 && !working;
+ // The end-of-history line answers "why did paging stop?" — a question only a
+ // reader who actually scrolled can have asked. A chat that fits the viewport
+ // never paged, so there the same line is noise rather than an answer.
+ const atHistoryStart = !hasOlder && historyOverflows;
// Capture the topmost (partly) visible row as the restore anchor. Viewport-
// relative rects keep this correct regardless of the scroll container's padding;
// it breaks at the first visible row, so the common case (reading near the top of
// the loaded window) is a couple of reads. Called from the scroll handler while
// the user is reading history, so the anchor is always fresh when a resize lands.
+ // ``pickScrollAnchor`` owns which elements qualify — transient chrome such as the
+ // older-page spinner is skipped, because an anchor that disappears in the very
+ // commit it has to survive restores nothing (see the module's own note).
const captureAnchor = useCallback(() => {
// A programmatic jump is in flight — don't record an anchor mid-jump (the
// restore would later snap back to it and undo the jump).
@@ -3558,15 +3570,10 @@ const Transcript: React.FC<TranscriptProps> = ({
const el = scrollRef.current;
const content = contentRef.current;
if (!el || !content) return;
- const containerTop = el.getBoundingClientRect().top;
- for (const child of Array.from(content.children) as HTMLElement[]) {
- const rect = child.getBoundingClientRect();
- if (rect.bottom > containerTop) {
- anchorRef.current = { el: child, top: rect.top - containerTop };
- return;
- }
- }
- anchorRef.current = null;
+ anchorRef.current = pickScrollAnchor(
+ Array.from(content.children) as HTMLElement[],
+ el.getBoundingClientRect().top,
+ );
}, []);
// Jump to the exact bottom and resume following. Instant, not smooth: a smooth
@@ -3730,6 +3737,11 @@ const Transcript: React.FC<TranscriptProps> = ({
const content = contentRef.current;
if (!el || !content) return;
const ro = new ResizeObserver(() => {
+ // Recomputed on every content resize, ahead of the anchor branches below so
+ // no early return can leave it stale. Monotone, so it cannot oscillate: the
+ // end-of-history line it gates is only ever ADDED to a transcript that
+ // already overflows, and removing it can only shrink the content further.
+ setHistoryOverflows(el.scrollHeight > el.clientHeight + 1);
// A programmatic jump owns scrollTop right now — neither pin-to-bottom nor
// anchor-restore should move it, or it would fight the jump.
if (suppressAnchorRef.current) return;
@@ -3791,11 +3803,28 @@ const Transcript: React.FC<TranscriptProps> = ({
<div ref={scrollRef} onScroll={handleScroll} className="min-h-0 flex-1 overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8">
<div ref={contentRef} className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
{forkSourceBanner}
- {loadingOlder && (
- <div className="flex h-8 items-center justify-center text-muted">
+ {/* One slot at the head of the history, so the spinner resolves into the
+ end-of-history line in place instead of the top twitching. Both are
+ transient by construction — they mount and unmount around the very
+ commits that prepend a page — so neither may become the scroll-anchor
+ (see pickScrollAnchor). */}
+ {loadingOlder ? (
+ <div
+ data-scroll-anchor="skip"
+ role="status"
+ aria-label={t('chat.loadingOlder')}
+ className="flex h-8 items-center justify-center text-muted"
+ >
<Loader2 className="size-4 animate-spin" />
</div>
- )}
+ ) : atHistoryStart ? (
+ <div
+ data-scroll-anchor="skip"
+ className="flex h-8 items-center justify-center text-[12px] text-muted"
+ >
+ {t('chat.noEarlierMessages')}
+ </div>
+ ) : null}
{/* Degenerate null-anchor groups render at the TOP (never the tail). */}
{activity?.enabled && activity.topGroups.map((group) => renderActivityChip(group))}
{messages.map((message) => {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 91eee1e90..2e9217a73 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3628,6 +3628,8 @@
"notFound": "Session not found.",
"missingSessionId": "Missing session id in the URL.",
"transcriptEmpty": "Type a message below to start the conversation",
+ "loadingOlder": "Loading earlier messages",
+ "noEarlierMessages": "No earlier messages",
"forkedEmptyTitle": "Forked session ready",
"forkedEmptyBody": "This session has been forked from the source context. The visible transcript starts clean, and the source context is preserved so you can continue the conversation here.",
"forkedFromPrefix": "Forked from",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 986b75db2..f7e18e7a2 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3628,6 +3628,8 @@
"notFound": "未找到该会话。",
"missingSessionId": "URL 缺少 session id。",
"transcriptEmpty": "在下方输入消息开始对话",
+ "loadingOlder": "正在加载更早的消息",
+ "noEarlierMessages": "没有更早的消息了",
"forkedEmptyTitle": "复刻会话已创建",
"forkedEmptyBody": "已从原会话上下文复刻,当前对话记录从空白开始,原会话上下文已保留,继续对话即可",
"forkedFromPrefix": "复刻自",
diff --git a/ui/src/lib/transcriptScrollAnchor.test.ts b/ui/src/lib/transcriptScrollAnchor.test.ts
new file mode 100644
index 000000000..dff8c4f4e
--- /dev/null
+++ b/ui/src/lib/transcriptScrollAnchor.test.ts
@@ -0,0 +1,84 @@
+/** @vitest-environment jsdom */
+
+import { describe, expect, it } from 'vitest';
+
+import { pickScrollAnchor } from './transcriptScrollAnchor';
+
+// jsdom does no layout, so each child declares the rect it would have had. The
+// numbers below mirror the real transcript column: the scroll container carries
+// ``py-5`` (20px) and the column ``gap-3`` (12px), and the older-page spinner is
+// ``h-8`` (32px) — so mounting the spinner shifts every message row down by 44px.
+const CONTAINER_TOP = 0;
+
+const child = (opts: { top: number; height: number; skip?: boolean; id?: string }): HTMLElement => {
+ const el = document.createElement('div');
+ if (opts.id) el.dataset.messageId = opts.id;
+ if (opts.skip) el.dataset.scrollAnchor = 'skip';
+ el.getBoundingClientRect = () =>
+ ({ top: opts.top, bottom: opts.top + opts.height, height: opts.height }) as DOMRect;
+ return el;
+};
+
+describe('pickScrollAnchor', () => {
+ it('picks the topmost element still (partly) in view, relative to the container', () => {
+ const scrolledPast = child({ top: -80, height: 60, id: 'm1' });
+ const firstVisible = child({ top: -8, height: 60, id: 'm2' });
+ const below = child({ top: 64, height: 60, id: 'm3' });
+
+ expect(pickScrollAnchor([scrolledPast, firstVisible, below], CONTAINER_TOP)).toEqual({
+ el: firstVisible,
+ top: -8,
+ });
+ });
+
+ it('reports no anchor when nothing is in view', () => {
+ expect(pickScrollAnchor([child({ top: -120, height: 60, id: 'm1' })], CONTAINER_TOP)).toBeNull();
+ });
+
+ // The regression this rule exists for. Paging up while parked at the very top:
+ // the spinner mounts above the messages, the restore scrolls down by its 44px to
+ // hold the reader's row, and that scroll re-captures the anchor at a position
+ // where the spinner is the topmost visible child. Picking it is fatal twice over
+ // — a prepended page lands below it so it never moves, and the commit that adds
+ // the page unmounts it — which is what left the viewport on the oldest row of the
+ // new page with a near-zero scrollTop that never re-armed the loader.
+ it('never anchors to the older-page spinner, even when it is the topmost visible child', () => {
+ const spinner = child({ top: -24, height: 32, skip: true });
+ const readersRow = child({ top: 20, height: 60, id: 'm2' });
+
+ expect(pickScrollAnchor([spinner, readersRow], CONTAINER_TOP)).toEqual({
+ el: readersRow,
+ top: 20,
+ });
+ });
+
+ it('keeps skipping transient chrome while still ignoring rows scrolled past', () => {
+ const scrolledPast = child({ top: -80, height: 60, id: 'm1' });
+ const spinner = child({ top: -24, height: 32, skip: true });
+ const readersRow = child({ top: 20, height: 60, id: 'm2' });
+
+ expect(pickScrollAnchor([scrolledPast, spinner, readersRow], CONTAINER_TOP)).toEqual({
+ el: readersRow,
+ top: 20,
+ });
+ });
+
+ // Stable chrome (the fork-source banner, a settled Agent Activity chip) is a
+ // legitimate anchor: it survives the load, and holding it holds everything below.
+ it('still anchors to unmarked non-message chrome', () => {
+ const banner = child({ top: 20, height: 28 });
+ const row = child({ top: 60, height: 60, id: 'm1' });
+
+ expect(pickScrollAnchor([banner, row], CONTAINER_TOP)).toEqual({ el: banner, top: 20 });
+ });
+
+ it('measures against the container top rather than the viewport', () => {
+ const offscreenAboveContainer = child({ top: 100, height: 40, id: 'm1' });
+ const firstVisible = child({ top: 152, height: 60, id: 'm2' });
+
+ expect(pickScrollAnchor([offscreenAboveContainer, firstVisible], 150)).toEqual({
+ el: firstVisible,
+ top: 2,
+ });
+ });
+});
diff --git a/ui/src/lib/transcriptScrollAnchor.ts b/ui/src/lib/transcriptScrollAnchor.ts
new file mode 100644
index 000000000..a05807827
--- /dev/null
+++ b/ui/src/lib/transcriptScrollAnchor.ts
@@ -0,0 +1,35 @@
+// The chat transcript keeps its own scroll-anchor: while the reader is scrolled
+// up in history, it remembers the topmost element still in view and how far its
+// top sits below the viewport top, so any later content resize can put that exact
+// element back where it was (iOS Safari still ships no CSS ``overflow-anchor``,
+// and the container opts out of the native one so every browser behaves alike).
+//
+// The anchor is only as good as the element it picks. Chrome that mounts or
+// unmounts AROUND a resize is disqualified: the older-page spinner is the case
+// that motivated this rule. It renders above the messages, so mounting it pushes
+// the anchored row down and the restore scrolls the viewport right onto the
+// spinner; from there it is the worst anchor available, because a prepended page
+// lands BELOW it (it never moves, so the restore computes a zero delta) and the
+// same commit that adds the page unmounts it (so the restore is skipped for a
+// disconnected node). Both paths leave the raw top-of-window ``scrollTop``, which
+// is what made paging up jump to the oldest row of the page just loaded — and
+// that same near-zero ``scrollTop`` then failed the loader's re-arm gate, so no
+// further page could load until the reader scrolled back down and up again.
+//
+// Rule: anything mounted or unmounted around a load carries
+// ``data-scroll-anchor="skip"`` and is never picked.
+export type ScrollAnchor = { el: HTMLElement; top: number };
+
+export const pickScrollAnchor = (
+ children: readonly HTMLElement[],
+ containerTop: number,
+): ScrollAnchor | null => {
+ for (const child of children) {
+ const rect = child.getBoundingClientRect();
+ // Entirely above the viewport top — scrolled past, not what the reader sees.
+ if (rect.bottom <= containerTop) continue;
+ if (child.dataset.scrollAnchor === 'skip') continue;
+ return { el: child, top: rect.top - containerTop };
+ }
+ return null;
+};