Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

perf(community): instant channel switch — paint & scroll a warm tail on first frame

Shelly#38636955f24fe3c1
diff --git a/src/web/src/hooks/community/use-messages.loading-state.test.ts b/src/web/src/hooks/community/use-messages.loading-state.test.ts
index 746614666..f1a368674 100644
--- a/src/web/src/hooks/community/use-messages.loading-state.test.ts
+++ b/src/web/src/hooks/community/use-messages.loading-state.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
import { useMessages } from "./use-messages"
const apiFetchMock = vi.fn()
@@ -34,8 +35,18 @@ function Capture({ onResult, channelId, lastReadMessageId }: {
function renderCapture(
onResult: (r: { isLoading: boolean; messages: unknown[] }) => void,
lastReadMessageId: string | null | undefined,
+ seedTail?: { id: string; seq: number }[],
) {
const queryClient = new QueryClient()
+ // Simulate a warm channel: the persisted `channelMessages` cache is already
+ // hydrated with a newest-tail window before this hook mounts (bootstrap/read
+ // snapshot not yet resolved).
+ if (seedTail) {
+ queryClient.setQueryData(communityKeys.channelMessages("ch_new"), {
+ pages: [{ messages: seedTail, hasMore: false, latestSeq: seedTail.at(-1)?.seq ?? 0 }],
+ pageParams: [{ mode: "newest" }],
+ })
+ }
act(() => {
TestRenderer.create(
React.createElement(
@@ -69,3 +80,32 @@ describe("useMessages — isLoading while the anchor snapshot is unresolved", ()
expect(latest?.isLoading).toBe(true)
})
})
+
+describe("useMessages — instant channel switch: warm cache paints without waiting on the anchor", () => {
+ it("reports isLoading: false when the anchor is unresolved but the channelMessages cache is already hydrated", () => {
+ let latest: { isLoading: boolean; messages: unknown[] } | undefined
+ // Warm switch: anchor snapshot still resolving (`lastReadMessageId:
+ // undefined`, query disabled) BUT the persisted newest-tail is already in
+ // cache. The rows must paint now — no skeleton, no network wait.
+ renderCapture((r) => { latest = r }, undefined, [
+ { id: "m_1", seq: 1 },
+ { id: "m_2", seq: 2 },
+ ])
+
+ expect(latest?.isLoading).toBe(false)
+ expect(latest?.messages).toHaveLength(2)
+ // Paints straight from cache — no fetch fired while the query is disabled.
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+
+ it("still reports isLoading: true (skeleton) on a cold cache with the anchor unresolved", () => {
+ let latest: { isLoading: boolean; messages: unknown[] } | undefined
+ // Cold channel: anchor unresolved AND no hydrated tail → skeleton, exactly
+ // as before, so the decoupling never turns a genuine cold load into a flash
+ // of empty content.
+ renderCapture((r) => { latest = r }, undefined)
+
+ expect(latest?.isLoading).toBe(true)
+ expect(latest?.messages).toEqual([])
+ })
+})
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 396d17225..e65afe9c1 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -498,13 +498,25 @@ function useMessagesInner(
return {
...query,
- // While the anchor snapshot is still resolving, the query is `enabled:
- // false` — TanStack forces `isFetching` to `false` in that state, which
- // makes the native `isLoading = isPending && isFetching` compute to
- // `false` even though nothing has loaded yet. Left uncorrected, callers
- // see one frame of "ready but empty" (no skeleton) on a brand-new scope
- // before the query flips `enabled` and `isLoading` jumps back to `true`.
- isLoading: query.isLoading || !anchorResolved,
+ // Instant channel switch: a warm channel already has its newest-tail
+ // hydrated into `messages` (from the persisted `channelMessages` cache)
+ // before the read anchor resolves. Those rows must paint immediately rather
+ // than wait on the bootstrap/read-snapshot round-trip — switching must not
+ // happen on a network timescale. So only report loading when there is
+ // genuinely nothing to show yet.
+ //
+ // `!anchorResolved` alone used to force loading=true on every mount: while
+ // the anchor snapshot resolves the query is `enabled: false`, and TanStack
+ // forces `isFetching` false in that state, so native
+ // `isLoading = isPending && isFetching` computes to `false` even with no
+ // data — leaving callers a frame of "ready but empty". We still guard that
+ // empty case, but a non-empty hydrated cache is the warm tail and renders
+ // now. The scroll-to-bottom / NEW-divider / unread count stay gated in the
+ // page + `useScrollAnchor` (which now scrolls a warm tail to the bottom on
+ // first paint and converges the divider once the snapshot lands), so early
+ // painting can't strand the viewport at the top. A cold channel (empty
+ // cache) still shows the skeleton.
+ isLoading: query.isLoading || (!anchorResolved && messages.length === 0),
messages,
latestSeq,
hasMoreOlder,
diff --git a/src/web/src/hooks/community/use-scroll-anchor.test.ts b/src/web/src/hooks/community/use-scroll-anchor.test.ts
index f16a835f4..78c959c0f 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts
@@ -37,8 +37,24 @@ describe("decideScrollAction — mount (rewritten — neither case is free with
expect(action).toEqual({ type: "mount", newDividerBefore: undefined })
})
- it("does not fire (and does not consume the one-shot gate) until initialScrollReady", () => {
+ it("scrolls a warm tail-attached cache to the bottom early — before initialScrollReady (instant switch phase 1)", () => {
+ // A revisit has its newest tail already hydrated; don't wait on the read
+ // snapshot to paint-and-scroll to the bottom. Consumes the phase-1 one-shot
+ // but leaves phase-2 (divider convergence) pending.
const { action, nextState } = decideScrollAction(baseInput({ initialScrollReady: false }))
+ expect(action).toEqual({ type: "scrollToEnd" })
+ expect(nextState.didInitialScroll).toBe(true)
+ expect(nextState.didDividerConverge).toBe(false)
+ })
+
+ it("does NOT take the early-bottom path for an older-only / mid-history window (hasMoreNewer) — waits on initialScrollReady", () => {
+ // A jump target or cold anchor fetch loads a window whose bottom is a
+ // mid-history edge, not the present. Scrolling "to the end" there would
+ // strand the viewer mid-history, so this must wait for the full mount
+ // (Cecilia's red line #1: judge the tail by hasMoreNewer, not "are there rows").
+ const { action, nextState } = decideScrollAction(
+ baseInput({ initialScrollReady: false, hasMoreNewer: true }),
+ )
expect(action).toEqual({ type: "none" })
expect(nextState.didInitialScroll).toBe(false)
})
@@ -59,13 +75,42 @@ describe("decideScrollAction — mount (rewritten — neither case is free with
expect(nextState.didInitialScroll).toBe(false)
})
- it("fires once both initialScrollReady and heroMeasured become true, even if one lagged behind the other", () => {
- const notReady = decideScrollAction(baseInput({ initialScrollReady: false, heroMeasured: false }))
+ it("for a cold / mid-history window fires the full mount once both initialScrollReady and heroMeasured become true, even if one lagged", () => {
+ // hasMoreNewer keeps it off the early-bottom path so this still exercises
+ // the "wait for both gates, then mount" sequence.
+ const notReady = decideScrollAction(baseInput({ initialScrollReady: false, heroMeasured: false, hasMoreNewer: true }))
expect(notReady.action).toEqual({ type: "none" })
- const heroOnly = decideScrollAction(baseInput({ state: notReady.nextState, initialScrollReady: false, heroMeasured: true }))
+ const heroOnly = decideScrollAction(baseInput({ state: notReady.nextState, initialScrollReady: false, heroMeasured: true, hasMoreNewer: true }))
expect(heroOnly.action).toEqual({ type: "none" })
- const bothReady = decideScrollAction(baseInput({ state: heroOnly.nextState, initialScrollReady: true, heroMeasured: true }))
+ const bothReady = decideScrollAction(baseInput({ state: heroOnly.nextState, initialScrollReady: true, heroMeasured: true, hasMoreNewer: true }))
expect(bothReady.action.type).toBe("mount")
+ // Full mount with the snapshot already resolved completes both phases.
+ expect(bothReady.nextState.didDividerConverge).toBe(true)
+ })
+
+ it("phase 2 — converges to the NEW divider once the snapshot resolves after an early bottom, only while still at the bottom", () => {
+ // Phase 1: warm early bottom (snapshot not ready).
+ const phase1 = decideScrollAction(baseInput({ initialScrollReady: false, newDividerBefore: undefined }))
+ expect(phase1.action).toEqual({ type: "scrollToEnd" })
+ expect(phase1.nextState.didDividerConverge).toBe(false)
+ // Phase 2: snapshot resolves, a divider is now named, viewer still at bottom.
+ const phase2 = decideScrollAction(
+ baseInput({ state: phase1.nextState, initialScrollReady: true, newDividerBefore: "m2", isAtEnd: true }),
+ )
+ expect(phase2.action).toEqual({ type: "mount", newDividerBefore: "m2" })
+ expect(phase2.nextState.didDividerConverge).toBe(true)
+ })
+
+ it("phase 2 — does NOT yank the viewport if the user scrolled away before the snapshot resolved", () => {
+ const phase1 = decideScrollAction(baseInput({ initialScrollReady: false }))
+ expect(phase1.action).toEqual({ type: "scrollToEnd" })
+ // Snapshot resolves with a divider, but the viewer is no longer at the bottom.
+ const phase2 = decideScrollAction(
+ baseInput({ state: phase1.nextState, initialScrollReady: true, newDividerBefore: "m2", isAtEnd: false }),
+ )
+ expect(phase2.action).toEqual({ type: "none" })
+ // One-shot still consumed so it can't fire on a later revalidation.
+ expect(phase2.nextState.didDividerConverge).toBe(true)
})
it("fires exactly once — a second commit with didInitialScroll already true does not re-mount-scroll", () => {
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 7dec3f97a..73ad7e94c 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -46,12 +46,21 @@ export interface ScrollAnchorMessage {
export interface ScrollAnchorState {
didInitialScroll: boolean
+ // Instant channel switch: the mount scroll now has two phases. Phase 1
+ // (`didInitialScroll`) puts the viewport at the bottom — it may fire early,
+ // off a warm tail-attached cache, before the read snapshot resolves. Phase 2
+ // (`didDividerConverge`) repositions once to the NEW-divider when the read
+ // snapshot lands. When phase 1 already had the divider (read snapshot ready
+ // at mount) both complete together. `didDividerConverge` guards phase 2 so
+ // it fires at most once and never re-yanks after the user starts scrolling.
+ didDividerConverge: boolean
lastTailId: string | null
}
export function createScrollAnchorState(): ScrollAnchorState {
return {
didInitialScroll: false,
+ didDividerConverge: false,
lastTailId: null,
}
}
@@ -112,6 +121,7 @@ export function decideScrollAction(input: DecideScrollActionInput): DecideScroll
const baseNextState: ScrollAnchorState = {
didInitialScroll: state.didInitialScroll,
+ didDividerConverge: state.didDividerConverge,
lastTailId: nextTail,
}
@@ -134,26 +144,83 @@ export function decideScrollAction(input: DecideScrollActionInput): DecideScroll
// hook instance (keyed by channelId/dmId — see this hook's doc comment),
// so this branch only ever matters for a same-scope transient empty.
if (nextLen === 0) {
- return { action: { type: "none" }, nextState: { ...baseNextState, didInitialScroll: false } }
+ return {
+ action: { type: "none" },
+ nextState: { ...baseNextState, didInitialScroll: false, didDividerConverge: false },
+ }
}
- // 1. Mount-time initial scroll — fires exactly once. Bails (without
- // consuming the gate) until `initialScrollReady` — running before the
- // owner's async anchor (e.g. `useChannelReadStateSnapshot`) resolves
- // would silently snap to the bottom and burn the one-shot gate. Also
- // bails until `heroMeasured` — see this field's doc comment above for why
- // firing on a stale (default-0) scrollMargin silently mis-targets the
- // NEW-divider case.
+ // Whether the loaded window is tail-attached to the present (its newest page
+ // reaches "now"). Only then is scrolling "to the bottom" scrolling to the
+ // real latest message — an older-only / mid-history window (e.g. a jump
+ // target, or a cold anchor fetch) has `hasMoreNewer` true, and its bottom is
+ // a mid-history edge, so it must NOT take the early-bottom path (Cecilia's
+ // red line #1: judge the tail by hasMoreNewer, not "are there rows").
+ const tailAttached = !hasMoreNewer
+
+ // Phase 1 — mount-time scroll to the bottom. Fires exactly once. Two ways in:
+ // • Read snapshot already resolved (`initialScrollReady`): do the full
+ // mount — divider target if there's an unread anchor, else the end — and
+ // complete BOTH phases at once (nothing left to converge).
+ // • Warm tail-attached cache, snapshot NOT yet resolved: paint-and-scroll
+ // to the end immediately so a revisit lands at the bottom on the first
+ // frame (instant switch) instead of waiting on the network. The
+ // NEW-divider then converges in phase 2 when the snapshot lands.
+ // Still bails until `heroMeasured` in both cases — firing on a default-0
+ // scrollMargin mis-targets the scroll (see `heroMeasured`'s doc comment).
if (!state.didInitialScroll) {
- if (!initialScrollReady || !heroMeasured) {
- return { action: { type: "none" }, nextState: { ...baseNextState, didInitialScroll: false } }
+ if (heroMeasured && initialScrollReady) {
+ return {
+ action: { type: "mount", newDividerBefore },
+ nextState: { ...baseNextState, didInitialScroll: true, didDividerConverge: true },
+ }
+ }
+ if (heroMeasured && tailAttached) {
+ // Early bottom: snapshot not ready, but a tail-attached warm cache means
+ // "bottom" is the true latest — scroll there now, leave phase 2 to place
+ // the divider once the snapshot resolves.
+ return {
+ action: { type: "scrollToEnd" },
+ nextState: { ...baseNextState, didInitialScroll: true, didDividerConverge: false },
+ }
+ }
+ return {
+ action: { type: "none" },
+ nextState: { ...baseNextState, didInitialScroll: false },
}
- return { action: { type: "mount", newDividerBefore }, nextState: { ...baseNextState, didInitialScroll: true } }
}
- // 2. Self-send / peer-follow — only relevant when the tail actually moved.
+ // Self-send / peer-follow — only relevant when the tail actually moved.
const tailChanged = state.lastTailId !== null && state.lastTailId !== nextTail
+
+ // Phase 2 — converge onto the NEW divider, exactly once, after an early
+ // bottom scroll. This is a MOUNT-SETTLING step, so it only applies while the
+ // tail is unchanged: once a live append arrives (`tailChanged`), we're past
+ // mount and the self-send/peer-follow logic below owns the viewport — a live
+ // append also consumes the convergence one-shot (we're no longer settling a
+ // fresh mount). Waits for the read snapshot (`initialScrollReady`) to name
+ // the anchor, and only repositions while the viewer is still parked at the
+ // bottom (`isAtEnd`): if they've started scrolling we must not yank them
+ // (Cecilia's red line #2 — converge, never pull a settled viewport back).
+ if (!state.didDividerConverge && !tailChanged) {
+ if (!initialScrollReady || !heroMeasured) {
+ return { action: { type: "none" }, nextState: baseNextState }
+ }
+ if (newDividerBefore && isAtEnd) {
+ return {
+ action: { type: "mount", newDividerBefore },
+ nextState: { ...baseNextState, didDividerConverge: true },
+ }
+ }
+ // No divider to place, or the viewer already scrolled away — consume the
+ // one-shot without moving them.
+ return { action: { type: "none" }, nextState: { ...baseNextState, didDividerConverge: true } }
+ }
if (tailChanged) {
+ // A live append means we're past mount-settling: the divider-convergence
+ // one-shot is spent (any pending convergence would now be a stale yank), so
+ // consume it on every tail-changed outcome below.
+ const liveState = { ...baseNextState, didDividerConverge: true }
const tail = messages[messages.length - 1]
const isSelfSend = !!viewerUserId && tail?.authorId === viewerUserId
if (isSelfSend) {
@@ -162,15 +229,16 @@ export function decideScrollAction(input: DecideScrollActionInput): DecideScroll
// changes via `reconcileServerId` on send success, but the author is
// still the viewer, so this branch still catches it as an idempotent
// self-send snap, not a misclassified no-op).
- return { action: { type: "scrollToEnd" }, nextState: baseNextState }
+ return { action: { type: "scrollToEnd" }, nextState: liveState }
}
// Peer send: only follow if the loaded window is tail-attached to the
// present (`hasMoreNewer` false) AND the viewer was already at/near the
// bottom just BEFORE this append — otherwise leave the "↓ N" pill to
// prompt them back down.
if (!hasMoreNewer && isAtEnd) {
- return { action: { type: "scrollToEnd" }, nextState: baseNextState }
+ return { action: { type: "scrollToEnd" }, nextState: liveState }
}
+ return { action: { type: "none" }, nextState: liveState }
}
return { action: { type: "none" }, nextState: baseNextState }