Skip to content

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

Transcript: a bounded window however far the reader scrolls (#6559)

Milind Soni3824568a84cf
diff --git a/src/hooks/use-transcript-viewport.test.ts b/src/hooks/use-transcript-viewport.test.ts
index 396edc6a14..7846cd400d 100644
--- a/src/hooks/use-transcript-viewport.test.ts
+++ b/src/hooks/use-transcript-viewport.test.ts
@@ -83,6 +83,7 @@ vi.mock("@/state/store", () => ({ useStore: () => store }));
vi.mock("@/lib/focus-message", () => ({ useFocusMessage: () => {} }));
import { useTranscriptViewport } from "./use-transcript-viewport";
+import { TRANSCRIPT_WINDOW_MAX } from "@/lib/transcript-window";
import { forgetTranscriptPositions } from "@/lib/transcript-follow";
import { noteLiveReplyEvent, resetLiveReplies } from "@/state/live-reply";
import type { RuntimeEvent } from "../../shared/runtime-events";
@@ -345,22 +346,35 @@ describe("transcript viewport", () => {
expect(view.current.windowedMessages.at(-1)?.id).toBe("step299");
});
- it("holds the reader's rows and grows the window once they have scrolled away", () => {
+ it("holds the reader's rows once they have scrolled away, drawing new rows only up to the window's cap", () => {
const view = mount({ messages: rows(300) });
view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
scroller.scrollTop = 2_000;
for (let total = 301; total <= 900; total++) view.rerender({ messages: rows(total) });
expect(view.current.hiddenCount).toBe(180);
- expect(view.current.windowedMessages).toHaveLength(720);
+ expect(view.current.windowedMessages).toHaveLength(TRANSCRIPT_WINDOW_MAX);
+ expect(view.current.laterCount).toBe(900 - 180 - TRANSCRIPT_WINDOW_MAX);
expect(scroller.scrollTop).toBe(2_000);
});
it("slides back to the latest window when the reader returns to the bottom", () => {
const view = mount({ messages: rows(300) });
view.act(() => view.current.showEarlier());
+ view.act(() => {
+ scroller.scrollTop = 1_000;
+ view.current.scrollHandlers.onScroll();
+ });
view.rerender({ messages: rows(301) });
expect(view.current.hiddenCount).toBe(60);
+ expect(view.current.laterCount, "the row past the cap waits below a reader up the page").toBe(1);
+ view.act(() => {
+ scroller.scrollTop = scroller.bottom;
+ view.current.scrollHandlers.onScroll();
+ view.current.scrollHandlers.onWheel({ deltaY: 40 } as never);
+ });
+ expect(view.current.following, "the bottom of a window short of the newest row is not the end").toBe(false);
+ expect(view.current.laterCount).toBe(0);
view.act(() => {
scroller.scrollTop = scroller.bottom;
view.current.scrollHandlers.onScroll();
@@ -370,6 +384,27 @@ describe("transcript viewport", () => {
expect(scroller.scrollTop).toBe(scroller.bottom);
});
+ it("lets the oldest rows go instead when rows arrive under a reader near the bottom", () => {
+ let thread = rows(300);
+ const view = mount({ messages: thread });
+ view.act(() => view.current.showEarlier());
+ view.act(() => {
+ scroller.scrollTop = scroller.bottom - 200;
+ view.current.scrollHandlers.onScroll();
+ });
+ expect(view.current.following).toBe(false);
+ for (let step = 0; step < 300; step++) {
+ scroller.scrollTop = Math.max(0, scroller.bottom - 200);
+ const reading = view.current.windowedMessages[Math.floor(scroller.scrollTop / ROW)]!.id;
+ thread = [...thread, { id: `new${step}`, role: "bot" }];
+ view.rerender({ messages: thread });
+ expect(view.current.windowedMessages.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ expect(view.current.laterCount).toBe(0);
+ expect(view.current.windowedMessages[Math.floor(scroller.scrollTop / ROW)]!.id).toBe(reading);
+ }
+ expect(view.current.windowedMessages.at(-1)?.id).toBe("new299");
+ });
+
it("shows the tail of a thread that shrinks under the window, following or not", () => {
const view = mount({ messages: rows(300) });
view.rerender({ messages: rows(400) });
@@ -460,17 +495,19 @@ describe("transcript viewport", () => {
expect(view.current.laterCount).toBe(60);
});
- it("keeps a search result's window when the reader scrolls to its end", () => {
+ it("pages on past a search result as the reader scrolls down, and follows only from the newest row", () => {
store.state.focusMessage = { threadId: "thread", messageId: "m10", nonce: 1, consumed: false };
const view = mount({ messages: rows(300) });
view.act(() => {
scroller.scrollTop = scroller.bottom;
view.current.scrollHandlers.onScroll();
});
- expect(view.current.following).toBe(true);
- view.rerender({ messages: rows(301) });
+ expect(view.current.following).toBe(false);
expect(view.current.windowedMessages[0]?.id).toBe("m0");
- expect(view.current.laterCount).toBe(181);
+ expect(view.current.laterCount).toBe(60);
+ view.rerender({ messages: rows(301) });
+ expect(view.current.laterCount).toBe(61);
+ expect(view.current.showJumpToLatest || view.current.following).toBe(false);
});
it("jumps back to the latest rows and resumes following", () => {
@@ -604,6 +641,81 @@ describe("transcript viewport", () => {
});
});
+describe("a long conversation read from its end to its start and back", () => {
+ const topId = (view: ReturnType<typeof mount>) => view.current.windowedMessages[Math.floor(scroller.scrollTop / ROW)]!.id;
+ const scrollTo = (view: ReturnType<typeof mount>, top: number) => view.act(() => {
+ scroller.scrollTop = top;
+ view.current.scrollHandlers.onScroll();
+ });
+ /** Scrolls to `top` and returns the row the reader sees there, read before the window steps. */
+ const readAt = (view: ReturnType<typeof mount>, top: number) => {
+ scroller.scrollTop = top;
+ const reading = topId(view);
+ view.act(() => view.current.scrollHandlers.onScroll());
+ return reading;
+ };
+
+ it("draws a bounded window all the way up and down, with the row under the reader held in place at each step", () => {
+ const view = mount({ messages: rows(3_000) });
+ view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
+ let steps = 0;
+ while (view.current.hiddenCount > 0 && steps++ < 100) {
+ scrollTo(view, 400);
+ const reading = readAt(view, 200);
+ expect(view.current.windowedMessages.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ expect(topId(view), "the row at the top stays the row at the top").toBe(reading);
+ }
+ expect(view.current.windowedMessages[0]?.id).toBe("m0");
+ expect(view.current.windowedMessages).toHaveLength(TRANSCRIPT_WINDOW_MAX);
+ expect(view.current.laterCount).toBe(3_000 - TRANSCRIPT_WINDOW_MAX);
+ expect(view.current.following).toBe(false);
+
+ steps = 0;
+ while (view.current.laterCount > 0 && steps++ < 100) {
+ scrollTo(view, scroller.bottom - 800);
+ const reading = readAt(view, scroller.bottom - 100);
+ expect(view.current.windowedMessages.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ expect(topId(view), "the row at the top stays the row at the top").toBe(reading);
+ expect(view.current.following, "no follow before the newest row").toBe(false);
+ }
+ expect(view.current.windowedMessages.at(-1)?.id).toBe("m2999");
+ scrollTo(view, scroller.bottom);
+ expect(view.current.following).toBe(true);
+ expect(view.current.windowedMessages).toHaveLength(120);
+ });
+
+ 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 });
+ view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
+ for (let page = 13; page >= 0; page--) {
+ while (view.current.hiddenCount > 0) {
+ scrollTo(view, 400);
+ scrollTo(view, 100);
+ }
+ dispatched = [];
+ scrollTo(view, 400);
+ scrollTo(view, 100);
+ expect(dispatched).toEqual([{ type: "loadOlderMessages", threadId: "thread" }]);
+ const reading = topId(view);
+ held = [...rows(200, page * 200), ...held];
+ view.rerender({ messages: held, hasMore: page > 0 });
+ expect(topId(view), "the row at the top stays the row at the top").toBe(reading);
+ expect(view.current.windowedMessages.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ }
+ expect(held).toHaveLength(3_000);
+ });
+
+ it("lets go of the rows paged in above the window when the reader leaves", () => {
+ const view = mount({ messages: rows(3_000) });
+ view.act(() => view.current.showEarlier());
+ const windowFirst = view.current.windowedMessages[0]!.id;
+ dispatched = [];
+ view.rerender({ threadId: "other", messages: rows(10, 9_000) });
+ expect(dispatched).toEqual([{ type: "trimHeldMessages", threadId: "thread", keepFromId: windowFirst }]);
+ });
+});
+
describe("following a reply and coming back to a conversation", () => {
const readUpTo = (view: ReturnType<typeof mount>, scrollTop: number) => {
view.act(() => view.current.scrollHandlers.onWheel({ deltaY: -40 } as never));
diff --git a/src/hooks/use-transcript-viewport.ts b/src/hooks/use-transcript-viewport.ts
index ac7068c55a..2eea5b375d 100644
--- a/src/hooks/use-transcript-viewport.ts
+++ b/src/hooks/use-transcript-viewport.ts
@@ -13,13 +13,19 @@ import {
import { BOTTOM_FOLLOW_THRESHOLD, followBottomGrowth, useBottomFollowResize } from "@/lib/bottom-follow";
import { useFocusMessage } from "@/lib/focus-message";
import {
+ TRANSCRIPT_WINDOW_MAX,
TRANSCRIPT_WINDOW_SIZE,
- expandWindowStart,
+ capWindowEnd,
focusWindowRange,
followWindowStart,
resolveTranscriptWindow,
+ restoreWindow,
tailWindowStart,
+ windowAfterPrepend,
+ windowEarlier,
+ windowLater,
withRestingCard,
+ type TranscriptWindowBounds,
} from "@/lib/transcript-window";
import { reducedMotion } from "@/lib/onboarding";
import {
@@ -28,6 +34,7 @@ import {
readTranscriptPosition,
rememberTranscriptPosition,
rowScrollTop,
+ rowsInView,
settleScroll,
topRow,
transitionTranscriptFollow,
@@ -42,21 +49,41 @@ export const AUTO_EXPAND_TOP_THRESHOLD = 250;
const WIDGETS_WITH_OWN_ARROW_KEYS = '[role="menu"], [role="menubar"], [role="listbox"], [role="tree"], [role="grid"], [role="tablist"], [role="radiogroup"], [role="slider"], select, [contenteditable="true"]';
-const atEndOf = (el: HTMLElement | null) => !el || el.scrollHeight - el.scrollTop - el.clientHeight < BOTTOM_FOLLOW_THRESHOLD;
+const gapBelow = (el: HTMLElement) => el.scrollHeight - el.scrollTop - el.clientHeight;
+const atEndOf = (el: HTMLElement | null) => !el || gapBelow(el) < BOTTOM_FOLLOW_THRESHOLD;
interface TranscriptVisit {
key: string;
follow: TranscriptFollow;
- /** The row to put back at the top, and the window start that draws it; absent when the visit opens at the end. */
- restore?: { rowId: string; offsetWithinRow: number; start: number };
+ /** The row to put back at the top, and the window that draws it; absent when the visit opens at the end. */
+ restore?: { rowId: string; offsetWithinRow: number } & TranscriptWindowBounds;
}
+type HeldWindow = { key: string; first: string | undefined } & TranscriptWindowBounds;
+
function openVisit(key: string, messages: readonly { id: string }[]): TranscriptVisit {
const remembered = readTranscriptPosition(key);
const rowIndex = remembered && !remembered.atEnd && remembered.rowId ? messages.findIndex((message) => message.id === remembered.rowId) : -1;
if (!remembered || rowIndex < 0) return { key, follow: initialTranscriptFollow(true) };
- const start = Math.min(rowIndex, Math.max(0, Math.min(remembered.windowStart ?? rowIndex, tailWindowStart(messages.length))));
- return { key, follow: initialTranscriptFollow(false), restore: { rowId: remembered.rowId!, offsetWithinRow: remembered.offsetWithinRow ?? 0, start } };
+ const window = restoreWindow(messages.length, rowIndex, remembered.windowStart);
+ return { key, follow: initialTranscriptFollow(false), restore: { rowId: remembered.rowId!, offsetWithinRow: remembered.offsetWithinRow ?? 0, ...window } };
+}
+
+/**
+ * The window for this render: shifted over older rows put in front, tailed while following, capped while reading.
+ * New rows past the cap wait below a reader up the page; under one reading near the bottom, the oldest rows go instead.
+ */
+function nextWindow(window: HeldWindow, messages: readonly { id: string; role?: string }[], following: boolean, readingBottom: () => boolean): TranscriptWindowBounds & { added: number } {
+ const added = window.first !== undefined && window.first !== messages[0]?.id ? messages.findIndex((message) => message.id === window.first) : -1;
+ const bounds = added > 0 ? windowAfterPrepend(window, added, messages.length) : { start: window.start, end: window.end };
+ if (following) {
+ const start = bounds.end === null ? followWindowStart(messages, bounds.start) : tailWindowStart(messages.length);
+ return { start, end: null, added };
+ }
+ if (bounds.end !== null) return { ...bounds, added };
+ const capped = capWindowEnd(bounds, messages.length);
+ if (capped.end === null || !readingBottom()) return { ...capped, added };
+ return { start: Math.max(bounds.start, messages.length - TRANSCRIPT_WINDOW_MAX), end: null, added };
}
export function useTranscriptViewport<T extends { id: string; role?: string }>({
@@ -87,10 +114,23 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const transcriptKey = `${ownerId}:${threadId}`;
const tailStart = tailWindowStart(messages.length);
+ /** The rows on screen before a window step; the commit after it puts the first one still drawn back in place. */
+ const anchor = useRef<{ key: string; rows: ReturnType<typeof rowsInView>; height: number } | null>(null);
+ const restingCardId = useRef<string | undefined>(undefined);
+ const holdRow = () => {
+ const el = scrollRef.current, list = transcriptRef.current;
+ anchor.current = el ? { key: transcriptKey, rows: list ? rowsInView(el, list, restingCardId.current) : [], height: el.scrollHeight } : null;
+ };
+ const readingBottom = () => {
+ const el = scrollRef.current;
+ return Boolean(el) && gapBelow(el!) <= el!.clientHeight;
+ };
+ const lastTop = useRef(0);
+ const movingDown = useRef(false);
// One visit per conversation: switching back opens where the reader left it, or at the end if they were there.
const [visit, setVisit] = useState(() => openVisit(transcriptKey, messages));
- const [transcriptWindow, setTranscriptWindow] = useState<{ key: string; start: number; end: number | null }>(
- () => ({ key: transcriptKey, start: visit.restore?.start ?? tailStart, end: null }),
+ const [transcriptWindow, setTranscriptWindow] = useState<HeldWindow>(
+ () => ({ key: transcriptKey, first: messages[0]?.id, start: visit.restore?.start ?? tailStart, end: visit.restore?.end ?? null }),
);
const followNow = useRef<{ key: string; follow: TranscriptFollow }>({ key: visit.key, follow: visit.follow });
const followRef = useRef(visit.follow.mode === "following");
@@ -103,13 +143,14 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
}
const follow = followNow.current.follow;
const following = follow.mode === "following";
- const nextStart = switched
- ? current.restore?.start ?? tailStart
- : following && transcriptWindow.end === null
- ? followWindowStart(messages, transcriptWindow.start)
- : transcriptWindow.start;
- if (switched || nextStart !== transcriptWindow.start) {
- setTranscriptWindow({ key: transcriptKey, start: nextStart, end: null });
+ const first = messages[0]?.id;
+ const next = switched
+ ? { start: current.restore?.start ?? tailStart, end: current.restore?.end ?? null, added: -1 }
+ : nextWindow(transcriptWindow, messages, following, readingBottom);
+ 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();
+ setTranscriptWindow({ key: transcriptKey, first, start: next.start, end: next.end });
}
const {
visible: windowedMessages,
@@ -123,6 +164,16 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
}, [messages, transcriptWindow.start, transcriptWindow.end, rests]);
const windowRef = useRef(transcriptWindow);
windowRef.current = transcriptWindow;
+ restingCardId.current = windowedMessages[0] && windowedMessages[0] !== messages[startIndex] ? windowedMessages[0].id : undefined;
+ const drawnBounds: TranscriptWindowBounds = { start: startIndex, end: laterCount > 0 ? endIndex : null };
+ const laterRef = useRef(laterCount);
+ laterRef.current = laterCount;
+ /** At the newest row: the bottom of a window that stops short of it is not the end. */
+ const atLiveEnd = (el: HTMLElement | null) => laterRef.current === 0 && atEndOf(el);
+ const nearWindowBottom = () => {
+ const el = scrollRef.current;
+ return laterCount > 0 && Boolean(el) && gapBelow(el!) <= AUTO_EXPAND_TOP_THRESHOLD;
+ };
const [, setFollowShown] = useState(follow);
const navigationCount = useRef(0);
@@ -145,9 +196,9 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
}, [smoothFollow]);
const setBottomFollow = useCallback((next: boolean) => followEvent({ type: next ? "followEnd" : "navigated" }), [followEvent]);
- const nearEnd = () => atEndOf(scrollRef.current);
+ const nearEnd = () => atLiveEnd(scrollRef.current);
const noteEnd = useCallback(() => {
- if (scrollRef.current) followEvent({ type: atEndOf(scrollRef.current) ? "reachedEnd" : "leftEnd" });
+ if (scrollRef.current) followEvent({ type: atLiveEnd(scrollRef.current) ? "reachedEnd" : "leftEnd" });
}, [followEvent]);
const recordFrame = useRef(false);
@@ -166,7 +217,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
// Content growing under a released reader can only take the end away from them; their own scroll brings it back.
const noteLeftEnd = useCallback(() => {
- if (!atEndOf(scrollRef.current)) followEvent({ type: "leftEnd" });
+ if (!atLiveEnd(scrollRef.current)) followEvent({ type: "leftEnd" });
}, [followEvent]);
const onTranscriptResize = useCallback(() => {
const el = scrollRef.current;
@@ -188,9 +239,10 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (!el || !list || !restore) return;
const navigations = navigationCount.current;
const target = () => rowScrollTop(el, list, restore.rowId, restore.offsetWithinRow);
- const first = target();
- if (first === undefined) return;
- el.scrollTop = first;
+ const top = target();
+ if (top === undefined) return;
+ el.scrollTop = top;
+ lastTop.current = top;
settleScroll(el, target, () => navigationCount.current !== navigations || followNow.current.key !== current.key);
}, [current]);
@@ -205,7 +257,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const range = focusWindowRange(messages.length, targetIndex);
followEvent({ type: "navigated" });
followEvent({ type: "leftEnd" });
- setTranscriptWindow({ key: transcriptKey, start: range.start, end: range.end });
+ setTranscriptWindow({ key: transcriptKey, first: messages[0]?.id, start: range.start, end: range.end });
}, [threadId, messages, followEvent, focusMessage, transcriptKey]);
useFocusMessage(threadId, messages.length > 0, scrollRef);
@@ -216,43 +268,43 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (!el) return;
if (!followRef.current) return noteLeftEnd();
el.scrollTo({ top: el.scrollHeight });
+ lastTop.current = el.scrollTop;
// eslint-disable-next-line react-hooks/exhaustive-deps -- pinOn is the caller's dependency list
- }, [transcriptKey, messages.length, ...pinOn]);
+ }, [transcriptKey, messages.length, laterCount > 0, ...pinOn]);
- // Shift scrollTop by the growth after commit (scroll anchoring is off here); a switch drops the capture.
- const preExpandHeight = useRef<{ key: string; height: number } | null>(null);
const expandingRef = useRef(false);
-
const holdRowForPrepend = () => {
- preExpandHeight.current = scrollRef.current ? { key: transcriptKey, height: scrollRef.current.scrollHeight } : null;
+ holdRow();
setBottomFollow(false);
};
- const oldestId = messages[0]?.id;
+ // The commit after a window step: the row that was on screen goes back where it was (scroll anchoring is off here),
+ // whichever edges gained or lost rows; a switch drops the capture.
useLayoutEffect(() => {
- const el = scrollRef.current;
- const captured = preExpandHeight.current;
- if (!captured || !el) {
- expandingRef.current = false;
- return;
- }
- preExpandHeight.current = null;
- if (captured.key !== transcriptKey) {
- expandingRef.current = false;
- return;
- }
- el.scrollTop += el.scrollHeight - captured.height;
+ const el = scrollRef.current, list = transcriptRef.current, held = anchor.current;
+ if (!held || !el) return;
+ anchor.current = null;
expandingRef.current = false;
- }, [transcriptWindow.start, oldestId, transcriptKey]);
+ if (held.key !== transcriptKey) return;
+ let top: number | undefined;
+ for (const row of list ? held.rows : []) {
+ top = rowScrollTop(el, list!, row.rowId, row.offsetWithinRow);
+ if (top !== undefined) break;
+ }
+ el.scrollTop = top ?? el.scrollTop + el.scrollHeight - held.height;
+ lastTop.current = el.scrollTop;
+ });
+ const stepWindow = (step: (window: TranscriptWindowBounds, total: number) => TranscriptWindowBounds) => {
+ holdRow();
+ setTranscriptWindow((w) => ({ ...w, ...step(drawnBounds, messages.length) }));
+ };
const showEarlier = () => {
- holdRowForPrepend();
- const start = expandWindowStart(startIndex);
- setTranscriptWindow((w) => ({ ...w, start }));
+ setBottomFollow(false);
+ stepWindow(windowEarlier);
};
const showLater = () => {
setBottomFollow(false);
- const nextEnd = Math.min(messages.length, endIndex + TRANSCRIPT_WINDOW_SIZE);
- setTranscriptWindow((w) => ({ ...w, end: nextEnd >= messages.length ? null : nextEnd }));
+ stepWindow(windowLater);
};
const loadOlder = () => {
holdRowForPrepend();
@@ -263,19 +315,33 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (!olderPending) expandingRef.current = false;
}, [olderPending]);
+ // Leaving a conversation lets go of the rows paged in above the window the reader left.
+ const leaving = useRef<{ threadId: string; keepFromId: string | undefined } | null>(null);
+ useEffect(() => () => {
+ const left = leaving.current;
+ if (left?.threadId === threadId) dispatch({ type: "trimHeldMessages", threadId, keepFromId: left.keepFromId });
+ }, [threadId, dispatch]);
+ useEffect(() => {
+ leaving.current = { threadId, keepFromId: messages[startIndex]?.id };
+ });
+
const triggerAutoEarlier = useCallback(() => {
if (expandingRef.current) return;
if (hiddenCount > 0) {
expandingRef.current = true;
- holdRowForPrepend();
- const start = expandWindowStart(startIndex);
- setTranscriptWindow((w) => ({ ...w, start }));
+ setBottomFollow(false);
+ stepWindow(windowEarlier);
} else if (hasMore && !olderPending) {
expandingRef.current = true;
holdRowForPrepend();
dispatch({ type: "loadOlderMessages", threadId });
}
- }, [hiddenCount, startIndex, hasMore, olderPending, threadId, dispatch, transcriptKey]);
+ }, [hiddenCount, startIndex, laterCount, endIndex, messages.length, hasMore, olderPending, threadId, dispatch, transcriptKey]);
+ const triggerAutoLater = () => {
+ if (expandingRef.current || laterCount === 0) return;
+ expandingRef.current = true;
+ stepWindow(windowLater);
+ };
useEffect(() => {
const sentinel = topSentinelRef.current;
@@ -284,7 +350,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const observer = new IntersectionObserver(
(entries) => {
const entry = entries[0];
- if (entry?.isIntersecting && !followRef.current) {
+ if (entry?.isIntersecting && !followRef.current && !movingDown.current) {
triggerAutoEarlier();
}
},
@@ -316,7 +382,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
const canScrollUp = () => canScroll() || hiddenCount > 0 || Boolean(hasMore);
const jumpToLatest = () => {
setBottomFollow(true);
- setTranscriptWindow({ key: transcriptKey, start: tailStart, end: null });
+ setTranscriptWindow({ key: transcriptKey, first: messages[0]?.id, start: tailStart, end: null });
requestAnimationFrame(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: reducedMotion() ? "auto" : "smooth" });
});
@@ -329,6 +395,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
if (el && e.target === el && e.nativeEvent.offsetX >= el.clientWidth) setBottomFollow(false);
},
onWheel: (e: WheelEvent<HTMLDivElement>) => {
+ movingDown.current = e.deltaY > 0;
if (e.deltaY < 0 && canScrollUp()) {
setBottomFollow(false);
const el = scrollRef.current;
@@ -337,6 +404,8 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
}
} else if (nearEnd()) {
setBottomFollow(true);
+ } else if (e.deltaY > 0 && nearWindowBottom()) {
+ triggerAutoLater();
}
},
onTouchStart: (e: TouchEvent<HTMLDivElement>) => {
@@ -344,6 +413,7 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
},
onTouchMove: (e: TouchEvent<HTMLDivElement>) => {
const y = e.touches[0]?.clientY ?? 0;
+ movingDown.current = y < touchY.current;
if (y > touchY.current + 4 && canScrollUp()) {
setBottomFollow(false);
const el = scrollRef.current;
@@ -352,14 +422,22 @@ export function useTranscriptViewport<T extends { id: string; role?: string }>({
}
} else if (nearEnd()) {
setBottomFollow(true);
+ } else if (movingDown.current && nearWindowBottom()) {
+ triggerAutoLater();
}
},
onScroll: () => {
const el = scrollRef.current;
if (!el) return;
+ const moved = el.scrollTop - lastTop.current;
+ lastTop.current = el.scrollTop;
+ if (moved !== 0) movingDown.current = moved > 0;
noteEnd();
recordPosition();
- if (!followRef.current && el.scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) triggerAutoEarlier();
+ if (followRef.current) return;
+ // Each edge steps only on a move toward it, so the scrollTop set after a step never steps the other way.
+ if (moved < 0 && el.scrollTop <= AUTO_EXPAND_TOP_THRESHOLD) triggerAutoEarlier();
+ else if (moved > 0 && nearWindowBottom()) triggerAutoLater();
},
};
diff --git a/src/lib/focus-message.load.test.ts b/src/lib/focus-message.load.test.ts
index 1181dc3d98..bb915de1f3 100644
--- a/src/lib/focus-message.load.test.ts
+++ b/src/lib/focus-message.load.test.ts
@@ -38,7 +38,7 @@ describe("landing on a search hit older than the loaded page", () => {
"/api/threads/t/messages?limit=200&before=m200",
]);
expect(actions.map((action) => action.type)).toEqual(["select", "olderMessages", "focusMessage"]);
- expect(actions[1]).toEqual({ type: "olderMessages", threadId: "t", generation: 3, messages: range(0, 400), hasMore: false });
+ expect(actions[1]).toEqual({ type: "olderMessages", threadId: "t", generation: 3, before: "m400", messages: range(0, 400), hasMore: false });
});
it("does the same in the room's open thread", async () => {
@@ -50,7 +50,7 @@ describe("landing on a search hit older than the loaded page", () => {
it("stops at the page that holds the hit", async () => {
await landOnSearchHit({ ...hit, botId: "scout", threadId: "t", messageId: "m300" }, state, dispatch, true);
expect(fixture.api).toHaveBeenCalledOnce();
- expect(actions[1]).toEqual({ type: "olderMessages", threadId: "t", generation: 3, messages: range(200, 400), hasMore: true });
+ expect(actions[1]).toEqual({ type: "olderMessages", threadId: "t", generation: 3, before: "m400", messages: range(200, 400), hasMore: true });
});
it("asks for nothing when the hit is already loaded", async () => {
diff --git a/src/lib/focus-message.ts b/src/lib/focus-message.ts
index 78eb20f3fb..545e27ad72 100644
--- a/src/lib/focus-message.ts
+++ b/src/lib/focus-message.ts
@@ -15,7 +15,8 @@ async function loadThroughMessage(
): Promise<void> {
if (!owner.hasMore || owner.messages.some((message) => message.id === messageId)) return;
const older: Message[] = [];
- let before = owner.messages[0]?.id;
+ const heldFrom = owner.messages[0]?.id;
+ let before = heldFrom;
let hasMore = true;
let found = false;
while (before && hasMore && !found) {
@@ -28,7 +29,7 @@ async function loadThroughMessage(
hasMore = Boolean(page.hasMore) && messages.length > 0;
before = messages[0]?.id;
}
- if (older.length) dispatch({ type: "olderMessages", threadId: owner.threadId, generation, messages: older, hasMore });
+ if (older.length) dispatch({ type: "olderMessages", threadId: owner.threadId, generation, before: heldFrom, messages: older, hasMore });
}
export async function landOnSearchHit(
diff --git a/src/lib/transcript-follow.test.ts b/src/lib/transcript-follow.test.ts
index b4da3242de..efe5fb037e 100644
--- a/src/lib/transcript-follow.test.ts
+++ b/src/lib/transcript-follow.test.ts
@@ -6,6 +6,7 @@ import {
initialTranscriptFollow,
readTranscriptPosition,
rememberTranscriptPosition,
+ rowsInView,
transitionTranscriptFollow,
wantsJumpToLatest,
type TranscriptFollow,
@@ -57,3 +58,16 @@ describe("remembered positions", () => {
expect(readTranscriptPosition("k99")).toEqual({ atEnd: true });
});
});
+
+describe("rows held across a window step", () => {
+ const view = { getBoundingClientRect: () => ({ top: 100, bottom: 500 }) } as unknown as HTMLElement;
+ const list = (tops: [string, number][]) => ({
+ querySelectorAll: () => tops.map(([mid, top]) => ({ dataset: { mid }, getBoundingClientRect: () => ({ top, bottom: top + 150, height: 150 }) })),
+ }) as unknown as HTMLElement;
+
+ it("offers rows wholly on screen first and the window's first row last, skipping the pinned card and live rows", () => {
+ const rows = rowsInView(view, list([["first", 40], ["card", 60], ["a", 190], ["live:x", 250], ["b", 340], ["c", 490], ["below", 520]]), "card");
+ expect(rows.map((row) => row.rowId)).toEqual(["a", "b", "c", "first"]);
+ expect(rows[0]).toEqual({ rowId: "a", offsetWithinRow: -90 });
+ });
+});
diff --git a/src/lib/transcript-follow.ts b/src/lib/transcript-follow.ts
index 86af12b066..c89f7a23f8 100644
--- a/src/lib/transcript-follow.ts
+++ b/src/lib/transcript-follow.ts
@@ -93,6 +93,25 @@ export function topRow(scroller: HTMLElement, transcript: HTMLElement): { rowId:
return null;
}
+/**
+ * The saved rows on screen, each with how far above the view's top its own top lies. Rows wholly on screen come
+ * first, and the transcript's first row comes last: a row at the edge of a window can regroup when rows join it.
+ */
+export function rowsInView(scroller: HTMLElement, transcript: HTMLElement, skip?: string): { rowId: string; offsetWithinRow: number }[] {
+ if (typeof transcript.querySelectorAll !== "function") return [];
+ const view = scroller.getBoundingClientRect();
+ const ranked: { rowId: string; offsetWithinRow: number; rank: number }[] = [];
+ Array.from(transcript.querySelectorAll<HTMLElement>(ROW_SELECTOR)).some((row, index) => {
+ const rowId = row.dataset.mid;
+ if (!rowId || rowId.startsWith("live:") || rowId === skip) return false;
+ const box = rowBox(row);
+ if (box.top >= view.bottom) return true;
+ if (box.bottom > view.top) ranked.push({ rowId, offsetWithinRow: view.top - box.top, rank: index === 0 ? 2 : box.top >= view.top ? 0 : 1 });
+ return false;
+ });
+ return ranked.sort((a, b) => a.rank - b.rank).map(({ rowId, offsetWithinRow }) => ({ rowId, offsetWithinRow }));
+}
+
/** The scrollTop that puts `rowId` back where `topRow` found it, or undefined when the row is not drawn. */
export function rowScrollTop(scroller: HTMLElement, transcript: HTMLElement, rowId: string, offsetWithinRow: number): number | undefined {
if (typeof transcript.querySelectorAll !== "function") return undefined;
diff --git a/src/lib/transcript-window.test.ts b/src/lib/transcript-window.test.ts
index 97e52701eb..f0172f2581 100644
--- a/src/lib/transcript-window.test.ts
+++ b/src/lib/transcript-window.test.ts
@@ -1,13 +1,20 @@
import { describe, expect, it } from "vitest";
import {
+ TRANSCRIPT_WINDOW_MAX,
TRANSCRIPT_WINDOW_SIZE,
+ capWindowEnd,
expandWindowStart,
focusWindowRange,
followWindowStart,
resolveTranscriptWindow,
+ restoreWindow,
tailWindowStart,
+ windowAfterPrepend,
+ windowEarlier,
+ windowLater,
withRestingCard,
+ type TranscriptWindowBounds,
} from "./transcript-window";
const thread = (total: number): number[] => Array.from({ length: total }, (_, i) => i);
@@ -187,3 +194,57 @@ describe("withRestingCard", () => {
expect(withRestingCard(rows, range.visible, range.startIndex)).toBe(range.visible);
});
});
+
+describe("a two-sided window", () => {
+ const drawn = (total: number, window: TranscriptWindowBounds) => resolveTranscriptWindow(thread(total), window.start, TRANSCRIPT_WINDOW_SIZE, window.end);
+
+ it("draws at most the cap however many steps up the reader takes, then as many back down", () => {
+ const total = 3_000;
+ let window: TranscriptWindowBounds = { start: tailWindowStart(total), end: null };
+ const seen = new Set<number>();
+ for (let step = 0; step < 30; step++) {
+ window = windowEarlier(window, total);
+ const shown = drawn(total, window);
+ expect(shown.visible.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ expect(shown.hiddenCount + shown.visible.length + shown.laterCount).toBe(total);
+ for (const row of shown.visible) seen.add(row);
+ }
+ expect(window).toEqual({ start: 0, end: TRANSCRIPT_WINDOW_MAX });
+ expect(seen.size, "every row was drawn on the way up").toBe(total);
+
+ for (let step = 0; step < 30; step++) {
+ window = windowLater(window, total);
+ expect(drawn(total, window).visible.length).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ }
+ expect(window).toEqual({ start: total - TRANSCRIPT_WINDOW_MAX, end: null });
+ });
+
+ it("keeps the rows it had on each step, so the row under the reader stays drawn", () => {
+ const total = 1_000;
+ const up = windowEarlier({ start: 500, end: 740 }, total);
+ expect(up).toEqual({ start: 380, end: 620 });
+ const down = windowLater({ start: 380, end: 620 }, total);
+ expect(down).toEqual({ start: 500, end: 740 });
+ });
+
+ it("caps only a window over the cap, and marks an end at the newest row as null", () => {
+ expect(capWindowEnd({ start: 100, end: null }, 300)).toEqual({ start: 100, end: null });
+ expect(capWindowEnd({ start: 0, end: null }, 300)).toEqual({ start: 0, end: TRANSCRIPT_WINDOW_MAX });
+ expect(capWindowEnd({ start: 200, end: 300 }, 300)).toEqual({ start: 200, end: null });
+ });
+
+ it("moves over an older page put in front: one step of it at the top, the same rows anywhere else", () => {
+ expect(windowAfterPrepend({ start: 0, end: null }, 200, 400)).toEqual({ start: 80, end: 320 });
+ expect(windowAfterPrepend({ start: 0, end: null }, 50, 100)).toEqual({ start: 0, end: null });
+ expect(windowAfterPrepend({ start: 40, end: 200 }, 200, 600)).toEqual({ start: 240, end: 400 });
+ });
+
+ it("puts a remembered row back inside a capped window", () => {
+ const window = restoreWindow(3_000, 1_000, 0);
+ expect(window.start).toBeLessThanOrEqual(1_000);
+ expect(window.end).not.toBeNull();
+ expect(window.end! - window.start).toBeLessThanOrEqual(TRANSCRIPT_WINDOW_MAX);
+ expect(window.end).toBeGreaterThan(1_000);
+ expect(restoreWindow(300, 250, 200)).toEqual({ start: 180, end: null });
+ });
+});
diff --git a/src/lib/transcript-window.ts b/src/lib/transcript-window.ts
index b5e6af940f..304927ba8f 100644
--- a/src/lib/transcript-window.ts
+++ b/src/lib/transcript-window.ts
@@ -1,4 +1,6 @@
export const TRANSCRIPT_WINDOW_SIZE = 120;
+/** The most rows drawn at once while the reader is away from the end: one step past it unloads rows at the far edge. */
+export const TRANSCRIPT_WINDOW_MAX = 2 * TRANSCRIPT_WINDOW_SIZE;
export interface TranscriptWindow<T> {
visible: T[];
@@ -30,6 +32,42 @@ export function expandWindowStart(startIndex: number, size: number = TRANSCRIPT_
return Math.max(0, startIndex - size);
}
+/** A window over a transcript; a null `end` reaches the newest row and grows with it. */
+export interface TranscriptWindowBounds {
+ start: number;
+ end: number | null;
+}
+
+/** Holds a window to `TRANSCRIPT_WINDOW_MAX` rows by dropping rows at its bottom; an end at the newest row is null. */
+export function capWindowEnd({ start, end }: TranscriptWindowBounds, total: number): TranscriptWindowBounds {
+ const last = Math.min(total, end ?? total);
+ if (last - start > TRANSCRIPT_WINDOW_MAX) return { start, end: start + TRANSCRIPT_WINDOW_MAX };
+ return { start, end: last >= total ? null : last };
+}
+
+export function windowEarlier(window: TranscriptWindowBounds, total: number): TranscriptWindowBounds {
+ return capWindowEnd({ start: expandWindowStart(window.start), end: window.end }, total);
+}
+
+/** One step down: rows below join and, past the cap, rows at the top leave. */
+export function windowLater({ start, end }: TranscriptWindowBounds, total: number): TranscriptWindowBounds {
+ if (end === null) return { start, end };
+ const nextEnd = Math.min(total, end + TRANSCRIPT_WINDOW_SIZE);
+ return { start: Math.max(start, nextEnd - TRANSCRIPT_WINDOW_MAX), end: nextEnd >= total ? null : nextEnd };
+}
+
+/** The window after `added` older rows were put in front of the transcript: a window at the top shows one step of them. */
+export function windowAfterPrepend({ start, end }: TranscriptWindowBounds, added: number, total: number): TranscriptWindowBounds {
+ const moved = { start: start === 0 ? Math.max(0, added - TRANSCRIPT_WINDOW_SIZE) : start + added, end: end === null ? null : end + added };
+ return capWindowEnd(moved, total);
+}
+
+/** The window that puts a remembered row back on screen, drawing at most `TRANSCRIPT_WINDOW_MAX` rows. */
+export function restoreWindow(total: number, rowIndex: number, rememberedStart: number | undefined): TranscriptWindowBounds {
+ const start = Math.max(0, rowIndex - TRANSCRIPT_WINDOW_SIZE, Math.min(rowIndex, rememberedStart ?? rowIndex, tailWindowStart(total)));
+ return capWindowEnd({ start, end: null }, total);
+}
+
export function focusWindowRange(
total: number,
targetIndex: number,
diff --git a/src/state/message-history.test.ts b/src/state/message-history.test.ts
new file mode 100644
index 0000000000..4d8dc288fb
--- /dev/null
+++ b/src/state/message-history.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+import { HELD_AFTER_LEAVING, HELD_FOR_PLACE, trimmedHeld } from "./message-history";
+import { initialState, reducer, type Bot, type Group, type Message } from "./store";
+
+const message = (index: number) => ({ id: `m${index}`, at: index, role: "user", kind: "text", text: `m${index}` }) as never as Message;
+const thread = (count: number) => Array.from({ length: count }, (_, index) => message(index));
+const ids = (owner: { messages: Message[] }) => owner.messages.map((row) => row.id);
+
+const bot = (fields: Partial<Bot> = {}) => ({ id: "bot-1", threadId: "thread-1", messages: thread(3_000), hasMore: false, ...fields }) as never as Bot;
+const other = { id: "bot-2", threadId: "thread-2", messages: thread(10), hasMore: false } as never as Bot;
+const away = (owner: Bot) => ({ ...initialState, bots: [owner, other], selectedId: other.id, activeView: "chat" as const });
+
+describe("letting go of paged rows when a conversation is left", () => {
+ it("keeps the newest rows of a conversation the reader left and lets it page again", () => {
+ const left = reducer(away(bot()), { type: "trimHeldMessages", threadId: "thread-1" });
+ const trimmed = left.bots[0]!;
+ expect(trimmed.messages).toHaveLength(HELD_AFTER_LEAVING);
+ expect(ids(trimmed).at(-1)).toBe("m2999");
+ expect(trimmed.hasMore).toBe(true);
+ expect(left.bots[1]).toBe(other);
+ });
+
+ it("keeps the reader's place when it lies close enough to the end", () => {
+ const near = 3_000 - HELD_FOR_PLACE;
+ expect(ids(trimmedHeld(bot(), `m${near}`))[0]).toBe(`m${near}`);
+ expect(trimmedHeld(bot(), `m${near - 1}`).messages).toHaveLength(HELD_AFTER_LEAVING);
+ });
+
+ it("never cuts off the pinned message or the leaf of the branch shown", () => {
+ expect(ids(trimmedHeld(bot({ pinnedMessageId: "m2500" })))[0]).toBe("m2500");
+ expect(trimmedHeld(bot({ pinnedMessageId: "m10" })).messages).toHaveLength(3_000);
+ expect(trimmedHeld(bot({ activeLeafId: "m100" })).messages).toHaveLength(3_000);
+ });
+
+ it("leaves the conversation on screen and a short one untouched", () => {
+ const shown = { ...initialState, bots: [bot()], selectedId: "bot-1", activeView: "chat" as const };
+ expect(reducer(shown, { type: "trimHeldMessages", threadId: "thread-1" })).toBe(shown);
+ const short = away(bot({ messages: thread(HELD_AFTER_LEAVING) }));
+ expect(reducer(short, { type: "trimHeldMessages", threadId: "thread-1" })).toBe(short);
+ });
+
+ it("trims a room the reader left the same way", () => {
+ const room = { id: "room-1", threadId: "room-thread", messages: thread(900), hasMore: false } as never as Group;
+ const left = reducer({ ...initialState, groups: [room], bots: [other], selectedId: other.id }, { type: "trimHeldMessages", threadId: "room-thread" });
+ expect(left.groups[0]!.messages).toHaveLength(HELD_AFTER_LEAVING);
+ expect(left.groups[0]!.hasMore).toBe(true);
+ });
+
+ it("drops an older page asked for before rows that were let go since, so no gap opens", () => {
+ const left = reducer(away(bot()), { type: "trimHeldMessages", threadId: "thread-1" });
+ const stale = reducer(left, { type: "olderMessages", threadId: "thread-1", generation: 0, before: "m0", messages: [message(-1)], hasMore: false });
+ expect(ids(stale.bots[0]!)).toEqual(ids(left.bots[0]!));
+ const fresh = reducer(left, { type: "olderMessages", threadId: "thread-1", generation: 0, before: "m2800", messages: thread(2_800).slice(-200), hasMore: true });
+ expect(ids(fresh.bots[0]!)[0]).toBe("m2600");
+ expect(fresh.bots[0]!.messages).toHaveLength(400);
+ });
+});
diff --git a/src/state/message-history.ts b/src/state/message-history.ts
index c373c17464..177cd9b63a 100644
--- a/src/state/message-history.ts
+++ b/src/state/message-history.ts
@@ -6,12 +6,17 @@ import type { Action, AppState, Message } from "./store";
export const MESSAGE_PAGE_SIZE = 200;
type OlderMessages = Extract<Action, { type: "olderMessages" }>;
type LoadOlderMessages = Extract<Action, { type: "loadOlderMessages" }>;
+type TrimHeldMessages = Extract<Action, { type: "trimHeldMessages" }>;
+type HeldOwner = { id: string; messages: Message[]; threadId: string; hasMore?: boolean; activeLeafId?: string | null; pinnedMessageId?: string };
export function reduceOlderMessages(state: AppState, action: OlderMessages): AppState {
const { [action.threadId]: _done, ...loadingOlder } = state.loadingOlder;
if ((state.transcriptGeneration[action.threadId] ?? 0) !== action.generation) return { ...state, loadingOlder };
- const prepend = <T extends { messages: Message[]; threadId: string; hasMore?: boolean }>(owner: T): T => {
- const held = new Set(owner.messages.map((message) => message.id));
+ const prepend = <T extends HeldOwner>(owner: T): T => {
+ // A page asked for before rows that have since been let go would leave a gap: the reader pages again instead.
+ if (action.before !== undefined && owner.messages[0]?.id !== action.before) return owner;
+ const page = new Set(action.messages.map((message) => message.id));
+ const held = new Set(owner.messages.filter((message) => page.has(message.id)).map((message) => message.id));
return {
...owner,
messages: [...action.messages.filter((message) => !held.has(message.id)), ...owner.messages],
@@ -25,6 +30,41 @@ export function reduceOlderMessages(state: AppState, action: OlderMessages): App
return { ...state, loadingOlder, bots, groups, unreadDivider };
}
+/** Rows a conversation keeps once the reader has left it, and the most it keeps to put a reader's place back. */
+export const HELD_AFTER_LEAVING = MESSAGE_PAGE_SIZE;
+export const HELD_FOR_PLACE = 3 * MESSAGE_PAGE_SIZE;
+
+/** The newest rows of `owner`, from `keepFromId` when that is close enough to the end, never cutting off its pinned
+ * message or the leaf of the branch it shows. */
+export function trimmedHeld<T extends HeldOwner>(owner: T, keepFromId?: string): T {
+ const total = owner.messages.length;
+ let from = total - HELD_AFTER_LEAVING;
+ if (from <= 0) return owner;
+ for (const id of [keepFromId, owner.activeLeafId, owner.pinnedMessageId]) {
+ const at = id ? owner.messages.findIndex((message) => message.id === id) : -1;
+ if (at < 0 || at >= from) continue;
+ if (id !== keepFromId && total - at > HELD_FOR_PLACE) return owner;
+ if (total - at <= HELD_FOR_PLACE) from = at;
+ }
+ return from > 0 ? { ...owner, messages: owner.messages.slice(from), hasMore: true } : owner;
+}
+
+export function reduceTrimHeldMessages(state: AppState, { threadId, keepFromId }: TrimHeldMessages): AppState {
+ const shown = state.activeView === "chat" &&
+ [...state.bots, ...state.groups].some((owner) => owner.id === state.selectedId && owner.threadId === threadId);
+ if (shown) return state;
+ let changed = false;
+ const trim = <T extends HeldOwner>(owner: T): T => {
+ if (owner.threadId !== threadId) return owner;
+ const next = trimmedHeld(owner, keepFromId);
+ changed ||= next !== owner;
+ return next;
+ };
+ const bots = state.bots.map(trim);
+ const groups = state.groups.map(trim);
+ return changed ? { ...state, bots, groups } : state;
+}
+
export function loadOlderPage(action: LoadOlderMessages, current: AppState, inFlight: Set<string>,
dispatch: (action: Action) => void, showError: (error: unknown) => void): void {
if (inFlight.has(action.threadId)) return;
@@ -40,9 +80,9 @@ export function loadOlderPage(action: LoadOlderMessages, current: AppState, inFl
void api<{ messages: Message[]; hasMore?: boolean }>(
`/api/threads/${action.threadId}/messages?limit=${MESSAGE_PAGE_SIZE}&before=${encodeURIComponent(before)}`,
).finally(() => inFlight.delete(action.threadId)).then((page) => dispatch({
- type: "olderMessages", threadId: action.threadId, generation, messages: page.messages ?? [], hasMore: Boolean(page.hasMore),
+ type: "olderMessages", threadId: action.threadId, generation, before, messages: page.messages ?? [], hasMore: Boolean(page.hasMore),
})).catch((error) => {
- dispatch({ type: "olderMessages", threadId: action.threadId, generation, messages: [], hasMore: true });
+ dispatch({ type: "olderMessages", threadId: action.threadId, generation, before, messages: [], hasMore: true });
showError(error);
});
}
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 6018718807..c63c5d6cea 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -1,6 +1,6 @@
import { cloudAsleep, onCloudPower } from "../lib/cloud-power";
import { api, ApiError, retryRequest, snapshotArrays } from "./api";
-import { loadOlderPage, MESSAGE_PAGE_SIZE, reduceOlderMessages } from "./message-history";
+import { loadOlderPage, MESSAGE_PAGE_SIZE, reduceOlderMessages, reduceTrimHeldMessages } from "./message-history";
export { MESSAGE_PAGE_SIZE } from "./message-history";
import { addForkOptimistic, reduceForkPanel, removeForkOptimistic, runForkEffect, type ForkPanelAction, type ForkPanelState } from "./fork-panel";
import { use, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
@@ -673,8 +673,8 @@ export type Action =
| { type: "editMessage"; botId: string; messageId: string; text: string; threadId?: string; sendId?: string }
| { type: "switchBranch"; botId: string; messageId: string; threadId?: string }
| { type: "threadActive"; threadId: string; activeLeafId: string }
- | { type: "loadOlderMessages"; threadId: string }
- | { type: "olderMessages"; threadId: string; generation: number; messages: Message[]; hasMore: boolean }
+ | { type: "loadOlderMessages"; threadId: string } | { type: "trimHeldMessages"; threadId: string; keepFromId?: string }
+ | { type: "olderMessages"; threadId: string; generation: number; before?: string; messages: Message[]; hasMore: boolean }
| { type: "answerCard"; botId: string; messageId: string; answer: string; threadId?: string; groupId?: string }
| { type: "answerCardFailed"; botId: string; messageId: string; answer: string; threadId?: string; groupId?: string }
| { type: "dismissCard"; botId: string; messageId: string; threadId?: string; groupId?: string }
@@ -909,8 +909,8 @@ export function reducer(state: AppState, action: Action): AppState {
return state.loadingOlder[action.threadId]
? state
: { ...state, loadingOlder: { ...state.loadingOlder, [action.threadId]: true } };
- case "olderMessages":
- return reduceOlderMessages(state, action);
+ case "olderMessages": return reduceOlderMessages(state, action);
+ case "trimHeldMessages": return reduceTrimHeldMessages(state, action);
case "sectionDeleted":
return {
...state, sections: action.sections,