fix(desktop): paint cached channel revisits immediately

Channel revisits showed a skeleton on every A-B switch because the
on-subscribe refresh invalidates channel-messages on each mount
(bypassing staleTime) and the loading selector had no path to paint
cached rows. Latch settled channels per-channel (guarded by cache
presence so GC-collected channels still cold-load), render the live
snapshot synchronously on settled revisits, never render empty/intro
over known rows, and align channel-window gcTime (60min) with
channel-messages.

Co-authored-by: Meeseeks <2e96988f190ed1bd3c568760103aa4cadb2bc6195b832e252c984392c89039bd@buzz.block.builderlab.xyz>
Co-authored-by: Wes <wesbillman@users.noreply.github.com>
Signed-off-by: Wes <wesbillman@users.noreply.github.com>
This commit is contained in:
Meeseeks
2026-08-11 09:10:14 -06:00
committed by Rick
parent 7eb8cc5a5f
commit b820030e0c
7 changed files with 160 additions and 62 deletions

View File

@@ -613,9 +613,10 @@ export function ChannelScreen({
setThreadReplyTargetId,
setThreadScrollTargetId,
});
const settledChannelIdRef = React.useRef<string | null>(null);
const settledChannelIdsRef = React.useRef<ReadonlySet<string>>(new Set());
const hasSettledThisChannel =
activeChannelId !== null && settledChannelIdRef.current === activeChannelId;
activeChannelId !== null &&
settledChannelIdsRef.current.has(activeChannelId);
const timelineLoadingNow =
activeChannel !== null &&
activeChannel.channelType !== "forum" &&
@@ -628,18 +629,18 @@ export function ChannelScreen({
},
hasSettledThisChannel,
);
const { settledChannelId, isLoading: isTimelineLoading } =
resolveTimelineLoadingLatch(
settledChannelIdRef.current,
activeChannelId,
timelineLoadingNow,
);
settledChannelIdRef.current = settledChannelId;
const loadingLatch = resolveTimelineLoadingLatch(
settledChannelIdsRef.current,
activeChannelId,
timelineLoadingNow,
messagesQuery.data !== undefined,
);
settledChannelIdsRef.current = loadingLatch.settledChannelIds;
const { welcomeKickoffStage, welcomeKickoffSettingUp } =
useWelcomeKickoffStagePresence(
activeChannel,
timelineMessages,
isTimelineLoading,
loadingLatch.isLoading,
);
const resetComposerTargets = React.useCallback(
(_channelId: string | null) => {
@@ -676,7 +677,7 @@ export function ChannelScreen({
clearOptimisticThreadOverride,
editTargetId,
editTargetMessage,
isTimelineLoading,
isTimelineLoading: loadingLatch.isLoading,
openThreadHeadId,
openThreadHeadMessage,
setEditTargetId,
@@ -896,7 +897,7 @@ export function ChannelScreen({
isFollowingThread={isNotifiedForEffectiveThread}
isSending={sendMessageMutation.isPending}
isSinglePanelView={isSinglePanelView}
isTimelineLoading={isTimelineLoading}
isTimelineLoading={loadingLatch.isLoading}
messages={timelineMessages}
threadSummaries={threadSummaries}
onCancelEdit={handleCancelEdit}

View File

@@ -223,6 +223,7 @@ export function useChannelWindowQuery(channel: Channel | null) {
queryClient.getQueryData<ChannelWindowStore>(queryKey) ??
emptyChannelWindowStore(),
staleTime: Number.POSITIVE_INFINITY,
gcTime: 60 * 60 * 1_000,
});
}

View File

@@ -1,7 +1,10 @@
import assert from "node:assert/strict";
import test from "node:test";
import { selectTimelineLoadingState } from "./timelineLoadingState.ts";
import {
resolveTimelineLoadingLatch,
selectTimelineLoadingState,
} from "./timelineLoadingState.ts";
const settled = {
isPending: false,
@@ -120,41 +123,62 @@ test("settled channel with rows mid-refetch is not loading", () => {
);
});
import { resolveTimelineLoadingLatch } from "./timelineLoadingState.ts";
test("latch: loading on first entry to a channel", () => {
const r = resolveTimelineLoadingLatch(null, "chan-a", true);
const r = resolveTimelineLoadingLatch(new Set(), "chan-a", true, false);
assert.equal(r.isLoading, true);
assert.equal(r.settledChannelId, null);
assert.deepEqual([...r.settledChannelIds], []);
});
test("latch: settles when loadingNow turns false, recording the channel", () => {
const r = resolveTimelineLoadingLatch(null, "chan-a", false);
const r = resolveTimelineLoadingLatch(new Set(), "chan-a", false, true);
assert.equal(r.isLoading, false);
assert.equal(r.settledChannelId, "chan-a");
assert.deepEqual([...r.settledChannelIds], ["chan-a"]);
});
test("latch: background refetch blip stays loaded once settled", () => {
// settled for chan-a, then loadingNow blips true (isFetching) — must NOT
// re-show the skeleton (the bounce Wes reported).
const r = resolveTimelineLoadingLatch("chan-a", "chan-a", true);
const r = resolveTimelineLoadingLatch(
new Set(["chan-a"]),
"chan-a",
true,
true,
);
assert.equal(r.isLoading, false);
assert.equal(r.settledChannelId, "chan-a");
});
test("latch: switching channels resets and loads the new one", () => {
const r = resolveTimelineLoadingLatch("chan-a", "chan-b", true);
test("latch: remembers both channels across an A-B-A revisit", () => {
const settledChannels = new Set(["chan-a", "chan-b"]);
assert.equal(
resolveTimelineLoadingLatch(settledChannels, "chan-a", true, true)
.isLoading,
false,
);
assert.equal(
resolveTimelineLoadingLatch(settledChannels, "chan-b", true, true)
.isLoading,
false,
);
});
test("latch: a settled channel goes cold after its query cache is collected", () => {
const r = resolveTimelineLoadingLatch(
new Set(["chan-a"]),
"chan-a",
true,
false,
);
assert.equal(r.isLoading, true);
assert.equal(r.settledChannelId, "chan-a"); // not yet settled for b
});
test("latch: no active channel passes loadingNow through untouched", () => {
assert.equal(
resolveTimelineLoadingLatch("chan-a", null, true).isLoading,
resolveTimelineLoadingLatch(new Set(["chan-a"]), null, true, false)
.isLoading,
true,
);
assert.equal(
resolveTimelineLoadingLatch("chan-a", null, false).isLoading,
resolveTimelineLoadingLatch(new Set(["chan-a"]), null, false, false)
.isLoading,
false,
);
});

View File

@@ -41,26 +41,27 @@ export function selectTimelineLoadingState(
}
/**
* Monotonic loading latch keyed by channel. Once a channel has settled (loaded),
* `loadingNow` blipping true again (a background refetch) must not re-show the
* skeleton — that re-flip is the visible skeleton bounce on entry. A different
* channel id resets the latch so the new channel loads fresh.
* Per-channel loading latch. Once a channel has settled, a background refetch
* must not re-show its skeleton, even after visiting another channel. The
* `hasCachedData` guard makes an entry forgettable in practice: if React Query
* has garbage-collected that channel, a later cold load still shows loading.
*/
export function resolveTimelineLoadingLatch(
settledChannelId: string | null,
settledChannelIds: ReadonlySet<string>,
activeChannelId: string | null,
loadingNow: boolean,
): { settledChannelId: string | null; isLoading: boolean } {
hasCachedData: boolean,
): { settledChannelIds: ReadonlySet<string>; isLoading: boolean } {
if (activeChannelId === null) {
return { settledChannelId, isLoading: loadingNow };
return { settledChannelIds, isLoading: loadingNow };
}
if (settledChannelId === activeChannelId) {
// Already settled for this channel — stay loaded through refetch blips.
return { settledChannelId, isLoading: false };
if (settledChannelIds.has(activeChannelId) && hasCachedData) {
return { settledChannelIds, isLoading: false };
}
if (!loadingNow) {
// First settle for this channel; latch it.
return { settledChannelId: activeChannelId, isLoading: false };
const nextSettledChannelIds = new Set(settledChannelIds);
nextSettledChannelIds.add(activeChannelId);
return { settledChannelIds: nextSettledChannelIds, isLoading: false };
}
return { settledChannelId, isLoading: true };
return { settledChannelIds, isLoading: true };
}

View File

@@ -14,6 +14,7 @@ import {
selectLatestMessageKey,
selectTimelineBodySurface,
selectTimelineIntroSurface,
selectTimelineRenderSource,
} from "./timelineSnapshot.ts";
// Local-midnight unix-second timestamps so isSameDay (local time) is stable
@@ -420,15 +421,14 @@ test("timeline-body-surface: loading and deferred-pending both paint the single
);
});
test("timeline-body-surface: first deferred message preserves a persistent channel intro", () => {
test("timeline-body-surface: known live rows suppress empty/intro until deferred rows commit", () => {
assert.equal(
selectTimelineBodySurface({
deferredCount: 0,
hasPersistentIntro: true,
isLoading: false,
liveCount: 1,
}),
"empty",
"skeleton",
);
});
@@ -474,6 +474,50 @@ test("deferred-snapshot: fresh when channel ids match", () => {
);
});
test("timeline-render-source: cached revisit paints live rows while old channel is deferred", () => {
assert.equal(
selectTimelineRenderSource({
deferredChannelId: "chan-b",
liveChannelId: "chan-a",
preferLiveSnapshot: true,
}),
"live",
);
});
test("timeline-render-source: settled empty revisit proves emptiness without waiting", () => {
assert.equal(
selectTimelineRenderSource({
deferredChannelId: "chan-b",
liveChannelId: "chan-a",
preferLiveSnapshot: true,
}),
"live",
);
});
test("timeline-render-source: cold switch never paints the old channel", () => {
assert.equal(
selectTimelineRenderSource({
deferredChannelId: "chan-a",
liveChannelId: "chan-b",
preferLiveSnapshot: false,
}),
null,
);
});
test("timeline-render-source: same-channel deferred rows remain the normal path", () => {
assert.equal(
selectTimelineRenderSource({
deferredChannelId: "chan-a",
liveChannelId: "chan-a",
preferLiveSnapshot: true,
}),
"deferred",
);
});
test("timeline-body-surface: stale deferred channel snapshot paints skeleton instead of old list", () => {
const isStale = isDeferredTimelineSnapshotStale({
deferredSnapshot: { channelId: "chan-a" },

View File

@@ -183,14 +183,37 @@ export function selectDeferredListRenderState(
export type TimelineBodySurface = "skeleton" | "empty" | "list";
export type TimelineRenderSource = "deferred" | "live" | null;
/**
* Choose only a snapshot that belongs to the active channel. A previously
* settled revisit may paint its live React-Query cache immediately; a cold
* switch must wait for the deferred snapshot rather than leaking old rows.
*/
export function selectTimelineRenderSource({
deferredChannelId,
liveChannelId,
preferLiveSnapshot,
}: {
deferredChannelId: string | null;
liveChannelId: string | null;
preferLiveSnapshot: boolean;
}): TimelineRenderSource {
if (deferredChannelId === liveChannelId) {
return "deferred";
}
if (preferLiveSnapshot) {
return "live";
}
return null;
}
export function selectTimelineBodySurface({
deferredCount,
hasPersistentIntro = false,
isLoading,
liveCount,
}: {
deferredCount: number;
hasPersistentIntro?: boolean;
isLoading: boolean;
liveCount: number;
}): TimelineBodySurface {
@@ -200,10 +223,10 @@ export function selectTimelineBodySurface({
const renderState = selectDeferredListRenderState(deferredCount, liveCount);
if (renderState === "pending") {
// A channel/DM intro is already meaningful stable content. Preserve it
// while React's deferred snapshot catches up to the first live message;
// replacing it with a skeleton makes an append look like a page reload.
return hasPersistentIntro ? "empty" : "skeleton";
// Live rows are authoritative proof that the channel is not empty. Keep the
// single loading surface until those same-channel rows commit; never flash
// an empty/intro surface over known content.
return "skeleton";
}
return renderState;
}

View File

@@ -1,10 +1,10 @@
import * as React from "react";
import {
isDeferredTimelineSnapshotStale,
isRenderedTimelineBehindHistoryPrepend,
selectTimelineBodySurface,
selectTimelineIntroSurface,
selectTimelineRenderSource,
} from "@/features/messages/lib/timelineSnapshot";
import { preloadTimelineImages } from "@/features/messages/lib/timelineImagePreload";
import type { TimelineMessage } from "@/features/messages/types";
@@ -253,7 +253,18 @@ const MessageTimelineBase = React.forwardRef<
liveSnapshot,
EMPTY_TIMELINE_SNAPSHOT,
);
const deferredMessages = deferredSnapshot.messages;
const renderSource = selectTimelineRenderSource({
deferredChannelId: deferredSnapshot.channelId,
liveChannelId: liveSnapshot.channelId,
preferLiveSnapshot: !isLoading,
});
const renderedSnapshot =
renderSource === "live"
? liveSnapshot
: renderSource === "deferred"
? deferredSnapshot
: EMPTY_TIMELINE_SNAPSHOT;
const deferredMessages = renderedSnapshot.messages;
const imagePreloadStateRef = React.useRef({
activeImages: new Set<HTMLImageElement>(),
requestedUrls: new Set<string>(),
@@ -261,11 +272,8 @@ const MessageTimelineBase = React.forwardRef<
React.useEffect(() => {
preloadTimelineImages(messages, imagePreloadStateRef.current);
}, [messages]);
const isDeferredSnapshotStale = isDeferredTimelineSnapshotStale({
deferredSnapshot,
liveSnapshot,
});
const isRenderPending = deferredSnapshot !== liveSnapshot;
const isDeferredSnapshotStale = renderSource === null;
const isRenderPending = renderedSnapshot !== liveSnapshot;
const scrollRestorationId = targetMessageId
? `message-timeline:${channelId ?? "none"}:target:${targetMessageId}`
: `message-timeline:${channelId ?? "none"}`;
@@ -287,10 +295,6 @@ const MessageTimelineBase = React.forwardRef<
const timelineBodySurface = selectTimelineBodySurface({
deferredCount: deferredMessages.length,
hasPersistentIntro:
channelIntro !== null ||
directMessageIntro !== null ||
pinnedIntro != null,
isLoading: isLoading || isDeferredSnapshotStale,
liveCount: messages.length,
});
@@ -331,7 +335,7 @@ const MessageTimelineBase = React.forwardRef<
} = useSettleGatedPrependMessages({
channelId,
messages: bufferedTimeline.messages,
meta: deferredSnapshot.historyExhausted,
meta: renderedSnapshot.historyExhausted,
scrollElementRef: activeScrollContainerRef,
});