feat(chat): implement pull-to-refresh functionality and pagination for chat history

This commit is contained in:
2026-07-15 18:19:35 +08:00
parent 05ca15be48
commit c37a2f9040
21 changed files with 892 additions and 66 deletions
+10 -1
View File
@@ -5,7 +5,10 @@ import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
import { useChatState } from "@/stores/chat/chat-context";
import {
useChatDispatch,
useChatState,
} from "@/stores/chat/chat-context";
import { ROUTES } from "@/router/routes";
import { MobileShell } from "@/app/_components/core";
@@ -45,6 +48,7 @@ export function ChatScreen() {
const router = useRouter();
const searchParams = useSearchParams();
const state = useChatState();
const chatDispatch = useChatDispatch();
const authState = useAuthState();
const authDispatch = useAuthDispatch();
useSplashLatestMessageSync({
@@ -232,12 +236,17 @@ export function ChatScreen() {
initialScrollReady={
state.historyLoaded && isPromotionBootstrapReady
}
canLoadMoreHistory={state.hasMoreHistory}
isLoadingMoreHistory={state.isLoadingMoreHistory}
isUnlockingMessage={state.isUnlockingMessage}
unlockingMessageId={state.unlockingMessageId}
onUnlockPrivateMessage={handleUnlockPrivateMessage}
onUnlockVoiceMessage={handleUnlockVoiceMessage}
onUnlockImageMessage={handleUnlockImageMessage}
onOpenImage={handleOpenImage}
onLoadMoreHistory={() => {
chatDispatch({ type: "ChatLoadMoreHistoryRequested" });
}}
/>
{messageLimitBanner.visible ? (
@@ -144,12 +144,47 @@ describe("ChatArea scrolling", () => {
expect(scrollNode.scrollTop).toBe(100);
});
it("preserves the visible message after older history is prepended", () => {
scrollHeight = 1_000;
clientHeight = 300;
const onLoadMoreHistory = vi.fn();
const history = [createMessage("history-1")];
renderChatArea(root, history, true, {
canLoadMoreHistory: true,
onLoadMoreHistory,
});
const scrollNode = getScrollNode(container);
scrollNode.scrollTop = 0;
act(() => scrollNode.dispatchEvent(new Event("scroll", { bubbles: true })));
pull(scrollNode, 180);
expect(onLoadMoreHistory).toHaveBeenCalledOnce();
scrollHeight = 1_400;
renderChatArea(
root,
[createMessage("older-1"), ...history],
true,
{
canLoadMoreHistory: true,
onLoadMoreHistory,
},
);
expect(scrollNode.scrollTop).toBe(400);
});
});
function renderChatArea(
root: Root,
messages: readonly UiMessage[],
initialScrollReady: boolean,
historyOptions: {
canLoadMoreHistory?: boolean;
isLoadingMoreHistory?: boolean;
onLoadMoreHistory?: () => void;
} = {},
): void {
act(() => {
root.render(
@@ -157,11 +192,32 @@ function renderChatArea(
messages={messages}
isReplyingAI={false}
initialScrollReady={initialScrollReady}
{...historyOptions}
/>,
);
});
}
function pull(target: HTMLElement, distance: number): void {
act(() => {
target.dispatchEvent(createTouchEvent("touchstart", 0));
target.dispatchEvent(createTouchEvent("touchmove", distance));
target.dispatchEvent(createTouchEvent("touchend", distance, true));
});
}
function createTouchEvent(
type: string,
clientY: number,
ended = false,
): Event {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperty(event, "touches", {
value: ended ? [] : [{ identifier: 1, clientY }],
});
return event;
}
function createMessage(id: string): UiMessage {
return {
id,
@@ -45,7 +45,7 @@ export function BrowserHintOverlay({
onClick={handleClick}
>
<span
className="inline-flex size-7.5 items-center justify-center rounded-full bg-(--color-accent,#f84d96) text-white shadow-[0_4px_12px_rgba(248,77,150,0.34)]"
className="inline-flex size-7.5 items-center justify-center rounded-full bg-accent text-white shadow-[0_4px_12px_rgba(248,77,150,0.34)]"
aria-hidden="true"
>
<ExternalLink size={15} strokeWidth={2.4} />
@@ -54,7 +54,7 @@ export function BrowserHintOverlay({
<span className="wrap-break-word text-(length:--font-size-sm,12px) font-extrabold leading-tight text-white">
{title}
</span>
<span className="wrap-break-word text-[11px] font-semibold leading-[1.25] text-[#f3dfe8]">
<span className="wrap-break-word text-[11px] font-semibold leading-tight text-[#f3dfe8]">
{description}
</span>
</span>
@@ -1,9 +1,13 @@
/* ChatArea 消息列表样式 */
.area {
--chat-pull-offset: 0px;
position: relative;
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
overscroll-behavior-y: contain;
padding:
var(--spacing-lg, 16px)
calc(var(--chat-inline-padding, 20px) + var(--app-safe-right, 0px))
@@ -11,11 +15,49 @@
calc(var(--chat-inline-padding, 20px) + var(--app-safe-left, 0px));
}
.pullIndicator {
position: absolute;
top: var(--spacing-sm, 8px);
left: 50%;
z-index: 2;
display: inline-flex;
min-height: 34px;
align-items: center;
gap: 7px;
padding: 0 12px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 999px;
background: rgba(24, 20, 30, 0.86);
color: rgba(255, 255, 255, 0.9);
font-size: var(--responsive-caption, var(--font-size-sm, 12px));
font-weight: 700;
opacity: 1;
pointer-events: none;
transform: translate(-50%, calc(var(--chat-pull-offset) - 42px));
white-space: nowrap;
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.28);
}
.pullIndicator[aria-hidden="true"] {
opacity: 0;
}
.pullIndicator svg[data-spinning="true"] {
animation: pullIndicatorSpin 0.8s linear infinite;
}
.content {
display: flex;
flex-direction: column;
gap: var(--spacing-3, 12px);
min-width: 0;
transform: translateY(var(--chat-pull-offset));
transition: transform 180ms ease;
will-change: transform;
}
.area[data-pulling="true"] .content {
transition: none;
}
.dateHeader {
@@ -143,3 +185,9 @@
0%, 60%, 100% { opacity: 0.2; }
30% { opacity: 1; }
}
@keyframes pullIndicatorSpin {
to {
transform: rotate(360deg);
}
}
+74 -1
View File
@@ -15,13 +15,16 @@
import {
lazy,
Suspense,
type CSSProperties,
useEffect,
useLayoutEffect,
useMemo,
useRef,
} from "react";
import { LoaderCircle } from "lucide-react";
import type { UiMessage } from "@/data/dto/chat";
import { usePullToRefresh } from "@/hooks/use-pull-to-refresh";
import {
buildChatRenderItems,
@@ -34,6 +37,7 @@ import { MessageBubble } from "./message-bubble";
import styles from "./chat-area.module.css";
const CHAT_AUTO_SCROLL_BOTTOM_THRESHOLD = 96;
const CHAT_PULL_LOADING_OFFSET = 46;
const ReplyingAnimation = lazy(() =>
import("./lottie-message-bubble").then((module) => ({
default: module.LottieMessageBubble,
@@ -44,30 +48,69 @@ export interface ChatAreaProps {
messages: readonly UiMessage[];
isReplyingAI: boolean;
initialScrollReady?: boolean;
canLoadMoreHistory?: boolean;
isLoadingMoreHistory?: boolean;
isUnlockingMessage?: boolean;
unlockingMessageId?: string | null;
onUnlockPrivateMessage?: (messageId: string) => void;
onUnlockVoiceMessage?: (messageId: string) => void;
onUnlockImageMessage?: (messageId: string) => void;
onOpenImage?: (messageId: string) => void;
onLoadMoreHistory?: () => void;
}
export function ChatArea({
messages,
isReplyingAI,
initialScrollReady = true,
canLoadMoreHistory = false,
isLoadingMoreHistory = false,
isUnlockingMessage,
unlockingMessageId,
onUnlockPrivateMessage,
onUnlockVoiceMessage,
onUnlockImageMessage,
onOpenImage,
onLoadMoreHistory,
}: ChatAreaProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const initialScrollSettledRef = useRef(false);
const shouldStickToBottomRef = useRef(true);
const loadMoreAnchorRef = useRef<{
scrollHeight: number;
scrollTop: number;
} | null>(null);
const getMessageKey = useMemo(() => createChatMessageKeyResolver(), []);
const {
isPulling,
isRefreshing,
isReleaseReady,
pullDistance,
touchHandlers,
} = usePullToRefresh(
(scrollNode) => {
if (!onLoadMoreHistory) return;
loadMoreAnchorRef.current = {
scrollHeight: scrollNode.scrollHeight,
scrollTop: scrollNode.scrollTop,
};
shouldStickToBottomRef.current = false;
onLoadMoreHistory();
},
{
disabled:
!initialScrollReady || !canLoadMoreHistory || !onLoadMoreHistory,
refreshing: isLoadingMoreHistory,
},
);
const pullOffset = isRefreshing
? CHAT_PULL_LOADING_OFFSET
: pullDistance;
const pullStyle = {
"--chat-pull-offset": `${pullOffset}px`,
} as CSSProperties;
const showPullIndicator = pullOffset > 0;
useLayoutEffect(() => {
if (!initialScrollReady) {
@@ -78,6 +121,16 @@ export function ChatArea({
const scrollNode = scrollRef.current;
if (!scrollNode) return;
if (loadMoreAnchorRef.current && !isLoadingMoreHistory) {
const anchor = loadMoreAnchorRef.current;
loadMoreAnchorRef.current = null;
scrollNode.scrollTop = Math.max(
0,
anchor.scrollTop + scrollNode.scrollHeight - anchor.scrollHeight,
);
return;
}
if (!initialScrollSettledRef.current) {
initialScrollSettledRef.current = true;
shouldStickToBottomRef.current = true;
@@ -96,7 +149,7 @@ export function ChatArea({
});
return () => cancelAnimationFrame(frameId);
}, [initialScrollReady, isReplyingAI, messages]);
}, [initialScrollReady, isLoadingMoreHistory, isReplyingAI, messages]);
useEffect(() => {
const scrollNode = scrollRef.current;
@@ -124,10 +177,30 @@ export function ChatArea({
ref={scrollRef}
className={styles.area}
aria-label="Chat messages"
data-pulling={isPulling ? "true" : "false"}
style={pullStyle}
{...touchHandlers}
onScroll={(event) => {
shouldStickToBottomRef.current = isNearBottom(event.currentTarget);
}}
>
<div
className={styles.pullIndicator}
aria-hidden={!showPullIndicator}
>
<LoaderCircle
size={17}
aria-hidden="true"
data-spinning={isRefreshing ? "true" : "false"}
/>
<span>
{isRefreshing
? "Loading earlier messages..."
: isReleaseReady
? "Release to load earlier messages"
: "Pull down for earlier messages"}
</span>
</div>
<div ref={contentRef} className={styles.content}>
<AiDisclosureBanner />
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { ChatHistoryResponse } from "@/data/dto/chat";
describe("ChatHistoryResponse", () => {
it("exposes the pagination total and limit used by chat history", () => {
const response = ChatHistoryResponse.from({
messages: [],
total: 120,
limit: 50,
offset: 0,
});
expect(response.total).toBe(120);
expect(response.limit).toBe(50);
});
});
@@ -10,6 +10,8 @@ import { ChatMessage } from "../chat_message";
export class ChatHistoryResponse {
declare readonly messages: ChatMessage[];
declare readonly total: number;
declare readonly limit: number;
private constructor(input: ChatHistoryResponseInput) {
const data = ChatHistoryResponseSchema.parse(input);
@@ -0,0 +1,110 @@
/* @vitest-environment jsdom */
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { usePullToRefresh } from "../use-pull-to-refresh";
function Harness({
disabled = false,
refreshing,
onRefresh,
}: {
disabled?: boolean;
refreshing?: boolean;
onRefresh: () => Promise<void> | void;
}) {
const pull = usePullToRefresh(() => onRefresh(), {
disabled,
refreshing,
});
return (
<div
aria-label="Pull container"
data-distance={pull.pullDistance}
data-pulling={pull.isPulling}
{...pull.touchHandlers}
/>
);
}
describe("usePullToRefresh", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
.IS_REACT_ACT_ENVIRONMENT = true;
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(() => {
act(() => root.unmount());
container.remove();
});
it("triggers once after pulling beyond the threshold", () => {
const onRefresh = vi.fn();
act(() => root.render(<Harness onRefresh={onRefresh} />));
const target = getTarget(container);
pull(target, 180);
expect(onRefresh).toHaveBeenCalledOnce();
});
it("does not trigger below the threshold or while disabled", () => {
const onRefresh = vi.fn();
act(() => root.render(<Harness onRefresh={onRefresh} />));
pull(getTarget(container), 80);
expect(onRefresh).not.toHaveBeenCalled();
act(() =>
root.render(<Harness disabled onRefresh={onRefresh} />),
);
pull(getTarget(container), 180);
expect(onRefresh).not.toHaveBeenCalled();
});
it("blocks another gesture while refresh is externally controlled", () => {
const onRefresh = vi.fn();
act(() =>
root.render(<Harness refreshing onRefresh={onRefresh} />),
);
pull(getTarget(container), 180);
expect(onRefresh).not.toHaveBeenCalled();
});
});
function getTarget(container: HTMLElement): HTMLDivElement {
const target = container.querySelector<HTMLDivElement>(
'[aria-label="Pull container"]',
);
if (!target) throw new Error("Pull container was not rendered");
return target;
}
function pull(target: HTMLDivElement, distance: number): void {
act(() => {
target.dispatchEvent(createTouchEvent("touchstart", 0));
target.dispatchEvent(createTouchEvent("touchmove", distance));
target.dispatchEvent(createTouchEvent("touchend", distance, true));
});
}
function createTouchEvent(
type: string,
clientY: number,
ended = false,
): Event {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperty(event, "touches", {
value: ended ? [] : [{ identifier: 1, clientY }],
});
return event;
}
+129 -59
View File
@@ -1,69 +1,139 @@
"use client";
/**
* 下拉刷新 hook(占位实现)
*
*
*
* 当前实现:最小可用版本 —— 监听顶部 overscroll 触发 onRefresh。
* 后续可替换为 react-use / react-easy-refresh。
*/
import { useEffect, useRef, useState } from "react";
import {
useEffect,
useRef,
useState,
type TouchEvent as ReactTouchEvent,
} from "react";
export interface PullToRefreshOptions {
threshold?: number;
maxPullDistance?: number;
disabled?: boolean;
refreshing?: boolean;
}
export interface PullToRefreshTouchHandlers {
onTouchStart: (event: ReactTouchEvent<HTMLDivElement>) => void;
onTouchMove: (event: ReactTouchEvent<HTMLDivElement>) => void;
onTouchEnd: (event: ReactTouchEvent<HTMLDivElement>) => void;
onTouchCancel: () => void;
}
export interface PullToRefreshState {
isRefreshing: boolean;
isPulling: boolean;
isReleaseReady: boolean;
pullDistance: number;
touchHandlers: PullToRefreshTouchHandlers;
}
export function usePullToRefresh(
onRefresh: () => Promise<void> | void,
options: { threshold?: number; disabled?: boolean } = {},
): {
isRefreshing: boolean;
pullDistance: number;
containerRef: React.RefObject<HTMLDivElement | null>;
} {
const { threshold = 80, disabled = false } = options;
const [isRefreshing, setIsRefreshing] = useState(false);
onRefresh: (container: HTMLDivElement) => Promise<void> | void,
options: PullToRefreshOptions = {},
): PullToRefreshState {
const {
threshold = 72,
maxPullDistance = threshold * 1.5,
disabled = false,
refreshing,
} = options;
const [internalRefreshing, setInternalRefreshing] = useState(false);
const [isPulling, setIsPulling] = useState(false);
const [pullDistance, setPullDistance] = useState(0);
const startY = useRef<number | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
const startYRef = useRef<number | null>(null);
const touchIdRef = useRef<number | null>(null);
const pullDistanceRef = useRef(0);
const refreshPendingRef = useRef(false);
const mountedRef = useRef(true);
const isRefreshing = refreshing ?? internalRefreshing;
useEffect(() => {
if (disabled || typeof window === "undefined") return;
const el = containerRef.current;
if (!el) return;
const onTouchStart = (e: TouchEvent) => {
if (el.scrollTop > 0) return;
startY.current = e.touches[0]?.clientY ?? null;
};
const onTouchMove = (e: TouchEvent) => {
if (startY.current == null) return;
const y = e.touches[0]?.clientY ?? startY.current;
const delta = y - startY.current;
if (delta > 0 && el.scrollTop <= 0) {
setPullDistance(Math.min(delta, threshold * 1.5));
}
};
const onTouchEnd = async () => {
if (startY.current == null) return;
if (pullDistance >= threshold && !isRefreshing) {
setIsRefreshing(true);
try {
await onRefresh();
} finally {
setIsRefreshing(false);
setPullDistance(0);
}
} else {
setPullDistance(0);
}
startY.current = null;
};
el.addEventListener("touchstart", onTouchStart, { passive: true });
el.addEventListener("touchmove", onTouchMove, { passive: true });
el.addEventListener("touchend", onTouchEnd);
return () => {
el.removeEventListener("touchstart", onTouchStart);
el.removeEventListener("touchmove", onTouchMove);
el.removeEventListener("touchend", onTouchEnd);
mountedRef.current = false;
};
}, [threshold, disabled, isRefreshing, onRefresh, pullDistance]);
}, []);
return { isRefreshing, pullDistance, containerRef };
const resetGesture = () => {
startYRef.current = null;
touchIdRef.current = null;
pullDistanceRef.current = 0;
setIsPulling(false);
setPullDistance(0);
};
const runRefresh = async (container: HTMLDivElement) => {
if (refreshPendingRef.current || isRefreshing) return;
refreshPendingRef.current = true;
if (refreshing === undefined) setInternalRefreshing(true);
try {
await onRefresh(container);
} finally {
refreshPendingRef.current = false;
if (refreshing === undefined && mountedRef.current) {
setInternalRefreshing(false);
}
}
};
const onTouchStart = (event: ReactTouchEvent<HTMLDivElement>) => {
const element = event.currentTarget;
if (disabled || isRefreshing || element.scrollTop > 0) return;
const touch = event.touches[0];
if (!touch || event.touches.length !== 1) return;
startYRef.current = touch.clientY;
touchIdRef.current = touch.identifier;
setIsPulling(true);
};
const onTouchMove = (event: ReactTouchEvent<HTMLDivElement>) => {
if (
disabled ||
isRefreshing ||
startYRef.current === null ||
touchIdRef.current === null
) {
return;
}
const touch = Array.from(event.touches).find(
(item) => item.identifier === touchIdRef.current,
);
if (!touch) return;
const delta = touch.clientY - startYRef.current;
if (delta <= 0 || event.currentTarget.scrollTop > 0) {
pullDistanceRef.current = 0;
setPullDistance(0);
return;
}
event.preventDefault();
const nextDistance = Math.min(maxPullDistance, delta * 0.55);
pullDistanceRef.current = nextDistance;
setPullDistance(nextDistance);
};
const onTouchEnd = (event: ReactTouchEvent<HTMLDivElement>) => {
if (startYRef.current === null) return;
const shouldRefresh =
!disabled &&
!isRefreshing &&
pullDistanceRef.current >= threshold;
resetGesture();
if (shouldRefresh) void runRefresh(event.currentTarget);
};
const effectivePullDistance = disabled || isRefreshing ? 0 : pullDistance;
return {
isRefreshing,
isPulling: !disabled && !isRefreshing && isPulling,
isReleaseReady: effectivePullDistance >= threshold,
pullDistance: effectivePullDistance,
touchHandlers: {
onTouchStart,
onTouchMove,
onTouchEnd,
onTouchCancel: resetGesture,
},
};
}
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import { ChatSendResponse } from "@/data/dto/chat";
import type { ChatState } from "@/stores/chat/chat-state";
import {
applyNetworkHistoryLoadedOutput,
applyHttpSendOutput,
countLockedHistoryMessages,
localMessagesToUi,
@@ -40,6 +41,10 @@ function makeChatState(overrides: Partial<ChatState> = {}): ChatState {
requiredCredits: 0,
shortfallCredits: 0,
historyLoaded: true,
historyTotal: 0,
historyLimit: 50,
nextHistoryOffset: 0,
isLoadingMoreHistory: false,
paymentUnlockPending: false,
unlockHistoryPromptVisible: false,
lockedHistoryCount: 0,
@@ -244,6 +249,21 @@ describe("applyHttpSendOutput", () => {
});
});
describe("chat history pagination helpers", () => {
it("falls back to the bounded history limit when the backend limit is zero", () => {
const nextState = applyNetworkHistoryLoadedOutput(makeChatState(), {
messages: [],
localCount: 0,
total: 120,
limit: 0,
});
expect(nextState.historyLimit).toBe(50);
expect(nextState.nextHistoryOffset).toBe(50);
expect(nextState.historyTotal).toBe(120);
});
});
describe("localMessagesToUi", () => {
it("maps locked voice messages from history", () => {
const [message] = localMessagesToUi([
@@ -4,8 +4,12 @@ import { createActor, fromCallback, waitFor } from "xstate";
import type { UiMessage } from "@/data/dto/chat";
import type { ChatEvent } from "@/stores/chat/chat-events";
import { chatMachine } from "@/stores/chat/chat-machine";
import type { LoadMoreHistoryActorEvent } from "@/stores/chat/machine/actors/history";
import { createTestChatMachine } from "./chat-machine.test-utils";
import {
createLoadHistoryCallback,
createTestChatMachine,
} from "./chat-machine.test-utils";
describe("chat history flow", () => {
it("enters user ready after history is loaded", async () => {
@@ -57,6 +61,8 @@ describe("chat history flow", () => {
localOverwritten: true,
localCount: 1,
networkCount: 1,
total: 1,
limit: 50,
},
});
});
@@ -87,4 +93,182 @@ describe("chat history flow", () => {
actor.stop();
});
it("loads older pages until total is exhausted and keeps existing messages", async () => {
const requests: LoadMoreHistoryActorEvent[] = [];
const latestMessage: UiMessage = {
id: "latest",
content: "current unlocked message",
isFromAI: true,
date: "2026-07-15",
};
const machine = chatMachine.provide({
actors: {
loadHistory: createLoadHistoryCallback(
[latestMessage],
[latestMessage],
{ total: 120, limit: 50 },
),
loadMoreHistory: fromCallback<LoadMoreHistoryActorEvent>(
({ receive, sendBack }) => {
receive((event) => {
requests.push(event);
if (event.offset === 50) {
sendBack({
type: "ChatOlderHistoryLoaded",
output: {
messages: [
createHistoryMessage("older-50"),
{ ...latestMessage, content: "stale duplicate" },
],
offset: event.offset,
total: 120,
limit: 50,
},
});
return;
}
sendBack({
type: "ChatOlderHistoryLoaded",
output: {
messages: [createHistoryMessage("oldest-100")],
offset: event.offset,
total: 120,
limit: 50,
},
});
});
return () => undefined;
},
),
},
});
const actor = createActor(machine).start();
actor.send({ type: "ChatUserLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ userSession: "ready" }),
);
actor.send({ type: "ChatLoadMoreHistoryRequested" });
await waitFor(
actor,
(snapshot) => snapshot.context.nextHistoryOffset === 100,
);
expect(requests[0]).toMatchObject({ offset: 50, limit: 50 });
expect(actor.getSnapshot().context.messages).toMatchObject([
{ id: "older-50" },
{ id: "latest", content: "current unlocked message" },
]);
actor.send({ type: "ChatLoadMoreHistoryRequested" });
await waitFor(
actor,
(snapshot) => snapshot.context.nextHistoryOffset === 150,
);
actor.send({ type: "ChatLoadMoreHistoryRequested" });
expect(requests).toHaveLength(2);
expect(actor.getSnapshot().context.nextHistoryOffset).toBeGreaterThanOrEqual(
actor.getSnapshot().context.historyTotal,
);
actor.stop();
});
it("keeps the offset after a failed page and allows retrying", async () => {
let requestCount = 0;
const machine = chatMachine.provide({
actors: {
loadHistory: createLoadHistoryCallback([], [], {
total: 75,
limit: 50,
}),
loadMoreHistory: fromCallback<LoadMoreHistoryActorEvent>(
({ receive, sendBack }) => {
receive((event) => {
requestCount += 1;
if (requestCount === 1) {
sendBack({
type: "ChatOlderHistoryLoadFailed",
error: new Error("network failed"),
});
return;
}
sendBack({
type: "ChatOlderHistoryLoaded",
output: {
messages: [createHistoryMessage("retry-message")],
offset: event.offset,
total: 75,
limit: 50,
},
});
});
return () => undefined;
},
),
},
});
const actor = createActor(machine).start();
actor.send({ type: "ChatGuestLogin" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ guestSession: "ready" }),
);
actor.send({ type: "ChatLoadMoreHistoryRequested" });
await waitFor(
actor,
(snapshot) =>
requestCount === 1 && !snapshot.context.isLoadingMoreHistory,
);
expect(actor.getSnapshot().context.nextHistoryOffset).toBe(50);
actor.send({ type: "ChatLoadMoreHistoryRequested" });
await waitFor(
actor,
(snapshot) => snapshot.context.nextHistoryOffset === 100,
);
expect(requestCount).toBe(2);
actor.stop();
});
it("does not request another page when total does not exceed limit", async () => {
let requested = false;
const machine = chatMachine.provide({
actors: {
loadHistory: createLoadHistoryCallback([], [], {
total: 50,
limit: 50,
}),
loadMoreHistory: fromCallback<LoadMoreHistoryActorEvent>(
({ receive }) => {
receive(() => {
requested = true;
});
return () => undefined;
},
),
},
});
const actor = createActor(machine).start();
actor.send({ type: "ChatUserLogin", token: "token" });
await waitFor(actor, (snapshot) =>
snapshot.matches({ userSession: "ready" }),
);
actor.send({ type: "ChatLoadMoreHistoryRequested" });
expect(requested).toBe(false);
expect(actor.getSnapshot().context.isLoadingMoreHistory).toBe(false);
actor.stop();
});
});
function createHistoryMessage(id: string): UiMessage {
return {
id,
content: `Message ${id}`,
isFromAI: true,
date: "2026-07-15",
};
}
@@ -131,6 +131,10 @@ export function createTestChatMachine(
export function createLoadHistoryCallback(
messages: UiMessage[],
networkMessages: UiMessage[] = messages,
pagination: { total: number; limit: number } = {
total: networkMessages.length,
limit: 50,
},
) {
return fromCallback<ChatEvent>(({ sendBack }) => {
sendBack({
@@ -147,6 +151,8 @@ export function createLoadHistoryCallback(
localOverwritten: true,
localCount: messages.length,
networkCount: networkMessages.length,
total: pagination.total,
limit: pagination.limit,
},
});
return () => undefined;
+6
View File
@@ -23,6 +23,8 @@ interface ChatState {
upgradeReason: MachineContext["upgradeReason"];
/** history 初始加载完成标志(local → network → save 跑完) —— UI 可用此显示 loading */
historyLoaded: boolean;
hasMoreHistory: boolean;
isLoadingMoreHistory: boolean;
unlockHistoryPromptVisible: boolean;
lockedHistoryCount: number;
isUnlockingHistory: boolean;
@@ -76,6 +78,10 @@ function selectChatState(state: ChatSnapshot): SelectedChatState {
upgradePromptVisible: state.context.upgradePromptVisible,
upgradeReason: state.context.upgradeReason,
historyLoaded: state.context.historyLoaded,
hasMoreHistory:
state.context.historyLoaded &&
state.context.nextHistoryOffset < state.context.historyTotal,
isLoadingMoreHistory: state.context.isLoadingMoreHistory,
unlockHistoryPromptVisible: state.context.unlockHistoryPromptVisible,
lockedHistoryCount: state.context.lockedHistoryCount,
isUnlockingHistory: state.context.isUnlockingHistory,
+6
View File
@@ -33,6 +33,12 @@ export type ChatEvent =
output: import("./chat-history-sync").NetworkHistorySyncOutput;
}
| { type: "ChatHistoryLoadFailed"; error: unknown }
| { type: "ChatLoadMoreHistoryRequested" }
| {
type: "ChatOlderHistoryLoaded";
output: import("./machine/actors/history").LoadMoreHistoryOutput;
}
| { type: "ChatOlderHistoryLoadFailed"; error: unknown }
// 业务事件
| { type: "ChatSendMessage"; content: string }
| { type: "ChatSendImage"; imageBase64: string }
+6
View File
@@ -17,6 +17,8 @@ export type ReadAndSyncHistoryOutput = {
localOverwritten: boolean;
localCount: number;
networkCount: number;
total: number;
limit: number;
};
export type LocalHistorySnapshotOutput = {
@@ -121,6 +123,8 @@ export async function syncNetworkHistory(
localOverwritten,
localCount,
networkCount: networkUi.length,
total: networkResult.data.total,
limit: networkResult.data.limit,
};
}
@@ -144,5 +148,7 @@ export async function readAndSyncHistory(): Promise<ReadAndSyncHistoryOutput> {
localOverwritten: false,
localCount: localSnapshot.localCount,
networkCount: 0,
total: 0,
limit: CHAT_HISTORY_LIMIT,
};
}
+8
View File
@@ -33,6 +33,10 @@ export interface ChatState {
shortfallCredits: number;
/** history 首屏可展示标志(本地快照加载完成即可进入 ready)。 */
historyLoaded: boolean;
historyTotal: number;
historyLimit: number;
nextHistoryOffset: number;
isLoadingMoreHistory: boolean;
paymentUnlockPending: boolean;
unlockHistoryPromptVisible: boolean;
lockedHistoryCount: number;
@@ -61,6 +65,10 @@ export const initialState: ChatState = {
requiredCredits: 0,
shortfallCredits: 0,
historyLoaded: false,
historyTotal: 0,
historyLimit: 50,
nextHistoryOffset: 0,
isLoadingMoreHistory: false,
paymentUnlockPending: false,
unlockHistoryPromptVisible: false,
lockedHistoryCount: 0,
+77 -1
View File
@@ -21,12 +21,88 @@ export function applyNetworkHistoryLoadedOutput(
output: {
messages: UiMessage[];
localCount: number;
total: number;
limit: number;
},
): Pick<ChatState, "messages" | "historyLoaded"> {
): Pick<
ChatState,
| "messages"
| "historyLoaded"
| "historyTotal"
| "historyLimit"
| "nextHistoryOffset"
| "isLoadingMoreHistory"
> {
const localSnapshotSize = output.localCount === 0 ? 1 : output.localCount;
const optimisticTail = context.messages.slice(localSnapshotSize);
const historyLimit = normalizeHistoryLimit(output.limit);
return {
messages: [...output.messages, ...optimisticTail],
historyLoaded: true,
historyTotal: Math.max(0, output.total),
historyLimit,
nextHistoryOffset: historyLimit,
isLoadingMoreHistory: false,
};
}
export function applyOlderHistoryLoadedOutput(
context: ChatState,
output: {
messages: UiMessage[];
offset: number;
total: number;
limit: number;
},
): Pick<
ChatState,
| "messages"
| "historyTotal"
| "historyLimit"
| "nextHistoryOffset"
| "isLoadingMoreHistory"
> {
const historyLimit = normalizeHistoryLimit(
output.limit,
context.historyLimit,
);
return {
messages: prependUniqueHistoryMessages(context.messages, output.messages),
historyTotal: Math.max(0, output.total),
historyLimit,
nextHistoryOffset: output.offset + historyLimit,
isLoadingMoreHistory: false,
};
}
export function canLoadMoreHistory(context: ChatState): boolean {
return (
context.historyLoaded &&
!context.isLoadingMoreHistory &&
context.nextHistoryOffset < context.historyTotal
);
}
export function normalizeHistoryLimit(
limit: number,
fallback = CHAT_HISTORY_LIMIT,
): number {
return Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : fallback;
}
export function prependUniqueHistoryMessages(
currentMessages: readonly UiMessage[],
olderMessages: readonly UiMessage[],
): UiMessage[] {
const existingIds = new Set(
currentMessages.flatMap((message) => (message.id ? [message.id] : [])),
);
const pageIds = new Set<string>();
const uniqueOlderMessages = olderMessages.filter((message) => {
if (!message.id) return true;
if (existingIds.has(message.id) || pageIds.has(message.id)) return false;
pageIds.add(message.id);
return true;
});
return [...uniqueOlderMessages, ...currentMessages];
}
+69
View File
@@ -1,6 +1,9 @@
import { fromCallback } from "xstate";
import type { UiMessage } from "@/data/dto/chat";
import { loadChatRepository } from "@/data/repositories/chat_repository_loader";
import { Logger } from "@/utils/logger";
import { Result } from "@/utils/result";
import {
readLocalHistorySnapshot,
@@ -8,9 +11,24 @@ import {
syncNetworkHistory,
} from "../../chat-history-sync";
import type { ChatEvent } from "../../chat-events";
import { normalizeHistoryLimit } from "../../helper/history";
import { localMessagesToUi } from "../../helper/message-mappers";
const log = new Logger("StoresChatChatHistoryFlow");
export interface LoadMoreHistoryActorEvent {
type: "LoadMoreHistoryPageRequested";
offset: number;
limit: number;
}
export interface LoadMoreHistoryOutput {
messages: UiMessage[];
offset: number;
total: number;
limit: number;
}
export const loadHistoryActor = fromCallback<ChatEvent>(({ sendBack }) => {
let cancelled = false;
@@ -42,3 +60,54 @@ export const loadHistoryActor = fromCallback<ChatEvent>(({ sendBack }) => {
cancelled = true;
};
});
export const loadMoreHistoryActor =
fromCallback<LoadMoreHistoryActorEvent>(({ receive, sendBack }) => {
let cancelled = false;
let running = false;
receive((event) => {
if (running || cancelled) return;
running = true;
void (async () => {
const chatRepo = await loadChatRepository();
const historyResult = await chatRepo.getHistory(
event.limit,
event.offset,
);
if (Result.isErr(historyResult)) throw historyResult.error;
if (cancelled) return;
const response = historyResult.data;
sendBack({
type: "ChatOlderHistoryLoaded",
output: {
messages: localMessagesToUi(response.messages),
offset: event.offset,
total: response.total,
limit: normalizeHistoryLimit(response.limit, event.limit),
} satisfies LoadMoreHistoryOutput,
});
void resolveHistoryCacheIdentity().then((cacheIdentity) => {
if (!cacheIdentity) return;
void chatRepo.prefetchMediaForMessages(
response.messages,
cacheIdentity,
);
});
})()
.catch((error: unknown) => {
if (cancelled) return;
log.warn("[chat-machine] loadMoreHistoryActor failed", { error });
sendBack({ type: "ChatOlderHistoryLoadFailed", error });
})
.finally(() => {
running = false;
});
});
return () => {
cancelled = true;
};
});
+45
View File
@@ -1,11 +1,14 @@
import {
applyOlderHistoryLoadedOutput,
applyHistoryLoadedOutput,
applyNetworkHistoryLoadedOutput,
canLoadMoreHistory,
} from "../helper/history";
import {
countLockedHistoryMessages,
shouldPromptUnlockHistory,
} from "../helper/unlock";
import type { ChatState } from "../chat-state";
import { baseChatMachineSetup } from "./setup";
const applyLocalHistoryLoadedAction = baseChatMachineSetup.assign(
@@ -49,6 +52,30 @@ const markHistoryLoadFailedAction = baseChatMachineSetup.assign({
historyLoaded: true,
});
const markLoadMoreHistoryStartedAction = baseChatMachineSetup.assign({
isLoadingMoreHistory: true,
});
const requestOlderHistoryPageAction = baseChatMachineSetup.sendTo(
"loadMoreHistory",
({ context }) => ({
type: "LoadMoreHistoryPageRequested",
offset: context.nextHistoryOffset,
limit: context.historyLimit,
}),
);
const applyOlderHistoryLoadedAction = baseChatMachineSetup.assign(
({ context, event }) => {
if (event.type !== "ChatOlderHistoryLoaded") return {};
return applyOlderHistoryLoadedOutput(context, event.output);
},
);
const markOlderHistoryLoadFailedAction = baseChatMachineSetup.assign({
isLoadingMoreHistory: false,
});
export const historyMachineSetup = baseChatMachineSetup.extend({
actions: {
applyLocalHistoryLoaded: applyLocalHistoryLoadedAction,
@@ -58,9 +85,27 @@ export const historyMachineSetup = baseChatMachineSetup.extend({
showUnlockHistoryPromptFromNetwork:
showUnlockHistoryPromptFromNetworkAction,
markHistoryLoadFailed: markHistoryLoadFailedAction,
markLoadMoreHistoryStarted: markLoadMoreHistoryStartedAction,
requestOlderHistoryPage: requestOlderHistoryPageAction,
applyOlderHistoryLoaded: applyOlderHistoryLoadedAction,
markOlderHistoryLoadFailed: markOlderHistoryLoadFailedAction,
},
});
export const historyPaginationTransitions = {
ChatLoadMoreHistoryRequested: {
guard: ({ context }: { context: ChatState }) =>
canLoadMoreHistory(context),
actions: ["markLoadMoreHistoryStarted", "requestOlderHistoryPage"],
},
ChatOlderHistoryLoaded: {
actions: "applyOlderHistoryLoaded",
},
ChatOlderHistoryLoadFailed: {
actions: "markOlderHistoryLoadFailed",
},
} as const;
export const guestInitializingState = historyMachineSetup.createStateConfig({
on: {
ChatLocalHistoryLoaded: {
+11
View File
@@ -3,6 +3,7 @@ import { shouldPromptUnlockHistory } from "../helper/unlock";
import { initialState } from "../chat-state";
import {
guestInitializingState,
historyPaginationTransitions,
userInitializingState,
} from "./history-flow";
import {
@@ -79,8 +80,13 @@ const guestSessionState = chatMachineSetup.createStateConfig({
id: "loadHistory",
src: "loadHistory",
},
{
id: "loadMoreHistory",
src: "loadMoreHistory",
},
],
on: {
...historyPaginationTransitions,
ChatUserLogin: {
target: "#chat.userSession",
actions: "startUserSession",
@@ -137,8 +143,13 @@ const userSessionState = chatMachineSetup.createStateConfig({
id: "loadHistory",
src: "loadHistory",
},
{
id: "loadMoreHistory",
src: "loadMoreHistory",
},
],
on: {
...historyPaginationTransitions,
ChatGuestLogin: {
target: "#chat.guestSession",
actions: "startGuestSession",
+5 -1
View File
@@ -1,7 +1,10 @@
import { setup, type ActionFunction, type EventObject } from "xstate";
import type { ChatEvent } from "../chat-events";
import { loadHistoryActor } from "./actors/history";
import {
loadHistoryActor,
loadMoreHistoryActor,
} from "./actors/history";
import {
httpMessageQueueActor,
sendMessageHttpActor,
@@ -19,6 +22,7 @@ export const baseChatMachineSetup = setup({
},
actors: {
loadHistory: loadHistoryActor,
loadMoreHistory: loadMoreHistoryActor,
sendMessageHttp: sendMessageHttpActor,
httpMessageQueue: httpMessageQueueActor,
unlockHistory: unlockHistoryActor,