Skip to content

Commit 4d61969

Browse files
wesbillmanBrainPinky
authored
Rework desktop message-timeline scrolling: de-virtualize + native overflow-anchor (#1338)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co>
1 parent c1d6f3f commit 4d61969

20 files changed

Lines changed: 876 additions & 1712 deletions

‎desktop/playwright.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ export default defineConfig({
5454
"**/reminders.spec.ts",
5555
"**/virtualization.spec.ts",
5656
"**/scroll-history.spec.ts",
57+
"**/cold-switch-longtask.perf.ts",
58+
"**/timeline-no-shift.spec.ts",
5759
],
5860
use: {
5961
...devices["Desktop Chrome"],

‎desktop/src/features/channels/ui/ChannelScreen.tsx‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as React from "react";
22
import { useAppShell } from "@/app/AppShellContext";
3+
import { cacheSearchHitEvent } from "@/app/navigation/searchHitEventCache";
34
import { useAppNavigation } from "@/app/navigation/useAppNavigation";
45
import { useActiveChannelHeader } from "@/features/channels/useActiveChannelHeader";
56
import { useChannelPaneHandlers } from "@/features/channels/useChannelPaneHandlers";
@@ -50,7 +51,7 @@ import { useChannelTyping } from "@/features/messages/useChannelTyping";
5051
import type { TimelineMessage } from "@/features/messages/types";
5152
import { useUsersBatchQuery } from "@/features/profile/hooks";
5253
import { mergeCurrentProfileIntoLookup } from "@/features/profile/lib/identity";
53-
import type { RespondToMode } from "@/shared/api/types";
54+
import type { RelayEvent, RespondToMode, SearchHit } from "@/shared/api/types";
5455
import { useChannelFind } from "@/features/search/useChannelFind";
5556
import { ViewLoadingFallback } from "@/shared/ui/ViewLoadingFallback";
5657
import { AgentSessionProvider } from "@/shared/context/AgentSessionContext";
@@ -242,13 +243,26 @@ export function ChannelScreen({
242243
const deleteMessageMutation = useDeleteMessageMutation(activeChannel);
243244
const editMessageMutation = useEditMessageMutation(activeChannel);
244245
const joinChannelMutation = useJoinChannelMutation(activeChannelId);
246+
const [findTargetEvents, setFindTargetEvents] = React.useState<RelayEvent[]>(
247+
[],
248+
);
249+
// biome-ignore lint/correctness/useExhaustiveDependencies: clear spliced find results exactly when the active channel changes.
250+
React.useEffect(() => {
251+
setFindTargetEvents([]);
252+
}, [activeChannelId]);
245253
const resolvedMessages = React.useMemo(() => {
246254
const currentMessages = messagesQuery.data ?? [];
247-
if (!activeChannel || targetMessageEvents.length === 0) {
255+
const extraEvents = [...targetMessageEvents, ...findTargetEvents];
256+
if (!activeChannel || extraEvents.length === 0) {
248257
return currentMessages;
249258
}
250-
return targetMessageEvents.reduce(mergeMessages, currentMessages);
251-
}, [activeChannel, messagesQuery.data, targetMessageEvents]);
259+
return extraEvents.reduce(mergeMessages, currentMessages);
260+
}, [
261+
activeChannel,
262+
findTargetEvents,
263+
messagesQuery.data,
264+
targetMessageEvents,
265+
]);
252266
const messageAuthorPubkeys = React.useMemo(
253267
() => collectMessageAuthorPubkeys(resolvedMessages),
254268
[resolvedMessages],
@@ -417,9 +431,18 @@ export function ChannelScreen({
417431
resolvedMessages,
418432
],
419433
);
434+
const handleFindSearchHit = React.useCallback((hit: SearchHit) => {
435+
const event = cacheSearchHitEvent(hit);
436+
setFindTargetEvents((currentEvents) =>
437+
currentEvents.some((currentEvent) => currentEvent.id === event.id)
438+
? currentEvents
439+
: [...currentEvents, event],
440+
);
441+
}, []);
420442
const channelFind = useChannelFind({
421443
channelId: activeChannelId,
422444
messages: timelineMessages,
445+
onSearchHit: handleFindSearchHit,
423446
});
424447
const {
425448
firstUnreadMessageId,

‎desktop/src/features/messages/hooks.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ type MessageQueryContext = {
4848
queryKey: ReturnType<typeof channelMessagesKey>;
4949
};
5050

51-
const CHANNEL_HISTORY_LIMIT = 300;
51+
const CHANNEL_HISTORY_LIMIT = 60;
5252

5353
function getLocalRenderKey(message: RelayEvent) {
5454
return message.localKey ?? message.id;
@@ -304,7 +304,7 @@ export function useChannelSubscription(channel: Channel | null) {
304304

305305
cleanup = dispose;
306306
// No post-subscribe history refetch: useChannelMessagesQuery already
307-
// loaded the latest CHANNEL_HISTORY_LIMIT (300) events, and the live
307+
// loaded the latest CHANNEL_HISTORY_LIMIT events, and the live
308308
// subscription itself backfills up to 50 most-recent events via its
309309
// initial REQ (buildChannelFilter(id, 50)). Both write into the same
310310
// channelMessagesKey cache, so any window between the two REQs is

‎desktop/src/features/messages/lib/pageOlderMessages.ts‎

Lines changed: 24 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,10 @@ export const MIN_TOP_LEVEL_ROWS_PER_FETCH = 30;
2222

2323
// Hard ceiling on relay pages fetched in one pass. On reply-heavy channels a
2424
// batch yields only a few visible rows, so the row floor alone could dig through
25-
// hundreds of messages behind one spinner and commit them at once (a sudden
26-
// "flood" with a tiny scrollbar). Capping per-pass keeps each fetch a bounded
27-
// page; the scroll observer re-arms to page further while in view.
25+
// hundreds of messages behind one spinner. Capping per-pass keeps each fetch a
26+
// bounded page; the scroll observer re-arms to page further while in view.
2827
const MAX_BATCHES_PER_FETCH = 3;
2928

30-
// Yield a frame so the rows just merged paint before the next round-trip;
31-
// otherwise a multi-batch pass renders as one bulk commit at the loop's end.
32-
function yieldToPaint(): Promise<void> {
33-
return new Promise((resolve) => {
34-
if (typeof requestAnimationFrame === "function") {
35-
requestAnimationFrame(() => resolve());
36-
} else {
37-
setTimeout(resolve, 0);
38-
}
39-
});
40-
}
41-
4229
export type PageOlderResult = {
4330
/** False once a short relay page proves history is exhausted. */
4431
hasOlderMessages: boolean;
@@ -68,16 +55,15 @@ export async function pageOlderMessagesUntilRowFloor(
6855
let hasOlderMessages = true;
6956
let batchesFetched = 0;
7057

71-
while (hasOlderMessages && shouldContinue()) {
72-
const before = queryClient.getQueryData<RelayEvent[]>(queryKey) ?? [];
73-
if (before.length === 0) {
74-
break;
75-
}
58+
// Accumulate every batch of this pass and commit to the cache once at the
59+
// end. Committing per batch paints the timeline in several small steps under
60+
// one spinner — on reply-heavy windows each 200-event batch adds only a few
61+
// visible rows, so the user sees the loader dribble messages in 1-5 at a
62+
// time. One commit = one bounded growth step.
63+
const fetched: RelayEvent[] = [];
64+
let oldestTimestamp = baseline[0].created_at;
7665

77-
// `until` is inclusive — the relay returns the boundary message again, but
78-
// sortMessages dedupes by id. Subtracting 1 risks skipping same-second
79-
// messages.
80-
const oldestTimestamp = before[0].created_at;
66+
while (hasOlderMessages && shouldContinue()) {
8167
const olderMessages = await relayClient.fetchChannelHistoryBefore(
8268
channelId,
8369
oldestTimestamp,
@@ -97,25 +83,24 @@ export async function pageOlderMessagesUntilRowFloor(
9783
}
9884

9985
if (olderMessages.length > 0) {
100-
queryClient.setQueryData<RelayEvent[]>(queryKey, (current = []) =>
101-
mergeTimelineHistoryMessages(current, olderMessages),
102-
);
103-
void backfillAuxForMessages(queryClient, channelId, olderMessages);
86+
fetched.push(...olderMessages);
10487
}
10588

10689
// Progress guard, not exhaustion: if the oldest timestamp didn't move back
10790
// (empty page, or all-duplicate), stop this pass to avoid re-fetching the
10891
// same `until`.
109-
const oldestAfterMerge = (queryClient.getQueryData<RelayEvent[]>(
110-
queryKey,
111-
) ?? [])[0]?.created_at;
112-
if (oldestAfterMerge === undefined || oldestAfterMerge >= oldestTimestamp) {
92+
const oldestFetched = fetched.reduce(
93+
(min, event) => (event.created_at < min ? event.created_at : min),
94+
oldestTimestamp,
95+
);
96+
if (oldestFetched >= oldestTimestamp) {
11397
break;
11498
}
99+
oldestTimestamp = oldestFetched;
115100

116101
const rowsGained =
117102
countTopLevelTimelineRows(
118-
queryClient.getQueryData<RelayEvent[]>(queryKey) ?? [],
103+
mergeTimelineHistoryMessages(baseline, fetched),
119104
) - baselineRowCount;
120105
if (rowsGained >= MIN_TOP_LEVEL_ROWS_PER_FETCH) {
121106
break;
@@ -124,8 +109,13 @@ export async function pageOlderMessagesUntilRowFloor(
124109
if (batchesFetched >= MAX_BATCHES_PER_FETCH) {
125110
break;
126111
}
112+
}
127113

128-
await yieldToPaint();
114+
if (fetched.length > 0 && shouldContinue()) {
115+
queryClient.setQueryData<RelayEvent[]>(queryKey, (current = []) =>
116+
mergeTimelineHistoryMessages(current, fetched),
117+
);
118+
void backfillAuxForMessages(queryClient, channelId, fetched);
129119
}
130120

131121
return { hasOlderMessages };

0 commit comments

Comments
 (0)