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(ui): make the transcript scroll-anchor positional, observe the viewport, surface load failures

cyh08724c18162f
diff --git a/.gitignore b/.gitignore
index 6bfdfeaac..223660546 100644
--- a/.gitignore
+++ b/.gitignore
@@ -154,7 +154,7 @@ _tmp/
.DS_Store
logs/
.vibe_remote/
-ui/node_modules/
+node_modules/
ui/dist/
ui/.vite/
vibe/show_runtime/*.tgz
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index c34c63611..84f7a3738 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -3476,8 +3476,13 @@ const Transcript: React.FC<TranscriptProps> = ({
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.
+ // own and is fresh in the commit that changes either side of the comparison.
const [historyOverflows, setHistoryOverflows] = useState(false);
+ // Surfaces a failed older-page fetch. Without it the spinner simply vanishes,
+ // which is indistinguishable from reaching the start of history — and since a
+ // failure adds no content, a reader parked at the top gets no further scroll
+ // event, so the silent retry the re-arm allows would never actually be reached.
+ const [olderLoadFailed, setOlderLoadFailed] = useState(false);
const loadOlderRef = useRef(onLoadOlder);
const reloadLatestRef = useRef(onReloadLatest);
// Load ONE older page per scroll gesture, not a cascade. The top threshold can
@@ -3560,9 +3565,9 @@ const Transcript: React.FC<TranscriptProps> = ({
// 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).
+ // ``pickScrollAnchor`` owns which elements qualify: the chrome rendered above
+ // ``messages.map`` below is disqualified, because a prepended page lands beneath
+ // it and it therefore 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).
@@ -3621,6 +3626,26 @@ const Transcript: React.FC<TranscriptProps> = ({
}, 150);
}, []);
+ // The one path that starts an older-page load, so the scroll trigger and the
+ // retry affordance cannot drift apart on how a failure is recorded.
+ const runLoadOlder = useCallback(() => {
+ canLoadOlderRef.current = false;
+ loadFailedRef.current = false;
+ setOlderLoadFailed(false);
+ void Promise.resolve(loadOlderRef.current()).then((ok) => {
+ if (ok === false) {
+ // Fetch failed: no content/restore, viewport parked at top. A slow failure
+ // already missed the in-flight-skipped settle and won't get another scroll,
+ // so schedule the re-arm here too (it ignores position when loadFailedRef)
+ // and offer an explicit retry, since a reader who stays put emits no scroll
+ // for that re-armed loader to fire on.
+ loadFailedRef.current = true;
+ setOlderLoadFailed(true);
+ scheduleReArm();
+ }
+ });
+ }, [scheduleReArm]);
+
const handleScroll = () => {
const el = scrollRef.current;
if (!el) return;
@@ -3640,17 +3665,7 @@ const Transcript: React.FC<TranscriptProps> = ({
// anchor-restore scroll + momentum can't cascade more pages.
scheduleReArm();
if (hasOlder && !loadingOlder && canLoadOlderRef.current && el.scrollTop < 120) {
- canLoadOlderRef.current = false;
- loadFailedRef.current = false;
- void Promise.resolve(loadOlderRef.current()).then((ok) => {
- if (ok === false) {
- // Fetch failed: no content/restore, viewport parked at top. A slow failure
- // already missed the in-flight-skipped settle and won't get another scroll,
- // so schedule the re-arm here too (it ignores position when loadFailedRef).
- loadFailedRef.current = true;
- scheduleReArm();
- }
- });
+ runLoadOlder();
}
};
@@ -3662,6 +3677,13 @@ const Transcript: React.FC<TranscriptProps> = ({
pinnedRef.current = true;
anchorRef.current = null;
setShowJump(false);
+ // Paging state belongs to the session that was open, not to the transcript:
+ // the component stays mounted across a switch, so a load that failed in the
+ // previous session would otherwise greet the next one with a retry line for
+ // a page it never asked for, and a disarmed loader would wait for a settle.
+ canLoadOlderRef.current = true;
+ loadFailedRef.current = false;
+ setOlderLoadFailed(false);
const id = requestAnimationFrame(() => scrollToBottom());
return () => cancelAnimationFrame(id);
}, [session.id, scrollToBottom]);
@@ -3737,10 +3759,10 @@ 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.
+ // Overflow is a comparison between the two boxes, so BOTH are observed: the
+ // content grows as pages load, and the viewport shrinks under a composer that
+ // has expanded, an on-screen keyboard, or a resized window. Recomputed ahead
+ // of the anchor branches below so no early return can leave it stale.
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.
@@ -3758,6 +3780,9 @@ const Transcript: React.FC<TranscriptProps> = ({
if (Math.abs(delta) >= 0.5) el.scrollTop += delta;
});
ro.observe(content);
+ // The viewport shrinking under the reader is a resize too: pin-to-bottom has to
+ // re-pin and the anchor has to hold, exactly as when the content itself grew.
+ ro.observe(el);
return () => ro.disconnect();
}, [empty]);
@@ -3803,25 +3828,27 @@ 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}
- {/* 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). */}
+ {/* One slot at the head of the history for every way paging can end, so
+ each outcome resolves in place instead of the top twitching: still
+ loading, failed (and retryable), or nothing older left. */}
{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"
+ ) : olderLoadFailed ? (
+ <button
+ type="button"
+ onClick={runLoadOlder}
+ className="flex h-8 items-center justify-center text-[12px] text-muted hover:text-foreground"
>
+ {t('chat.olderLoadFailed')}
+ </button>
+ ) : atHistoryStart ? (
+ <div className="flex h-8 items-center justify-center text-[12px] text-muted">
{t('chat.noEarlierMessages')}
</div>
) : null}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 2e9217a73..0fb85b1e0 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3630,6 +3630,7 @@
"transcriptEmpty": "Type a message below to start the conversation",
"loadingOlder": "Loading earlier messages",
"noEarlierMessages": "No earlier messages",
+ "olderLoadFailed": "Couldn't load earlier messages — tap to retry",
"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 f7e18e7a2..eb284443b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3630,6 +3630,7 @@
"transcriptEmpty": "在下方输入消息开始对话",
"loadingOlder": "正在加载更早的消息",
"noEarlierMessages": "没有更早的消息了",
+ "olderLoadFailed": "加载更早的消息失败,点击重试",
"forkedEmptyTitle": "复刻会话已创建",
"forkedEmptyBody": "已从原会话上下文复刻,当前对话记录从空白开始,原会话上下文已保留,继续对话即可",
"forkedFromPrefix": "复刻自",
diff --git a/ui/src/lib/transcriptScrollAnchor.test.ts b/ui/src/lib/transcriptScrollAnchor.test.ts
index dff8c4f4e..52093ed6f 100644
--- a/ui/src/lib/transcriptScrollAnchor.test.ts
+++ b/ui/src/lib/transcriptScrollAnchor.test.ts
@@ -10,20 +10,29 @@ import { pickScrollAnchor } from './transcriptScrollAnchor';
// ``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 => {
+// A message row: the kind of element a prepended page pushes down.
+const row = (opts: { top: number; height: number; id: string }): HTMLElement => {
+ const el = document.createElement('div');
+ el.dataset.messageId = opts.id;
+ el.getBoundingClientRect = () =>
+ ({ top: opts.top, bottom: opts.top + opts.height, height: opts.height }) as DOMRect;
+ return el;
+};
+
+// Anything without a message id: chrome. Above the message list it holds still
+// across a load, which is exactly why it must never be picked.
+const chrome = (opts: { top: number; height: number }): 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' });
+ it('picks the topmost row still (partly) in view, relative to the container', () => {
+ const scrolledPast = row({ top: -80, height: 60, id: 'm1' });
+ const firstVisible = row({ top: -8, height: 60, id: 'm2' });
+ const below = row({ top: 64, height: 60, id: 'm3' });
expect(pickScrollAnchor([scrolledPast, firstVisible, below], CONTAINER_TOP)).toEqual({
el: firstVisible,
@@ -31,50 +40,61 @@ describe('pickScrollAnchor', () => {
});
});
- it('reports no anchor when nothing is in view', () => {
- expect(pickScrollAnchor([child({ top: -120, height: 60, id: 'm1' })], CONTAINER_TOP)).toBeNull();
+ it('reports no anchor when every row is scrolled past', () => {
+ expect(pickScrollAnchor([row({ 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('reports no anchor when the transcript has no rows at all', () => {
+ expect(pickScrollAnchor([chrome({ top: 20, height: 32 })], CONTAINER_TOP)).toBeNull();
});
- 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' });
+ // The invariant this module exists for, stated as a property over every kind of
+ // chrome ``ChatPage`` renders ahead of ``messages.map``. All of it holds still
+ // while a prepended page pushes the rows down, so anchoring to any of it computes
+ // a zero delta and drops the reader on the oldest row of the page just loaded —
+ // and the near-zero scrollTop that leaves behind then fails the loader's re-arm
+ // gate, which is what killed paging after the first page.
+ it('never anchors above the first row, whichever chrome sits there', () => {
+ const preMessageChrome = {
+ 'fork-source banner': chrome({ top: -60, height: 28 }),
+ // Unmounted by the very commit that prepends the page, so it would not even
+ // survive to be restored against.
+ 'older-page spinner': chrome({ top: -24, height: 32 }),
+ 'end-of-history line': chrome({ top: -24, height: 32 }),
+ 'null-anchor activity chip': chrome({ top: -12, height: 24 }),
+ };
+ const readersRow = row({ top: 20, height: 60, id: 'm2' });
- expect(pickScrollAnchor([scrolledPast, spinner, readersRow], CONTAINER_TOP)).toEqual({
- el: readersRow,
- top: 20,
- });
+ for (const [name, above] of Object.entries(preMessageChrome)) {
+ expect(pickScrollAnchor([above, readersRow], CONTAINER_TOP), name).toEqual({
+ el: readersRow,
+ top: 20,
+ });
+ }
+
+ // ...and all of it at once, in render order, is still skipped.
+ expect(pickScrollAnchor([...Object.values(preMessageChrome), 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' });
+ // The rule is positional, not "messages only": an activity chip anchored between
+ // two rows is pushed down by a prepend exactly like a row is, so it stays a
+ // legitimate anchor. Skipping it would be as wrong as picking the banner.
+ it('anchors to chrome that sits below the first row', () => {
+ const firstRow = row({ top: -80, height: 60, id: 'm1' });
+ const chipBetweenRows = chrome({ top: -8, height: 24 });
+ const nextRow = row({ top: 28, height: 60, id: 'm2' });
- expect(pickScrollAnchor([banner, row], CONTAINER_TOP)).toEqual({ el: banner, top: 20 });
+ expect(pickScrollAnchor([firstRow, chipBetweenRows, nextRow], CONTAINER_TOP)).toEqual({
+ el: chipBetweenRows,
+ top: -8,
+ });
});
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' });
+ const offscreenAboveContainer = row({ top: 100, height: 40, id: 'm1' });
+ const firstVisible = row({ top: 152, height: 60, id: 'm2' });
expect(pickScrollAnchor([offscreenAboveContainer, firstVisible], 150)).toEqual({
el: firstVisible,
diff --git a/ui/src/lib/transcriptScrollAnchor.ts b/ui/src/lib/transcriptScrollAnchor.ts
index a05807827..e33dbe083 100644
--- a/ui/src/lib/transcriptScrollAnchor.ts
+++ b/ui/src/lib/transcriptScrollAnchor.ts
@@ -1,34 +1,41 @@
// 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).
+// up in history, it remembers an element 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.
+// The anchor is only as good as the element it picks, and the property it must
+// have is positional: **it has to move when an older page is prepended.** Older
+// messages are inserted at the head of ``messages``, so everything the transcript
+// renders ABOVE that list — the fork-source banner, the loading / end-of-history
+// slot, the null-anchor activity chips — stays exactly where it is across the
+// load. Anchoring to one of those restores nothing: the delta is zero, so the
+// viewport keeps the raw top-of-window ``scrollTop`` and the reader is dropped on
+// the oldest row of the page that just arrived. The transient members of that
+// group are worse still — the spinner is unmounted by the very commit that adds
+// the page, so the restore is skipped for a disconnected node — and it was that
+// near-zero ``scrollTop`` which then failed the loader's re-arm gate, leaving
+// paging dead 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.
+// So the rule below is structural rather than a list of elements to avoid: the
+// search starts at the first message row and never looks above it. Chrome added
+// above the transcript later is excluded by construction instead of by someone
+// remembering to mark it.
export type ScrollAnchor = { el: HTMLElement; top: number };
export const pickScrollAnchor = (
children: readonly HTMLElement[],
containerTop: number,
): ScrollAnchor | null => {
- for (const child of children) {
+ // Everything before the first row holds still while the content grows above it,
+ // so it can never restore anything.
+ const firstRow = children.findIndex((child) => child.dataset.messageId !== undefined);
+ if (firstRow < 0) return null;
+ for (let i = firstRow; i < children.length; i += 1) {
+ const child = children[i];
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;