perf(desktop): paint newest thread page incrementally

Use relay-authoritative page bounds so malformed stored rows cannot truncate
thread history. Fetch newest-first, publish each page into the cache without
losing live arrivals, and retain cached channel and thread rows during
revalidation.

Add identity-correlated channel/thread timing marks and deterministic smoke
coverage for cold, fresh, stale, paginated, and in-flight live-write paths.

Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz>
Signed-off-by: Wes <wesbillman@users.noreply.github.com>
This commit is contained in:
Wes
2026-08-13 12:36:47 -06:00
committed by Carl
co-authored by Carl
parent a86ebf867b
commit cabcd3376b
24 changed files with 1154 additions and 85 deletions
+2
View File
@@ -34,6 +34,8 @@ export default defineConfig({
"**/add-community-screenshots.spec.ts",
"**/hosted-communities-settings-screenshots.spec.ts",
"**/invites-settings-screenshots.spec.ts",
"**/message-performance.spec.ts",
"**/thread-newest-ab.perf.ts",
"**/messaging.spec.ts",
"**/message-feedback-snapshots.spec.ts",
"**/custom-emoji.spec.ts",
+8 -22
View File
@@ -2,6 +2,7 @@ use nostr::{Event, EventId, Keys, PublicKey};
use tauri::{AppHandle, State};
mod forum;
mod thread_page;
use forum::{
apply_link_preview_suppression, fetch_agent_owner_pubkeys, link_preview_suppression_targets,
@@ -251,6 +252,7 @@ pub async fn get_thread_replies(
channel_id: Option<String>,
limit: Option<u32>,
depth_limit: Option<u32>,
thread_order: Option<String>,
cursor: Option<crate::models::ThreadCursor>,
state: State<'_, AppState>,
) -> Result<ThreadRepliesResponse, String> {
@@ -260,32 +262,12 @@ pub async fn get_thread_replies(
channel_id.as_deref(),
depth_limit.unwrap_or(64),
cap,
thread_order.as_deref(),
cursor.as_ref(),
);
let events = query_relay(&state, &[serde_json::Value::Object(filter)]).await?;
// A full page implies there may be more; hand back the last event's
// composite key as the next cursor (the DB returns replies strictly after
// it, tiebroken by event_id so same-second replies are not skipped).
let next_cursor = if events.len() as u32 >= cap {
events.last().map(|ev| crate::models::ThreadCursor {
created_at: ev.created_at.as_secs() as i64,
event_id: ev.id.to_hex(),
})
} else {
None
};
let event_values: Vec<serde_json::Value> = events
.iter()
.filter_map(|ev| serde_json::to_value(ev).ok())
.collect();
Ok(ThreadRepliesResponse {
events: event_values,
next_cursor,
})
thread_page::parse(events, &root_event_id)
}
/// Build the relay `/query` filter for the server-side thread-subtree read.
@@ -308,6 +290,7 @@ fn build_thread_replies_filter(
channel_id: Option<&str>,
depth_limit: u32,
cap: u32,
thread_order: Option<&str>,
cursor: Option<&crate::models::ThreadCursor>,
) -> serde_json::Map<String, serde_json::Value> {
let mut filter = serde_json::Map::new();
@@ -317,6 +300,9 @@ fn build_thread_replies_filter(
// defaults it to a deep-but-bounded value so nested replies aren't dropped.
filter.insert("depth_limit".to_string(), serde_json::json!(depth_limit));
filter.insert("limit".to_string(), serde_json::json!(cap));
if matches!(thread_order, Some("newest")) {
filter.insert("thread_order".to_string(), serde_json::json!("newest"));
}
if let Some(cid) = channel_id {
filter.insert("#h".to_string(), serde_json::json!([cid]));
}
@@ -0,0 +1,58 @@
use nostr::Event;
use serde::Deserialize;
use crate::models::{ThreadCursor, ThreadRepliesResponse};
#[derive(Deserialize)]
struct BoundsCursor {
created_at: i64,
id: String,
}
#[derive(Deserialize)]
struct BoundsPayload {
has_more: bool,
next_cursor: Option<BoundsCursor>,
}
pub(super) fn parse(
events: Vec<Event>,
root_event_id: &str,
) -> Result<ThreadRepliesResponse, String> {
let mut replies = Vec::new();
let mut bounds = None;
for event in events {
if event.kind.as_u16() as u32 == buzz_core_pkg::kind::KIND_THREAD_BOUNDS {
if bounds.is_some() {
return Err("Thread response contained multiple bounds overlays".to_string());
}
let matches_root = event.tags.iter().any(|tag| {
let values = tag.as_slice();
values.first().map(String::as_str) == Some("e")
&& values.get(1).map(String::as_str) == Some(root_event_id)
});
if !matches_root {
return Err("Thread bounds overlay does not match the requested root".to_string());
}
bounds = Some(
serde_json::from_str::<BoundsPayload>(&event.content)
.map_err(|error| format!("Invalid thread bounds overlay: {error}"))?,
);
} else if let Ok(value) = serde_json::to_value(&event) {
replies.push(value);
}
}
let bounds = bounds.ok_or_else(|| "Thread response omitted its bounds overlay".to_string())?;
let next_cursor = bounds.next_cursor.map(|cursor| ThreadCursor {
created_at: cursor.created_at,
event_id: cursor.id,
});
if bounds.has_more != next_cursor.is_some() {
return Err("Thread bounds has_more and next_cursor disagree".to_string());
}
Ok(ThreadRepliesResponse {
events: replies,
has_more: bounds.has_more,
next_cursor,
})
}
@@ -146,7 +146,7 @@ fn thread_replies_filter_carries_non_p_gated_kinds_to_clear_the_gate() {
// and every kind MUST be non-p-gated (else the gate still fires). The
// Playwright mock does not model p-gating, so this unit test is the
// only guard against the client/relay auth contract drifting.
let filter = build_thread_replies_filter("root-hex", Some("channel-1"), 64, 200, None);
let filter = build_thread_replies_filter("root-hex", Some("channel-1"), 64, 200, None, None);
let kinds = filter
.get("kinds")
@@ -175,7 +175,9 @@ fn thread_replies_filter_pages_with_composite_cursor() {
created_at: 1_700_000_000,
event_id: "abcd".to_string(),
};
let filter = build_thread_replies_filter("root-hex", None, 64, 200, Some(&cursor));
let filter =
build_thread_replies_filter("root-hex", None, 64, 200, Some("newest"), Some(&cursor));
assert_eq!(filter["thread_order"], serde_json::json!("newest"));
assert_eq!(filter["thread_cursor"], serde_json::json!(1_700_000_000));
assert_eq!(filter["thread_cursor_id"], serde_json::json!("abcd"));
assert!(
+1
View File
@@ -321,6 +321,7 @@ pub struct ThreadCursor {
#[derive(Serialize, Deserialize)]
pub struct ThreadRepliesResponse {
pub events: Vec<serde_json::Value>,
pub has_more: bool,
pub next_cursor: Option<ThreadCursor>,
}
+8 -1
View File
@@ -33,6 +33,7 @@ import {
import { useUnreadChannels } from "@/features/channels/useUnreadChannels";
import { useMembershipNotifications } from "@/features/channels/useMembershipNotifications";
import { useFeedItemState } from "@/features/home/useFeedItemState";
import { markChannelSelectionPerformance } from "@/features/messages/useMessagePerformance";
import { useThreadFollows } from "@/features/messages/lib/useThreadFollows";
import {
useHomeFeedNotifications,
@@ -847,7 +848,13 @@ export function AppShell() {
await goChannel(directMessage.id);
}}
onSelectAgents={() => void goAgents()}
onSelectChannel={handleSidebarChannelSelect}
onSelectChannel={(channelId) => {
markChannelSelectionPerformance(
channelId,
selectedChannelId,
);
handleSidebarChannelSelect(channelId);
}}
onOpenSearchResult={handleOpenSearchResult}
searchChannels={channels}
searchFocusRequests={[
@@ -1,6 +1,7 @@
import * as React from "react";
import { useAppShell } from "@/app/AppShellContext";
import { useAppNavigation } from "@/app/navigation/useAppNavigation";
import { useMeasuredOpenThread } from "@/features/messages/useMessagePerformance";
import { useActiveChannelHeader } from "@/features/channels/useActiveChannelHeader";
import { useChannelPaneHandlers } from "@/features/channels/useChannelPaneHandlers";
import { useMessageEventProfilePubkeys } from "@/features/channels/useMessageEventProfilePubkeys";
@@ -595,6 +596,9 @@ export function ChannelScreen({
const settledChannelIdRef = React.useRef<string | null>(null);
const hasSettledThisChannel =
activeChannelId !== null && settledChannelIdRef.current === activeChannelId;
const hasAuthoritativeTimelineCache = Boolean(
windowQuery.data && windowQuery.data.pages.length > 0,
);
const timelineLoadingNow =
activeChannel !== null &&
activeChannel.channelType !== "forum" &&
@@ -606,6 +610,7 @@ export function ChannelScreen({
dataLength: messagesQuery.data?.length ?? null,
},
hasSettledThisChannel,
hasAuthoritativeTimelineCache,
);
const { settledChannelId, isLoading: isTimelineLoading } =
resolveTimelineLoadingLatch(
@@ -673,6 +678,10 @@ export function ChannelScreen({
channelManagementOpen,
);
const displayedThreadHeadMessage = threadPanelData.threadHead;
const handleMeasuredOpenThread = useMeasuredOpenThread(
effectiveOpenThreadHeadId,
handleOpenThreadAndCloseAgentSession,
);
const displayedThreadAllMessages = threadPanelData.messages;
const displayedThreadMessages = threadPanelData.visibleReplies;
const displayedThreadReplyTargetMessage = threadPanelData.replyTargetMessage;
@@ -914,7 +923,7 @@ export function ChannelScreen({
onOpenProfilePanel={handleOpenProfilePanel}
onResetThreadPanelWidth={handleThreadPanelWidthReset}
onCloseProfilePanel={handleCloseProfilePanel}
onOpenThread={handleOpenThreadAndCloseAgentSession}
onOpenThread={handleMeasuredOpenThread}
onSelectThreadReplyTarget={handleSelectThreadReplyTarget}
onSendMessage={handleSendMessage}
onSendToChannel={handleSendToChannel}
@@ -0,0 +1,74 @@
export const CHANNEL_SWITCH_START_MARK = "buzz:channel-switch:start";
export const CHANNEL_ROWS_PAINTED_MARK = "buzz:channel-switch:rows-painted";
export const CHANNEL_ROWS_PAINTED_MEASURE =
"buzz:channel-switch:rows-painted-duration";
export const CHANNEL_VIEWPORT_SETTLED_MARK =
"buzz:channel-switch:viewport-settled";
export const CHANNEL_VIEWPORT_SETTLED_MEASURE =
"buzz:channel-switch:viewport-settled-duration";
export const CHANNEL_VIRTUALIZER_CALLBACK_MARK =
"buzz:channel-switch:virtualizer-callback";
export const CHANNEL_RESIZE_OBSERVER_CALLBACK_MARK =
"buzz:channel-switch:resize-observer-callback";
export const CHANNEL_SCROLL_WRITE_MARK = "buzz:channel-switch:scroll-write";
export const THREAD_OPEN_START_MARK = "buzz:thread-open:start";
export const THREAD_REPLIES_PAINTED_MARK = "buzz:thread-open:replies-painted";
export const THREAD_REPLIES_PAINTED_MEASURE =
"buzz:thread-open:replies-painted-duration";
export const THREAD_VIEWPORT_SETTLED_MARK = "buzz:thread-open:viewport-settled";
export const THREAD_VIEWPORT_SETTLED_MEASURE =
"buzz:thread-open:viewport-settled-duration";
const listeners = new Map<string, Set<() => void>>();
export function subscribePerformanceMark(
names: readonly string[],
listener: () => void,
): () => void {
for (const name of names) {
const current = listeners.get(name) ?? new Set();
current.add(listener);
listeners.set(name, current);
}
return () => {
for (const name of names) listeners.get(name)?.delete(listener);
};
}
export function startPerformanceMark(
name: string,
identity: string,
detail?: Record<string, unknown>,
): void {
performance.mark(name, { detail: { ...detail, identity } });
}
export function recordPerformanceMark(
name: string,
detail?: Record<string, unknown>,
): void {
performance.mark(name, detail ? { detail } : undefined);
for (const listener of listeners.get(name) ?? []) listener();
}
export function finishPerformanceMeasure(input: {
startMark: string;
endMark: string;
measure: string;
identity: string;
detail?: Record<string, unknown>;
}): number | null {
const start = [...performance.getEntriesByName(input.startMark, "mark")]
.reverse()
.find(
(entry) => (entry as PerformanceMark).detail?.identity === input.identity,
);
if (!start) return null;
performance.mark(input.endMark, {
detail: { ...input.detail, identity: input.identity },
});
const end = performance.getEntriesByName(input.endMark, "mark").at(-1);
if (!end) return null;
performance.measure(input.measure, {
start: start.startTime,
end: end.startTime,
detail: { ...input.detail, identity: input.identity },
});
return start.startTime;
}
@@ -85,6 +85,28 @@ test("initial load holds the skeleton while the cold-load top-up fetches", () =>
);
});
test("pre-settle authoritative cached rows paint during revalidation", () => {
assert.equal(
selectTimelineLoadingState(
{ ...settled, isFetching: true, dataLength: 8 },
false,
true,
),
false,
);
});
test("pre-settle authoritative empty cache still holds the skeleton", () => {
assert.equal(
selectTimelineLoadingState(
{ ...settled, isFetching: true, dataLength: 0 },
false,
true,
),
true,
);
});
test("pre-settle placeholder rows paint immediately (snapshot revisit)", () => {
// A revisit painting from the React-Query cache or a persisted snapshot:
// placeholder rows are a previously-settled timeline, not a partial cold
@@ -18,11 +18,17 @@ export type TimelineQueryStatus = {
export function selectTimelineLoadingState(
status: TimelineQueryStatus,
hasSettled = true,
hasAuthoritativeCache = false,
): boolean {
if (status.isPending) {
return true;
}
if (!hasSettled) {
// A populated authoritative window proves these rows came from a previous
// settled load, not from the live subscription's partial pre-settle seed.
if (hasAuthoritativeCache && (status.dataLength ?? 0) > 0) {
return false;
}
// Placeholder rows are a previously-settled timeline (React-Query cache on
// revisit, or a persisted snapshot) — paint them stale-then-revalidate
// instead of holding a skeleton over known content.
@@ -14,6 +14,7 @@ import {
selectLatestMessageKey,
selectTimelineBodySurface,
selectTimelineIntroSurface,
selectTimelineRenderSource,
} from "./timelineSnapshot.ts";
// Local-midnight unix-second timestamps so isSameDay (local time) is stable
@@ -370,6 +371,39 @@ test("classifyTimelineMessageDelta: unchanged snapshots do not count as arrivals
// RenderState picks which of three states the reply region paints so we never
// flash "No replies" over a list that's streaming in on the deferred commit.
test("timeline-render-source: keeps a cold channel deferred until it commits", () => {
assert.equal(
selectTimelineRenderSource({
deferredChannelId: "old-channel",
liveChannelId: "cold-channel",
preferLiveSnapshot: false,
}),
null,
);
});
test("timeline-render-source: paints a settled channel cache during revisit", () => {
assert.equal(
selectTimelineRenderSource({
deferredChannelId: "other-channel",
liveChannelId: "cached-channel",
preferLiveSnapshot: true,
}),
"live",
);
});
test("timeline-render-source: uses the matching deferred snapshot", () => {
assert.equal(
selectTimelineRenderSource({
deferredChannelId: "channel-a",
liveChannelId: "channel-a",
preferLiveSnapshot: false,
}),
"deferred",
);
});
test("deferred-render: paints the list whenever the deferred snapshot has rows", () => {
// deferred caught up — normal steady state.
assert.equal(selectDeferredListRenderState(3, 3), "list");
@@ -181,6 +181,22 @@ export function selectDeferredListRenderState(
return "pending";
}
export type TimelineRenderSource = "live" | "deferred" | null;
/** Keep cold loads deferred, but let an already-settled channel repaint cache. */
export function selectTimelineRenderSource({
deferredChannelId,
liveChannelId,
preferLiveSnapshot,
}: {
deferredChannelId: string | null;
liveChannelId: string | null;
preferLiveSnapshot: boolean;
}): TimelineRenderSource {
if (deferredChannelId === liveChannelId) return "deferred";
return preferLiveSnapshot ? "live" : null;
}
export type TimelineBodySurface = "skeleton" | "empty" | "list";
export function selectTimelineBodySurface({
@@ -1,6 +1,5 @@
import * as React from "react";
import { ArrowDown } from "lucide-react";
import { useKnownAgentPubkeys } from "@/features/agents/useKnownAgentPubkeys";
import { HuddleTranscriptIntro } from "@/features/huddle/components/HuddleTranscriptIntro";
import { orderMentionPubkeysByText } from "@/features/messages/lib/orderMentionPubkeys";
@@ -52,7 +51,7 @@ import { useComposerHeightPadding } from "./useComposerHeightPadding";
import { useStableSendToChannel } from "./useStableSendToChannel";
import { useAnchoredScroll } from "./useAnchoredScroll";
import { selectDeferredListRenderState } from "@/features/messages/lib/timelineSnapshot";
import { useThreadPerformance } from "@/features/messages/useMessagePerformance";
type MessageThreadPanelProps = ThreadPanelLayoutProps & {
channel: Channel | null;
channelId: string | null;
@@ -343,9 +342,6 @@ export function MessageThreadPanel({
}
}, [collapsedThreadHeadId, scrollTargetIsVisibleReply, threadHeadId]);
// Which of the three states the reply region paints this frame. Delegated to
// a pure helper so the "don't flash empty over an incoming list" rule is
// covered in the lib test suite (see selectDeferredListRenderState).
const repliesRenderState = selectDeferredListRenderState(
deferredThreadReplies.length,
threadReplies.length,
@@ -363,11 +359,6 @@ export function MessageThreadPanel({
const visibleThreadHeadSummary = isThreadHeadRepliesCollapsed
? threadHeadSummary
: null;
// Focus mode gives the thread a subject/body structure: the head is what the
// thread is about, the replies are the conversation about it. Only draw the
// rule when there is actually conversation under it — the "no replies yet"
// card and the streaming-in `pending` state would both leave a rule hanging
// over an empty region or a placeholder.
const showThreadHeadDivider =
!isHuddleTranscript &&
isFocusMode &&
@@ -524,6 +515,15 @@ export function MessageThreadPanel({
"padding",
settleAtBottomAfterLayout,
);
useThreadPerformance({
bodyRef: threadBodyRef,
ready:
repliesRenderState === "list" &&
!threadRepliesPending &&
!isRepliesPending,
replyCount: deferredThreadReplies.length,
threadHeadId,
});
const knownAgentPubkeys = useKnownAgentPubkeys();
const initialAgentPubkeys = React.useMemo(() => {
if (
@@ -647,7 +647,9 @@ export function MessageThreadPanel({
className={cn(THREAD_PANEL_MESSAGE_GUTTER_CLASS, "pb-3 pt-0")}
data-testid="message-thread-replies"
>
{threadRepliesPending && !isHuddleTranscript ? (
{threadRepliesPending &&
!isHuddleTranscript &&
deferredThreadReplies.length === 0 ? (
<div
className="space-y-2.5 pt-1"
data-testid="message-thread-replies-loading"
@@ -655,7 +657,8 @@ export function MessageThreadPanel({
<ThreadMessageSkeleton />
<ThreadMessageSkeleton />
</div>
) : repliesRenderState === "list" ? (
) : repliesRenderState === "list" ||
deferredThreadReplies.length > 0 ? (
visibleThreadHeadSummary ? (
<div
className="space-y-0"
@@ -5,9 +5,18 @@ import {
isRenderedTimelineBehindHistoryPrepend,
selectTimelineBodySurface,
selectTimelineIntroSurface,
selectTimelineRenderSource,
} from "@/features/messages/lib/timelineSnapshot";
import { preloadTimelineImages } from "@/features/messages/lib/timelineImagePreload";
import type { TimelineMessage } from "@/features/messages/types";
import {
useChannelRowsPaintedPerformanceMeasure,
useChannelViewportSettledPerformanceMeasure,
} from "@/features/messages/useMessagePerformance";
import {
CHANNEL_VIRTUALIZER_CALLBACK_MARK,
recordPerformanceMark,
} from "@/features/messages/lib/messagePerformance";
import type { MainTimelineEntry } from "@/features/messages/lib/threadPanel";
import type { ChannelWindowThreadSummary } from "@/features/messages/lib/channelWindowStore";
import type { UserProfileLookup } from "@/features/profile/lib/identity";
@@ -254,7 +263,45 @@ const MessageTimelineBase = React.forwardRef<
liveSnapshot,
EMPTY_TIMELINE_SNAPSHOT,
);
const deferredMessages = deferredSnapshot.messages;
// Cold loads keep the deferred markdown gate. Once a channel has committed,
// a warm revisit can paint its cached snapshot immediately while refresh
// work continues behind it.
const requiresDeferredSettleRef = React.useRef(new Map<string, boolean>());
const snapshotChannelId = liveSnapshot.channelId;
if (snapshotChannelId) {
if (!requiresDeferredSettleRef.current.has(snapshotChannelId)) {
requiresDeferredSettleRef.current.set(snapshotChannelId, isLoading);
} else if (isLoading) {
requiresDeferredSettleRef.current.set(snapshotChannelId, true);
}
if (
!isLoading &&
deferredSnapshot.channelId === snapshotChannelId &&
messages.length > 0
) {
requiresDeferredSettleRef.current.set(snapshotChannelId, false);
}
}
const renderSource = selectTimelineRenderSource({
deferredChannelId: deferredSnapshot.channelId,
liveChannelId: snapshotChannelId,
preferLiveSnapshot:
!isLoading &&
messages.length > 0 &&
(snapshotChannelId === null ||
requiresDeferredSettleRef.current.get(snapshotChannelId) === false),
});
const renderedSnapshot =
renderSource === "live"
? liveSnapshot
: renderSource === "deferred"
? deferredSnapshot
: EMPTY_TIMELINE_SNAPSHOT;
const deferredMessages = renderedSnapshot.messages;
useChannelRowsPaintedPerformanceMeasure(
channelId ?? null,
deferredMessages.length,
);
const imagePreloadStateRef = React.useRef({
activeImages: new Set<HTMLImageElement>(),
requestedUrls: new Set<string>(),
@@ -262,11 +309,13 @@ const MessageTimelineBase = React.forwardRef<
React.useEffect(() => {
preloadTimelineImages(messages, imagePreloadStateRef.current);
}, [messages]);
const isDeferredSnapshotStale = isDeferredTimelineSnapshotStale({
deferredSnapshot,
liveSnapshot,
});
const isRenderPending = deferredSnapshot !== liveSnapshot;
const isDeferredSnapshotStale =
renderSource === null &&
isDeferredTimelineSnapshotStale({
deferredSnapshot,
liveSnapshot,
});
const isRenderPending = renderedSnapshot !== liveSnapshot;
const scrollRestorationId = targetMessageId
? `message-timeline:${channelId ?? "none"}:target:${targetMessageId}`
: `message-timeline:${channelId ?? "none"}`;
@@ -339,7 +388,7 @@ const MessageTimelineBase = React.forwardRef<
} = useSettleGatedPrependMessages({
channelId,
messages: bufferedTimeline.messages,
meta: deferredSnapshot.historyExhausted,
meta: renderedSnapshot.historyExhausted,
scrollElementRef: activeScrollContainerRef,
});
@@ -637,8 +686,20 @@ const MessageTimelineBase = React.forwardRef<
);
const handleVirtualizerRangeChanged = React.useCallback(() => {
recordPerformanceMark(CHANNEL_VIRTUALIZER_CALLBACK_MARK, {
channelId: channelId ?? null,
});
bumpVirtualizerRenderVersion();
}, []);
}, [channelId]);
useChannelViewportSettledPerformanceMeasure({
channelId: channelId ?? null,
ready:
showMessageList &&
renderedMessages.length > 0 &&
!isRenderPending &&
!isHoldingPrepend,
settleVersion: virtualizerRenderVersion,
});
const timelineList = showMessageList ? (
<TimelineMessageList
@@ -792,7 +853,12 @@ const MessageTimelineBase = React.forwardRef<
)}
>
{showTimelineSkeleton ? (
<TimelineSkeleton rows={timelineSkeletonRows} />
<div
className="contents"
data-testid="message-timeline-loading"
>
<TimelineSkeleton rows={timelineSkeletonRows} />
</div>
) : null}
{activeDirectMessageIntro ? (
<div
@@ -22,6 +22,10 @@ import type { MainTimelineEntry } from "@/features/messages/lib/threadPanel";
import type { ChannelWindowThreadSummary } from "@/features/messages/lib/channelWindowStore";
import { buildVideoReviewContextsByMessageId } from "@/features/messages/lib/videoReviewContext";
import type { TimelineMessage } from "@/features/messages/types";
import {
CHANNEL_RESIZE_OBSERVER_CALLBACK_MARK,
recordPerformanceMark,
} from "@/features/messages/lib/messagePerformance";
import type { UserProfileLookup } from "@/features/profile/lib/identity";
import type { ChannelType } from "@/shared/api/types";
import { cn } from "@/shared/lib/cn";
@@ -695,7 +699,10 @@ function VirtualizedTimelineRows({
setOffscreenBufferSize(host.clientHeight * 3);
};
updateBufferSize();
const resizeObserver = new ResizeObserver(updateBufferSize);
const resizeObserver = new ResizeObserver(() => {
recordPerformanceMark(CHANNEL_RESIZE_OBSERVER_CALLBACK_MARK);
updateBufferSize();
});
resizeObserver.observe(host);
return () => resizeObserver.disconnect();
}, []);
@@ -1,5 +1,9 @@
import * as React from "react";
import type { VListHandle } from "virtua";
import {
CHANNEL_SCROLL_WRITE_MARK,
recordPerformanceMark,
} from "@/features/messages/lib/messagePerformance";
const SCROLL_INTENT_KEYS = new Set([
"ArrowDown",
@@ -44,6 +48,7 @@ export function useVirtualizedBottomSettle(
const scroller = hostRef.current?.firstElementChild;
const lastIndex = itemsLengthRef.current - 1;
if (!(scroller instanceof HTMLDivElement) || lastIndex < 0) return;
recordPerformanceMark(CHANNEL_SCROLL_WRITE_MARK, { lastIndex });
listRef.current?.scrollToIndex(lastIndex, { align: "end" });
}, [hostRef, itemsLengthRef, listRef]);
@@ -0,0 +1,201 @@
import * as React from "react";
import {
CHANNEL_ROWS_PAINTED_MARK,
CHANNEL_ROWS_PAINTED_MEASURE,
CHANNEL_RESIZE_OBSERVER_CALLBACK_MARK,
CHANNEL_SCROLL_WRITE_MARK,
CHANNEL_SWITCH_START_MARK,
CHANNEL_VIRTUALIZER_CALLBACK_MARK,
CHANNEL_VIEWPORT_SETTLED_MARK,
CHANNEL_VIEWPORT_SETTLED_MEASURE,
THREAD_OPEN_START_MARK,
THREAD_REPLIES_PAINTED_MARK,
THREAD_REPLIES_PAINTED_MEASURE,
THREAD_VIEWPORT_SETTLED_MARK,
THREAD_VIEWPORT_SETTLED_MEASURE,
finishPerformanceMeasure,
startPerformanceMark,
subscribePerformanceMark,
} from "@/features/messages/lib/messagePerformance";
import type { TimelineMessage } from "@/features/messages/types";
const CHANNEL_EVIDENCE = [
CHANNEL_VIRTUALIZER_CALLBACK_MARK,
CHANNEL_RESIZE_OBSERVER_CALLBACK_MARK,
CHANNEL_SCROLL_WRITE_MARK,
] as const;
export function markChannelSelectionPerformance(
channelId: string,
activeChannelId?: string | null,
): void {
if (channelId !== activeChannelId)
startPerformanceMark(CHANNEL_SWITCH_START_MARK, channelId);
}
export function useMeasuredOpenThread(
openId: string | null,
onOpen: (message: TimelineMessage) => void,
): (message: TimelineMessage) => void {
return React.useCallback(
(message) => {
if (message.id !== openId)
startPerformanceMark(THREAD_OPEN_START_MARK, message.id);
onOpen(message);
},
[onOpen, openId],
);
}
function usePaint(input: {
identity: string | null;
count: number;
start: string;
end: string;
measure: string;
}): void {
const measured = React.useRef(-1);
React.useEffect(() => {
if (!input.identity || !input.count) return;
const frame = requestAnimationFrame(() => {
const value = finishPerformanceMeasure({
startMark: input.start,
endMark: input.end,
measure: input.measure,
identity: input.identity as string,
detail: { rowCount: input.count },
});
if (value !== null && value !== measured.current)
measured.current = value;
});
return () => cancelAnimationFrame(frame);
}, [input.count, input.end, input.identity, input.measure, input.start]);
}
export function useChannelRowsPaintedPerformanceMeasure(
channelId: string | null,
count: number,
): void {
usePaint({
identity: channelId,
count,
start: CHANNEL_SWITCH_START_MARK,
end: CHANNEL_ROWS_PAINTED_MARK,
measure: CHANNEL_ROWS_PAINTED_MEASURE,
});
}
export function useThreadRepliesPaintedPerformanceMeasure(
threadId: string | null,
count: number,
): void {
usePaint({
identity: threadId,
count,
start: THREAD_OPEN_START_MARK,
end: THREAD_REPLIES_PAINTED_MARK,
measure: THREAD_REPLIES_PAINTED_MEASURE,
});
}
function useSettle(input: {
identity: string | null;
ready: boolean;
version: number;
evidence?: readonly string[];
start: string;
end: string;
measure: string;
}): void {
const [evidenceVersion, bump] = React.useReducer((n: number) => n + 1, 0);
React.useEffect(
() =>
input.evidence?.length
? subscribePerformanceMark(input.evidence, bump)
: undefined,
[input.evidence],
);
React.useEffect(() => {
void evidenceVersion;
void input.version;
if (!input.identity || !input.ready) return;
let second = 0;
const first = requestAnimationFrame(() => {
second = requestAnimationFrame(() =>
finishPerformanceMeasure({
startMark: input.start,
endMark: input.end,
measure: input.measure,
identity: input.identity as string,
}),
);
});
return () => {
cancelAnimationFrame(first);
if (second) cancelAnimationFrame(second);
};
}, [
evidenceVersion,
input.end,
input.identity,
input.measure,
input.ready,
input.start,
input.version,
]);
}
export function useChannelViewportSettledPerformanceMeasure(input: {
channelId: string | null;
ready: boolean;
settleVersion: number;
}): void {
useSettle({
identity: input.channelId,
ready: input.ready,
version: input.settleVersion,
evidence: CHANNEL_EVIDENCE,
start: CHANNEL_SWITCH_START_MARK,
end: CHANNEL_VIEWPORT_SETTLED_MARK,
measure: CHANNEL_VIEWPORT_SETTLED_MEASURE,
});
}
export function useThreadSettleVersion(
bodyRef: React.RefObject<HTMLElement | null>,
): number {
const [version, bump] = React.useReducer((n: number) => n + 1, 0);
React.useEffect(() => {
const body = bodyRef.current;
if (!body) return;
const observer = new ResizeObserver(bump);
body.addEventListener("scroll", bump, { passive: true });
observer.observe(body);
return () => {
observer.disconnect();
body.removeEventListener("scroll", bump);
};
}, [bodyRef]);
return version;
}
export function useThreadViewportSettledPerformanceMeasure(input: {
ready: boolean;
settleVersion: number;
threadHeadId: string | null;
}): void {
useSettle({
identity: input.threadHeadId,
ready: input.ready,
version: input.settleVersion,
start: THREAD_OPEN_START_MARK,
end: THREAD_VIEWPORT_SETTLED_MARK,
measure: THREAD_VIEWPORT_SETTLED_MEASURE,
});
}
export function useThreadPerformance(input: {
bodyRef: React.RefObject<HTMLElement | null>;
ready: boolean;
replyCount: number;
threadHeadId: string | null;
}): void {
useThreadRepliesPaintedPerformanceMeasure(
input.threadHeadId,
input.replyCount,
);
useThreadViewportSettledPerformanceMeasure({
ready: input.ready,
settleVersion: useThreadSettleVersion(input.bodyRef),
threadHeadId: input.threadHeadId,
});
}
@@ -89,15 +89,22 @@ async function loadThreadReplies(
const response = await getThreadReplies(rootId, channelId, {
limit: THREAD_PAGE_LIMIT,
cursor,
order: "newest",
});
replies.push(...response.events);
if (!response.nextCursor) {
const fetched = await withThreadAux(channelId, rootId, replies);
const pageWithAux = await withThreadAux(channelId, rootId, response.events);
replies.push(...pageWithAux);
queryClient.setQueryData<RelayEvent[]>(queryKey, (current = []) =>
sortMessages([...current, ...pageWithAux]),
);
if (!response.hasMore) {
const current = queryClient.getQueryData<RelayEvent[]>(queryKey) ?? [];
const receivedInFlight = current.filter(
(event) => !idsAtStart.has(event.id),
);
return sortMessages([...fetched, ...receivedInFlight]);
return sortMessages([...replies, ...receivedInFlight]);
}
if (!response.nextCursor) {
throw new Error(`Thread ${rootId} returned hasMore without a cursor.`);
}
cursor = response.nextCursor;
}
+7 -11
View File
@@ -7,7 +7,10 @@ import {
fromRawInstallRuntimeResult,
type RawInstallRuntimeResult,
} from "@/shared/api/installTypes";
import type { RawSendChannelMessageResult } from "@/shared/api/tauriMessageTypes";
import type {
RawSendChannelMessageResult,
RawThreadRepliesResponse,
} from "@/shared/api/tauriMessageTypes";
import type {
AddChannelMembersInput,
AddChannelMembersResult,
@@ -471,16 +474,6 @@ export async function getEventById(eventId: string): Promise<RelayEvent> {
return JSON.parse(eventJson) as RelayEvent;
}
type RawThreadCursor = {
created_at: number;
event_id: string;
};
type RawThreadRepliesResponse = {
events: RelayEvent[];
next_cursor: RawThreadCursor | null;
};
/**
* Fetch the full reply subtree under a thread root, server-side.
*
@@ -504,6 +497,7 @@ export async function getThreadReplies(
limit?: number;
depthLimit?: number;
cursor?: ThreadCursor | null;
order?: "oldest" | "newest";
},
): Promise<ThreadRepliesResponse> {
const response = await invokeTauri<RawThreadRepliesResponse>(
@@ -513,6 +507,7 @@ export async function getThreadReplies(
channelId: channelId ?? null,
limit: options?.limit ?? null,
depthLimit: options?.depthLimit ?? null,
threadOrder: options?.order ?? null,
cursor: options?.cursor
? {
created_at: options.cursor.createdAt,
@@ -524,6 +519,7 @@ export async function getThreadReplies(
return {
events: response.events,
hasMore: response.has_more,
nextCursor: response.next_cursor
? {
createdAt: response.next_cursor.created_at,
@@ -1,3 +1,11 @@
import type { RelayEvent } from "@/shared/api/types";
export type RawThreadRepliesResponse = {
events: RelayEvent[];
has_more: boolean;
next_cursor: { created_at: number; event_id: string } | null;
};
export type RawSendChannelMessageResult = {
event_id: string;
parent_event_id: string | null;
+4 -4
View File
@@ -1,7 +1,6 @@
export type ChannelType = "stream" | "forum" | "dm";
export type ChannelVisibility = "open" | "private";
export type ChannelRole = "owner" | "admin" | "member" | "guest" | "bot";
export type Channel = {
id: string;
name: string;
@@ -20,7 +19,6 @@ export type Channel = {
ttlSeconds: number | null;
ttlDeadline: string | null;
};
export type ChannelDetail = Channel & {
createdBy: string;
createdAt: string;
@@ -965,9 +963,11 @@ export type ThreadCursor = {
};
export type ThreadRepliesResponse = {
/** The reply subtree (chronological, oldest first), depth >= 1. Excludes the root event (relay keys on `root_event_id`, which a root row lacks); the caller already holds the root. */
/** Page events; callers merge chronologically. */
events: RelayEvent[];
/** Present only when a full page was returned — pass back to fetch the next page. */
/** Relay-authoritative; never infer from event count. */
hasMore: boolean;
/** Raw-scan continuation, present exactly with `hasMore`. */
nextCursor: ThreadCursor | null;
};
+90 -18
View File
@@ -339,7 +339,11 @@ type E2eConfig = {
/** Delay (ms) after snapshotting a thread-replies page so E2E tests can
* deliver live reply/aux events while an older response is in flight. */
threadRepliesDelayMs?: number;
/** Hold the first continuation page until the E2E release seam is called. */
holdThreadRepliesPage2?: boolean;
usersBatchDelayMs?: number;
/** Delay (ms) applied only to initial channel-window requests. */
initialChannelWindowDelayMs?: number;
/** Delay (ms) applied to continuation channel-window requests so e2e
* tests can observe the in-flight prepend window. 0/undefined = instant. */
channelWindowDelayMs?: number;
@@ -1111,6 +1115,16 @@ declare global {
command: string;
payload: unknown;
}>;
/** Start/end timestamps for deterministic message-performance assertions. */
__BUZZ_E2E_MESSAGE_REQUEST_LOG__?: Array<{
command: "get_channel_window" | "get_thread_replies";
endedAt: number | null;
payload: unknown;
requestId: number;
startedAt: number;
}>;
/** Release the held thread continuation page in the disposable A/B probe. */
__BUZZ_E2E_RELEASE_THREAD_PAGE_2__?: () => void;
/** Release a mock media proxy held at port 0 and return its ready port. */
__BUZZ_E2E_RELEASE_MEDIA_PROXY__?: () => number;
/** Release mock send events that were stored but withheld from live subscribers. */
@@ -4607,6 +4621,7 @@ type RawThreadCursor = {
type RawThreadRepliesResponse = {
events: RelayEvent[];
has_more: boolean;
next_cursor: RawThreadCursor | null;
};
@@ -4626,6 +4641,7 @@ async function handleGetThreadReplies(
limit?: number | null;
depthLimit?: number | null;
cursor?: RawThreadCursor | null;
threadOrder?: "oldest" | "newest" | null;
},
config: E2eConfig | undefined,
): Promise<RawThreadRepliesResponse> {
@@ -4699,23 +4715,35 @@ async function handleGetThreadReplies(
event_id: events[events.length - 1].id,
}
: null;
return { events, next_cursor: nextCursor };
return {
events,
has_more: nextCursor !== null,
next_cursor: nextCursor,
};
}
// Mock mode paging: sort by the composite key, then slice strictly after the
// cursor so same-second ties can never be skipped across a page boundary.
subtree.sort(
(left, right) =>
left.created_at - right.created_at || left.id.localeCompare(right.id),
);
const order = args.threadOrder ?? "oldest";
subtree.sort((left, right) => {
const chronological =
left.created_at - right.created_at || left.id.localeCompare(right.id);
if (order === "oldest") return chronological;
return (
right.created_at - left.created_at || right.id.localeCompare(left.id)
);
});
let start = 0;
if (args.cursor) {
const cursor = args.cursor;
start = subtree.findIndex(
(event) =>
event.created_at > cursor.created_at ||
(event.created_at === cursor.created_at &&
event.id.localeCompare(cursor.event_id) > 0),
start = subtree.findIndex((event) =>
order === "oldest"
? event.created_at > cursor.created_at ||
(event.created_at === cursor.created_at &&
event.id.localeCompare(cursor.event_id) > 0)
: event.created_at < cursor.created_at ||
(event.created_at === cursor.created_at &&
event.id.localeCompare(cursor.event_id) < 0),
);
if (start < 0) {
start = subtree.length;
@@ -4729,12 +4757,31 @@ async function handleGetThreadReplies(
event_id: page[page.length - 1].id,
}
: null;
if (
config?.mock?.holdThreadRepliesPage2 &&
args.cursor &&
window.__BUZZ_E2E_MESSAGE_REQUEST_LOG__?.filter(
(request) => request.command === "get_thread_replies",
).length === 2 &&
window.__BUZZ_E2E_RELEASE_THREAD_PAGE_2__ === undefined
) {
await new Promise<void>((resolve) => {
window.__BUZZ_E2E_RELEASE_THREAD_PAGE_2__ = () => {
delete window.__BUZZ_E2E_RELEASE_THREAD_PAGE_2__;
resolve();
};
});
}
const delayMs = config?.mock?.threadRepliesDelayMs ?? 0;
if (delayMs > 0) {
await new Promise((resolve) => window.setTimeout(resolve, delayMs));
}
return { events: page, next_cursor: nextCursor };
return {
events: page,
has_more: nextCursor !== null,
next_cursor: nextCursor,
};
}
const TIMELINE_KINDS = new Set([
@@ -5092,10 +5139,6 @@ async function handleGetChannelWindow(
return relayQuery(config, [filter]);
};
if (!args.cursor) {
return execute();
}
const probe = window as unknown as {
__CHANNEL_WINDOW_FETCH_COUNT__?: number;
__CHANNEL_WINDOW_INFLIGHT__?: number;
@@ -5104,7 +5147,9 @@ async function handleGetChannelWindow(
probe.__CHANNEL_WINDOW_FETCH_COUNT__ =
(probe.__CHANNEL_WINDOW_FETCH_COUNT__ ?? 0) + 1;
const delayMs = getConfig()?.mock?.channelWindowDelayMs ?? 0;
const delayMs = args.cursor
? (getConfig()?.mock?.channelWindowDelayMs ?? 0)
: (getConfig()?.mock?.initialChannelWindowDelayMs ?? 0);
if (delayMs <= 0) {
return execute();
}
@@ -10166,6 +10211,7 @@ export function maybeInstallE2eTauriMocks() {
window.__BUZZ_E2E_COMMANDS__ = [];
window.__BUZZ_E2E_COMMAND_PAYLOADS__ = [];
window.__BUZZ_E2E_COMMAND_LOG__ = [];
window.__BUZZ_E2E_MESSAGE_REQUEST_LOG__ = [];
mockMediaProxyPort = config.mock?.mediaProxyInitiallyUnavailable
? 0
: MOCK_MEDIA_PROXY_PORT;
@@ -13166,11 +13212,37 @@ export function maybeInstallE2eTauriMocks() {
throw new Error(`Unsupported mocked Tauri command: ${command}`);
}
};
const invokeMockCommand = async (
command: string,
payload: unknown,
): Promise<unknown> => {
const messageCommand =
command === "get_channel_window" || command === "get_thread_replies"
? command
: null;
if (!messageCommand) return handleMockCommand(command, payload);
const messageRequest: NonNullable<
typeof window.__BUZZ_E2E_MESSAGE_REQUEST_LOG__
>[number] = {
command: messageCommand,
endedAt: null,
payload,
requestId: window.__BUZZ_E2E_MESSAGE_REQUEST_LOG__?.length ?? 0,
startedAt: performance.now(),
};
window.__BUZZ_E2E_MESSAGE_REQUEST_LOG__?.push(messageRequest);
try {
return await handleMockCommand(command, payload);
} finally {
messageRequest.endedAt = performance.now();
}
};
window.__BUZZ_E2E_INVOKE_MOCK_COMMAND__ = (command, payload) =>
handleMockCommand(command, payload ?? null);
invokeMockCommand(command, payload ?? null);
window.__BUZZ_E2E_EMIT_TAURI_EVENT__ = (event, payload) =>
emit(event, payload);
mockIPC(handleMockCommand, { shouldMockEvents: true });
mockIPC(invokeMockCommand, { shouldMockEvents: true });
const tauriInternals = (
window as typeof window & {
__TAURI_INTERNALS__: {
@@ -0,0 +1,483 @@
import { expect, test, type Locator, type Page } from "@playwright/test";
import { installMockBridge } from "../helpers/bridge";
const GENERAL_CHANNEL_ID = "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50";
const RANDOM_CHANNEL_ID = "9dae0116-799b-5071-a0a8-fdd30a91a35d";
const DEEP_HISTORY_CHANNEL_ID = "feedf00d-0000-4000-8000-000000000007";
type MessageRequest = {
command: "get_channel_window" | "get_thread_replies";
endedAt: number | null;
payload: unknown;
requestId: number;
startedAt: number;
};
async function clearMessageRequests(page: Page) {
await page.evaluate(() => {
window.__BUZZ_E2E_MESSAGE_REQUEST_LOG__ = [];
});
}
async function readMessageRequests(
page: Page,
command: MessageRequest["command"],
): Promise<MessageRequest[]> {
return page.evaluate(
(targetCommand) =>
(window.__BUZZ_E2E_MESSAGE_REQUEST_LOG__ ?? []).filter(
(entry) => entry.command === targetCommand,
),
command,
);
}
async function openThread(root: Locator, page: Page) {
const timelineRoot = root.first();
await timelineRoot.hover();
await timelineRoot.getByRole("button", { name: "Reply" }).click();
const panel = page.getByTestId("message-thread-panel");
await expect(panel).toBeVisible();
return panel;
}
async function installChannelRevisitPaintTracking(page: Page) {
await page.evaluate(() => {
const tracking = {
cachedRowSeen: false,
cachedRowRemovedAfterPaint: false,
disconnect: () => {},
};
const inspect = () => {
const cachedRow = document.querySelector(
'[data-message-id^="mock-deep-history-"]',
);
if (cachedRow && !tracking.cachedRowSeen) {
tracking.cachedRowSeen = true;
}
if (tracking.cachedRowSeen && !cachedRow) {
tracking.cachedRowRemovedAfterPaint = true;
}
};
const observer = new MutationObserver(inspect);
observer.observe(document.body, { childList: true, subtree: true });
tracking.disconnect = () => observer.disconnect();
inspect();
(
window as typeof window & {
__MESSAGE_REVISIT_PAINT__?: typeof tracking;
}
).__MESSAGE_REVISIT_PAINT__ = tracking;
});
}
async function readChannelRevisitPaintTracking(page: Page) {
return page.evaluate(() => {
const tracking = (
window as typeof window & {
__MESSAGE_REVISIT_PAINT__?: {
cachedRowSeen: boolean;
cachedRowRemovedAfterPaint: boolean;
disconnect: () => void;
};
}
).__MESSAGE_REVISIT_PAINT__;
if (!tracking) throw new Error("revisit paint observer was not installed");
tracking.disconnect();
return tracking;
});
}
test("cold channel load keeps its skeleton; fresh and stale revisits keep cached rows painted", async ({
page,
}) => {
await installMockBridge(page, { initialChannelWindowDelayMs: 700 });
await page.goto("/");
await page.getByTestId("channel-general").click();
await expect(page.getByTestId("chat-title")).toHaveText("general");
await expect(
page.locator('[data-message-id="mock-general-welcome"]'),
).toBeVisible();
await clearMessageRequests(page);
await page.getByTestId("channel-deep-history").click();
await expect(page.getByTestId("chat-title")).toHaveText("deep-history");
// Negative guard: a genuinely cold query still holds the timeline skeleton.
await expect(page.getByTestId("message-timeline-loading")).toBeVisible();
await expect
.poll(() => readMessageRequests(page, "get_channel_window"))
.toHaveLength(1);
await expect(
page.locator('[data-message-id^="mock-deep-history-"]').first(),
).toBeVisible();
await expect(page.getByTestId("message-timeline-loading")).toHaveCount(0);
await page.getByTestId("channel-general").click();
await expect(page.getByTestId("chat-title")).toHaveText("general");
await clearMessageRequests(page);
await installChannelRevisitPaintTracking(page);
// A fresh warm revisit remains painted across the required
// post-subscription reconciliation.
await page.getByTestId("channel-deep-history").click();
await expect(
page.locator('[data-message-id^="mock-deep-history-"]').first(),
).toBeVisible();
await expect
.poll(() => readMessageRequests(page, "get_channel_window"))
.toHaveLength(1);
await expect
.poll(async () =>
(await readMessageRequests(page, "get_channel_window")).every(
(request) => request.endedAt !== null,
),
)
.toBe(true);
await expect(
page.locator('[data-message-id^="mock-deep-history-"]').first(),
).toBeVisible();
const freshRevisit = await readChannelRevisitPaintTracking(page);
expect(freshRevisit.cachedRowSeen).toBe(true);
expect(freshRevisit.cachedRowRemovedAfterPaint).toBe(false);
await page.getByTestId("channel-general").click();
await expect(page.getByTestId("chat-title")).toHaveText("general");
// Make the now-inactive message cache older than its five-minute staleTime
// while retaining the authoritative channel-window proof.
await page.evaluate((channelId) => {
const queryClient = window.__BUZZ_E2E_QUERY_CLIENT__ as unknown as {
getQueryData: (key: readonly unknown[]) => unknown;
removeQueries: (filters: { queryKey: readonly unknown[] }) => void;
setQueryData: (
key: readonly unknown[],
data: unknown,
options?: { updatedAt?: number },
) => void;
};
const key = ["channel-messages", channelId] as const;
const cachedMessages = queryClient.getQueryData(key);
queryClient.removeQueries({ queryKey: key });
queryClient.setQueryData(key, cachedMessages, {
updatedAt: Date.now() - 10 * 60 * 1_000,
});
}, DEEP_HISTORY_CHANNEL_ID);
await clearMessageRequests(page);
await installChannelRevisitPaintTracking(page);
const staleRevisitStartedAt = await page.evaluate(() => performance.now());
// A >5-minute stale revisit keeps cached rows painted while one delayed
// initial-window reconciliation runs behind it.
await page.getByTestId("channel-deep-history").click();
await expect(
page.locator('[data-message-id^="mock-deep-history-"]').first(),
).toBeVisible();
const staleRevisit = await readChannelRevisitPaintTracking(page);
expect(staleRevisit.cachedRowSeen).toBe(true);
expect(staleRevisit.cachedRowRemovedAfterPaint).toBe(false);
await expect
.poll(async () => {
const requests = await readMessageRequests(page, "get_channel_window");
return requests.some(
(request) =>
request.startedAt >= staleRevisitStartedAt &&
request.endedAt === null,
);
})
.toBe(true);
const staleRevalidation = (
await readMessageRequests(page, "get_channel_window")
).find(
(request) =>
request.startedAt >= staleRevisitStartedAt && request.endedAt === null,
);
expect(staleRevalidation).toBeDefined();
expect(staleRevalidation?.endedAt).toBeNull();
await expect
.poll(
async () =>
(await readMessageRequests(page, "get_channel_window")).find(
(request) => request.requestId === staleRevalidation?.requestId,
)?.endedAt,
)
.not.toBeNull();
});
test("thread cache paints on fresh reopen and while a stale cache revalidates", async ({
page,
}) => {
await installMockBridge(page, { threadRepliesDelayMs: 700 });
await page.goto("/");
await page.getByTestId("channel-general").click();
await expect(page.getByTestId("chat-title")).toHaveText("general");
const root = page.locator('[data-message-id="mock-general-welcome"]');
await expect(root).toBeVisible();
const reply = await page.evaluate((parentEventId) => {
const emit = window.__BUZZ_E2E_EMIT_MOCK_MESSAGE__;
if (!emit) throw new Error("mock message emitter is unavailable");
return emit({
channelName: "general",
content: "Cached thread reply",
parentEventId,
});
}, "mock-general-welcome");
let panel = await openThread(root, page);
await expect(panel.locator(`[data-message-id="${reply.id}"]`)).toContainText(
"Cached thread reply",
);
await expect
.poll(async () => {
const requests = await readMessageRequests(page, "get_thread_replies");
return requests.length === 1 && requests[0].endedAt !== null;
})
.toBe(true);
await panel.getByTestId("auxiliary-panel-close").click();
await expect(panel).toHaveCount(0);
// Every reopen paints the cache immediately and revalidates in background.
await clearMessageRequests(page);
panel = await openThread(root, page);
await expect(panel.locator(`[data-message-id="${reply.id}"]`)).toBeVisible();
await expect(panel.getByTestId("message-thread-replies-loading")).toHaveCount(
0,
);
await expect
.poll(() => readMessageRequests(page, "get_thread_replies"))
.toHaveLength(1);
const [freshRevalidation] = await readMessageRequests(
page,
"get_thread_replies",
);
expect(freshRevalidation.endedAt).toBeNull();
await expect
.poll(
async () =>
(await readMessageRequests(page, "get_thread_replies"))[0]?.endedAt,
)
.not.toBeNull();
// Negative guard: once genuinely stale, the same cached row remains painted
// while a delayed background reconciliation is in flight.
await panel.getByTestId("auxiliary-panel-close").click();
await expect(panel).toHaveCount(0);
await page.evaluate(
async ({ channelId, rootId }) => {
const queryClient = window.__BUZZ_E2E_QUERY_CLIENT__ as unknown as {
getQueryData: (key: readonly unknown[]) => unknown;
removeQueries: (filters: { queryKey: readonly unknown[] }) => void;
setQueryData: (
key: readonly unknown[],
data: unknown,
options?: { updatedAt?: number },
) => void;
};
const key = ["thread-replies", channelId, rootId] as const;
const cachedReplies = queryClient.getQueryData(key);
queryClient.removeQueries({ queryKey: key });
queryClient.setQueryData(key, cachedReplies, {
updatedAt: Date.now() - 10 * 60 * 1_000,
});
},
{ channelId: GENERAL_CHANNEL_ID, rootId: "mock-general-welcome" },
);
await clearMessageRequests(page);
await page.evaluate((replyId) => {
const tracking = {
cachedReplyFrameAt: null as number | null,
disconnect: () => {},
};
let framePending = false;
const inspect = () => {
if (tracking.cachedReplyFrameAt !== null || framePending) return;
if (!document.querySelector(`[data-message-id="${replyId}"]`)) return;
framePending = true;
requestAnimationFrame(() => {
tracking.cachedReplyFrameAt = performance.now();
framePending = false;
});
};
const observer = new MutationObserver(inspect);
observer.observe(document.body, { childList: true, subtree: true });
tracking.disconnect = () => observer.disconnect();
inspect();
(
window as typeof window & {
__THREAD_CACHE_PAINT__?: typeof tracking;
}
).__THREAD_CACHE_PAINT__ = tracking;
}, reply.id);
panel = await openThread(root, page);
await expect(panel.locator(`[data-message-id="${reply.id}"]`)).toBeVisible();
await expect
.poll(() =>
page.evaluate(
() =>
(
window as typeof window & {
__THREAD_CACHE_PAINT__?: { cachedReplyFrameAt: number | null };
}
).__THREAD_CACHE_PAINT__?.cachedReplyFrameAt ?? null,
),
)
.not.toBeNull();
const cachedPaintedAt = await page.evaluate(() => {
const tracking = (
window as typeof window & {
__THREAD_CACHE_PAINT__?: {
cachedReplyFrameAt: number | null;
disconnect: () => void;
};
}
).__THREAD_CACHE_PAINT__;
if (!tracking?.cachedReplyFrameAt) {
throw new Error("cached thread reply paint was not observed");
}
tracking.disconnect();
return tracking.cachedReplyFrameAt;
});
await expect(panel.getByTestId("message-thread-replies-loading")).toHaveCount(
0,
);
await expect
.poll(() => readMessageRequests(page, "get_thread_replies"))
.toHaveLength(1);
await expect
.poll(
async () =>
(await readMessageRequests(page, "get_thread_replies"))[0]?.endedAt,
)
.not.toBeNull();
const [revalidation] = await readMessageRequests(page, "get_thread_replies");
expect(revalidation.startedAt).toBeLessThanOrEqual(cachedPaintedAt);
expect(revalidation.endedAt ?? 0).toBeGreaterThanOrEqual(cachedPaintedAt);
await expect(panel.locator(`[data-message-id="${reply.id}"]`)).toBeVisible();
});
test("401-reply thread paints page 1, preserves a live arrival, and converges", async ({
page,
}) => {
await installMockBridge(page, {
holdThreadRepliesPage2: true,
threadRepliesDelayMs: 25,
});
await page.goto("/");
await page.getByTestId("channel-general").click();
await expect(page.getByTestId("chat-title")).toHaveText("general");
const seeded = await page.evaluate(() => {
const emit = window.__BUZZ_E2E_EMIT_MOCK_MESSAGE__;
if (!emit) throw new Error("mock message emitter is unavailable");
const root = emit({ channelName: "random", content: "Large thread root" });
const replyIds: string[] = [];
for (let index = 0; index < 401; index += 1) {
replyIds.push(
emit({
channelName: "random",
content: `Large thread reply ${index}`,
createdAt: 1_700_000_000 + index,
parentEventId: root.id,
}).id,
);
}
return { rootId: root.id, replyIds };
});
await page.getByTestId("channel-random").click();
await expect(page.getByTestId("chat-title")).toHaveText("random");
const root = page.locator(`[data-message-id="${seeded.rootId}"]`);
await expect(root).toBeVisible();
await clearMessageRequests(page);
const panel = await openThread(root, page);
// Page 2 is deliberately held. The newest page must already be useful; a
// skeleton or wait-for-convergence implementation cannot satisfy this.
await expect
.poll(() => readMessageRequests(page, "get_thread_replies"))
.toHaveLength(2);
const pageTwoPending = await readMessageRequests(page, "get_thread_replies");
expect(pageTwoPending[0].endedAt).not.toBeNull();
expect(pageTwoPending[1].endedAt).toBeNull();
expect((pageTwoPending[0].payload as { limit?: number }).limit).toBe(200);
expect(
(pageTwoPending[0].payload as { threadOrder?: string }).threadOrder,
).toBe("newest");
await expect(panel).toContainText("Large thread reply 400");
await expect(panel).not.toContainText("Large thread reply 0");
await expect(panel.getByTestId("message-thread-replies-loading")).toHaveCount(
0,
);
const liveReply = await page.evaluate((parentEventId) => {
const emit = window.__BUZZ_E2E_EMIT_MOCK_MESSAGE__;
if (!emit) throw new Error("mock message emitter is unavailable");
return emit({
channelName: "random",
content: "Live reply during pagination",
createdAt: 1_700_000_500,
parentEventId,
});
}, seeded.rootId);
await expect(
panel.locator(`[data-message-id="${liveReply.id}"]`),
).toBeVisible();
await page.evaluate(() => {
const release = window.__BUZZ_E2E_RELEASE_THREAD_PAGE_2__;
if (!release) throw new Error("thread page 2 was not held");
release();
});
await expect
.poll(async () => {
const requests = await readMessageRequests(page, "get_thread_replies");
return (
requests.length === 3 &&
requests.every((request) => request.endedAt !== null)
);
})
.toBe(true);
const convergence = await page.evaluate(
({ channelId, rootId, expectedIds, liveId }) => {
const queryClient = window.__BUZZ_E2E_QUERY_CLIENT__ as unknown as {
getQueryData: (key: readonly unknown[]) =>
| Array<{
created_at: number;
id: string;
}>
| undefined;
};
const replies =
queryClient.getQueryData(["thread-replies", channelId, rootId]) ?? [];
const ids = replies.map((reply) => reply.id);
return {
chronological: replies.every(
(reply, index) =>
index === 0 ||
replies[index - 1].created_at < reply.created_at ||
(replies[index - 1].created_at === reply.created_at &&
replies[index - 1].id.localeCompare(reply.id) <= 0),
),
exactSeedSet: expectedIds.every((id) => ids.includes(id)),
liveCount: ids.filter((id) => id === liveId).length,
total: ids.length,
unique: new Set(ids).size,
};
},
{
channelId: RANDOM_CHANNEL_ID,
rootId: seeded.rootId,
expectedIds: seeded.replyIds,
liveId: liveReply.id,
},
);
expect(convergence).toEqual({
chronological: true,
exactSeedSet: true,
liveCount: 1,
total: 402,
unique: 402,
});
});
+4
View File
@@ -293,7 +293,11 @@ type MockBridgeOptions = {
/** Delay (ms) after snapshotting a thread-replies page so E2E tests can
* deliver live reply/aux events while an older response is in flight. */
threadRepliesDelayMs?: number;
/** Hold page 2 until the E2E release seam is called. */
holdThreadRepliesPage2?: boolean;
usersBatchDelayMs?: number;
/** Delay (ms) for initial channel-window requests. */
initialChannelWindowDelayMs?: number;
/** Delay (ms) for older-history fetches; see e2eBridge mock config. */
channelWindowDelayMs?: number;
profileReadDelayMs?: number;