Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Chat: scrolling across a tall reply in a long chat never freezes or unloads what is on screen

aivsomkar809fa9ff5284
diff --git a/src/hooks/use-transcript-viewport.test.ts b/src/hooks/use-transcript-viewport.test.ts
index 51017a9600..7efd678cc4 100644
--- a/src/hooks/use-transcript-viewport.test.ts
+++ b/src/hooks/use-transcript-viewport.test.ts
@@ -135,6 +135,7 @@ let keyListeners: Set<(event: Partial<KeyboardEvent>) => void>;
let observers: number;
let resized: (() => void)[];
let dispatched: unknown[];
+let intersections: ((entries: { isIntersecting: boolean }[]) => void)[];
function mount(initial: Partial<Props> = {}) {
let props: Props = { ownerId: "bot", threadId: "thread", messages: rows(10), pinOn: [false], ...initial };
@@ -146,6 +147,7 @@ function mount(initial: Partial<Props> = {}) {
const commit = () => {
result.scrollRef.current = scroller as unknown as HTMLDivElement;
result.transcriptRef.current = transcriptOf(result.windowedMessages) as unknown as HTMLDivElement;
+ result.topSentinelRef.current = {} as HTMLDivElement;
scroller.rows = result.windowedMessages.length;
scroller.content = result.windowedMessages.reduce((sum, row) => sum + heightOf(row), 0);
scroller.scrollTop = Math.min(scroller.scrollTop, scroller.bottom);
@@ -191,6 +193,7 @@ beforeEach(() => {
observers = 0;
resized = [];
dispatched = [];
+ intersections = [];
forgetTranscriptPositions();
resetLiveReplies();
store.state.focusMessage = null;
@@ -212,7 +215,9 @@ beforeEach(() => {
disconnect() {}
});
vi.stubGlobal("IntersectionObserver", class {
- constructor() {}
+ constructor(callback: (entries: { isIntersecting: boolean }[]) => void) {
+ intersections.push(callback);
+ }
observe() {}
disconnect() {}
});
@@ -732,6 +737,52 @@ describe("a long conversation read from its end to its start and back", () => {
expect(view.current.windowedMessages).toHaveLength(120);
});
+ it("keeps stepping up when the top sentinel reports between a step's commit and the observer's next subscription", () => {
+ const view = mount({ messages: rows(600) });
+ view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
+ const observedBeforeStep = intersections.at(-1)!;
+ scrollTo(view, 100);
+ expect(view.current.hiddenCount).toBe(480 - TRANSCRIPT_WINDOW_STEP);
+
+ view.act(() => observedBeforeStep([{ isIntersecting: true }]));
+ const afterReport = view.current.hiddenCount;
+ scrollTo(view, scroller.scrollTop + 100);
+ scrollTo(view, 50);
+ expect(view.current.hiddenCount).toBeLessThan(afterReport);
+ });
+
+ it("never lets go of a row on screen when rows that draw nothing make the whole window shorter than the view", () => {
+ // Turns of a question, 110 folded tool steps and a short answer; the newest answer is five views tall.
+ heightOf = (row) => {
+ const index = Number(row.id.slice(1));
+ return index === 599 ? 2_000 : index % 112 === 0 || index % 112 === 111 ? 50 : 0;
+ };
+ const view = mount({ messages: rows(600) });
+ view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
+ const onScreen = () => {
+ let below = 0;
+ return view.current.windowedMessages.filter((row) => {
+ const top = below;
+ below += heightOf(row);
+ return heightOf(row) > 0 && top < scroller.scrollTop + scroller.clientHeight && below > scroller.scrollTop;
+ }).map((row) => row.id);
+ };
+ /** Moves the view by `by` and checks the window step that follows keeps every row on screen at that moment. */
+ const wheel = (by: number) => {
+ scroller.scrollTop = Math.max(0, Math.min(scroller.bottom, scroller.scrollTop + by));
+ const shown = onScreen();
+ view.act(() => {
+ view.current.scrollHandlers.onWheel({ deltaY: by } as never);
+ view.current.scrollHandlers.onScroll();
+ });
+ expect(view.current.windowedMessages.map((row) => row.id)).toEqual(expect.arrayContaining(shown));
+ };
+ for (let step = 0; step < 200 && view.current.hiddenCount > 0; step++) wheel(-100);
+ expect(view.current.hiddenCount).toBe(0);
+ for (let step = 0; step < 200 && view.current.laterCount > 0; step++) wheel(100);
+ expect(view.current.laterCount).toBe(0);
+ });
+
it("keeps a window of held pages bounded as older pages arrive from the server", () => {
let held = rows(200, 2_800);
const view = mount({ messages: held, hasMore: true });
diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.ts
index 0a0127656f..fe1164443b 100644
--- a/src/hooks/use-transcript-viewport.ts
+++ b/src/hooks/use-transcript-viewport.ts
@@ -152,6 +152,19 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (aside) setAside.current = { key: transcriptKey, selection: aside };
return next;
};
+ /**
+ * `next`, widened over the rows on screen: rows that draw nothing (folded tool steps) can leave a whole window shorter
+ * than the view. Unbounded, since no more rows can be on screen than fit on it.
+ */
+ const keepOnScreen = (next: TranscriptWindowBounds): TranscriptWindowBounds => {
+ const el = scrollRef.current, list = transcriptRef.current;
+ if (!el || !list) return next;
+ const shown = rowsInView(el, list, restingCardId.current)
+ .map((row) => messages.findIndex((message) => message.id === row.rowId))
+ .filter((index) => index >= 0);
+ if (shown.length === 0) return next;
+ return holdRows(next, messages.length, { first: Math.min(...shown), last: Math.max(...shown) }, Infinity)!;
+ };
const readingBottom = () => {
const el = scrollRef.current;
return Boolean(el) && gapBelow(el!) <= el!.clientHeight;
@@ -179,7 +192,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
? { start: current.restore?.start ?? tailStart, end: current.restore?.end ?? null, added: -1 }
: nextWindow(transcriptWindow, messages, following, readingBottom);
const moves = proposed.start !== transcriptWindow.start || proposed.end !== transcriptWindow.end;
- const next = !switched && moves ? { ...proposed, ...keepSelection(proposed) } : proposed;
+ const next = !switched && moves ? { ...proposed, ...keepSelection(following ? proposed : keepOnScreen(proposed)) } : proposed;
if (switched || next.start !== transcriptWindow.start || next.end !== transcriptWindow.end || first !== transcriptWindow.first) {
// Rows came in front of the drawn ones or left their top: the DOM is still the last commit's, so it is read now.
if (!switched && !following && (next.added > 0 || next.start > transcriptWindow.start)) holdRow();
@@ -390,7 +403,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
/** Draws the window `step` gives, in a transition so its rows mount between frames; false when there is nothing to draw. */
const stepWindow = (step: (window: TranscriptWindowBounds, total: number) => TranscriptWindowBounds) => {
- const target = keepSelection(step(drawnBounds, messages.length), drawnBounds);
+ const target = keepSelection(keepOnScreen(step(drawnBounds, messages.length)), drawnBounds);
if (target.start === drawnBounds.start && target.end === drawnBounds.end) return false;
holdRow(windowRef.current);
startTransition(() => setTranscriptWindow((w) => w.key === transcriptKey ? { ...w, ...target } : w));
@@ -438,6 +451,8 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (expandingRef.current || drawFromRef.current || laterCount === 0) return;
expandingRef.current = stepWindow(windowLater);
};
+ const latestAutoEarlier = useRef(triggerAutoEarlier);
+ latestAutoEarlier.current = triggerAutoEarlier;
useEffect(() => {
const sentinel = topSentinelRef.current;
@@ -446,8 +461,10 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const observer = new IntersectionObserver(
(entries) => {
const entry = entries[0];
+ // An observer can report between a step's commit and this effect re-running: the step it made would start
+ // from the window before, ask for the window already drawn, and hold every later step forever.
if (entry?.isIntersecting && !followRef.current && !movingDown.current) {
- triggerAutoEarlier();
+ latestAutoEarlier.current();
}
},
{ root, rootMargin: `${STEP_AHEAD_VIEWS * 100}% 0px 0px 0px` },
diff --git a/src/lib/transcript-window.ts b/src/lib/transcript-window.ts
index d467e37dab..fb1b0aca82 100644
--- a/src/lib/transcript-window.ts
+++ b/src/lib/transcript-window.ts
@@ -74,11 +74,11 @@ export function windowAfterPrepend({ start, end }: TranscriptWindowBounds, added
return capWindowEnd(moved, total);
}
-/** `window` widened to draw rows `first` to `last`, or null when that would draw more than `SELECTION_HOLD_MAX` rows. */
-export function holdRows({ start, end }: TranscriptWindowBounds, total: number, { first, last }: { first: number; last: number }): TranscriptWindowBounds | null {
+/** `window` widened to draw rows `first` to `last`, or null when that would draw more than `max` rows. */
+export function holdRows({ start, end }: TranscriptWindowBounds, total: number, { first, last }: { first: number; last: number }, max = SELECTION_HOLD_MAX): TranscriptWindowBounds | null {
const from = Math.max(0, Math.min(start, first));
const to = Math.min(total, Math.max(end ?? total, last + 1));
- if (to - from > SELECTION_HOLD_MAX) return null;
+ if (to - from > max) return null;
return { start: from, end: end === null || to >= total ? null : to };
}