Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(share): reopen a shared topic where the reader stopped (#21652)

YuTengjing3df36f353182
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 313f54cbb9d..432dac95e66 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -40,6 +40,7 @@ the next free number of that prefix.
- **L-E21** Evidence for "A is unaffected by B" must be able to tell A from B: distinct content and the target echoed in the request line.
- **L-E21** Publish against production even when the subject exists only locally; a local ingest may supplement, never replace.
- **L-E22** `requiredEvidence: text` is satisfied only by `.txt`/`.json`-style files; an `.md` file ingests as `markdown` and leaves the check `uncertain`.
+- **L-E23** Published evidence never shows a real person's private content (photos, faces, personal messages); rebuild the case on placeholder fixtures instead of the user's real page.
**Product and interaction contracts**
@@ -621,6 +622,20 @@ dev.mjs 每次启动都会拉起 renderer Vite dev server,而后者启动即
`.txt`。发布后用 `lh acceptance run result list --run <id> --json` 核对每项 verdict。已发布的轮次
用 `lh acceptance run result submit --type text --file <x>.txt --verdict ...` 补交,不要新开一轮。
+### L-E23 — Capturing a real user's private content as evidence
+
+`since 2026-10-26` · `holds-while: always`
+
+**Trap:** the report reproduces a bug on the real page the user linked (a
+`/share/t/<id>` topic of their own). The screenshots show the conversation as is,
+including a family member's photo, and ingest publishes them.
+
+**Rule:** before capture, build the case on placeholder data: `lh topic import`
+of placeholder messages, `lh topic share` it, and unshare and delete it in
+teardown. When only the real page reproduces the case, redact faces, photos and
+personal text before ingest. Open every image before ingest; if a published
+round still leaks content, `lh acceptance run delete <runId> --yes` and republish.
+
### L-S26 — 在坏掉的根 `.env` 上原地硬修
`since 2026-10-23` · `holds-while: init-dev-env.sh 在根 .env 存在时直接退出,dev-server.md 只写了「有 .env 用现有配置」这一条分支`
diff --git a/apps/share/src/features/topic/SharedMessageList.tsx b/apps/share/src/features/topic/SharedMessageList.tsx
index 14b3bbc7f4c..d9650f31ffc 100644
--- a/apps/share/src/features/topic/SharedMessageList.tsx
+++ b/apps/share/src/features/topic/SharedMessageList.tsx
@@ -38,6 +38,7 @@ const SharedMessageList = memo<SharedMessageListProps>((props) => {
<ConversationProvider context={context}>
<ChatList
disableActionsBar
+ rememberReadingPosition
headerSlot={headerSlot}
initialScrollPosition={'top'}
itemContent={itemContent}
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index ef78ce15bd4..b2ef309c2bf 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -34,6 +34,7 @@ import {
} from '../hooks/useConversationScroll';
import { useEarlierHistoryTrigger } from '../hooks/useEarlierHistoryTrigger';
import { useLaterHistoryTrigger } from '../hooks/useLaterHistoryTrigger';
+import { useReadingAnchor } from '../hooks/useReadingAnchor';
import { useSelectionMessageIds } from '../hooks/useSelectionMessageIds';
import { type InitialScrollPosition, useTopicScrollPersist } from '../hooks/useTopicScrollPersist';
import { resolveAutoScrollDetached } from '../utils/autoScrollFollow';
@@ -72,6 +73,8 @@ interface VirtualizedListProps {
paging?: 'backward' | 'forward';
/** Print the loaded transcript, without the app chrome, when the page prints. */
printable?: boolean;
+ /** Reopen at the message the reader last had at the top of the viewport. */
+ rememberReadingPosition?: boolean;
}
/**
@@ -89,6 +92,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
messageDeepLink,
paging,
printable,
+ rememberReadingPosition,
}) => {
const isForward = paging === 'forward';
const virtuaRef = useRef<VListHandle>(null);
@@ -169,6 +173,16 @@ const VirtualizedList = memo<VirtualizedListProps>(
});
const historyTrigger = isForward ? laterHistory : earlierHistory;
+ const { onScroll: recordReadingAnchor } = useReadingAnchor({
+ contextKey,
+ dataSource,
+ enabled: !!rememberReadingPosition && !messageDeepLink,
+ getScroller,
+ headerOffset: LEADING_ROWS,
+ loadPage: isForward ? loadLaterMessages : loadEarlierMessages,
+ virtuaRef,
+ });
+
const markUserScrollIntent = useCallback(() => {
lastUserScrollIntentAtRef.current = Date.now();
}, []);
@@ -281,6 +295,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
// Programmatic mount/restore scrolls carry no intent and never fetch.
if (hasUserScrollIntent) historyTrigger.onUserScroll();
+ recordReadingAnchor(hasUserScrollIntent);
const autoScrollDetached = resolveAutoScrollDetached({
detached: storeApi.getState().autoScrollDetached,
@@ -305,6 +320,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
historyTrigger,
markUserScrolling,
onScrollOffset,
+ recordReadingAnchor,
recordScroll,
setActiveIndex,
setScrollState,
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
index cfc3b4bd653..8dfbc7788ac 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
@@ -118,6 +118,7 @@ describe('useConversationScroll — pin behavior', () => {
*/
type StoreFixture = {
displayMessages: Array<{ id: string; role: 'user' | 'assistant' }>;
+ hasLaterMessages?: boolean;
isAIGenerating: boolean;
virtuaScrollMethods: {
getItemOffset?: (i: number) => number;
@@ -146,6 +147,7 @@ describe('useConversationScroll — pin behavior', () => {
vi.mocked(useConversationStore).mockImplementation((selector: any) => {
const probe: any = {
displayMessages: currentFixture.displayMessages,
+ hasLaterMessages: currentFixture.hasLaterMessages ?? false,
operationState: { isAIGenerating: currentFixture.isAIGenerating },
virtuaScrollMethods: currentFixture.virtuaScrollMethods,
};
@@ -192,13 +194,16 @@ describe('useConversationScroll — pin behavior', () => {
const rerender = (next: {
contextKey?: string;
dataSource: string[];
+ hasLaterMessages?: boolean;
isSecondLastMessageFromUser: boolean;
}) => {
+ const { hasLaterMessages, ...props } = next;
currentFixture = {
...currentFixture,
displayMessages: deriveDisplayMessages(next.isSecondLastMessageFromUser),
+ hasLaterMessages: hasLaterMessages ?? currentFixture.hasLaterMessages,
};
- hook.rerender({ contextKey: undefined, ...next });
+ hook.rerender({ contextKey: undefined, ...props });
};
return { ...hook, rerender };
@@ -250,6 +255,23 @@ describe('useConversationScroll — pin behavior', () => {
expect(scrollToIndex).toHaveBeenCalledWith(3, { align: 'start', smooth: true });
});
+ it('does not scroll when a forward read appends its next page as a user+assistant pair', () => {
+ const { rerender } = renderScrollHook({
+ dataSource: [assistantId, 'prev'],
+ fixture: { hasLaterMessages: true },
+ isSecondLastMessageFromUser: false,
+ });
+
+ // The last page lands: later rounds are no longer unread after it.
+ rerender({
+ dataSource: ['m0', 'm1', userId, assistantId],
+ hasLaterMessages: false,
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
it('does not scroll when only the assistant message is appended', () => {
const { rerender } = renderScrollHook({
dataSource: [userId, assistantId],
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
index fac186bce74..d5d5e79cc18 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
@@ -468,6 +468,7 @@ export const useConversationScroll = ({
virtuaRef,
}: UseConversationScrollOptions): UseConversationScrollResult => {
const displayMessages = useConversationStore(dataSelectors.displayMessages);
+ const hasLaterMessages = useConversationStore(dataSelectors.hasLaterMessages);
const isAIGenerating = useConversationStore(messageStateSelectors.isAIGenerating);
const getItemOffset = useConversationStore((s) => s.virtuaScrollMethods?.getItemOffset);
const getItemSize = useConversationStore((s) => s.virtuaScrollMethods?.getItemSize);
@@ -484,6 +485,10 @@ export const useConversationScroll = ({
const [userMessageIndex, setUserMessageIndex] = useState<number | null>(null);
const [assistantMessageIndex, setAssistantMessageIndex] = useState<number | null>(null);
const prevLengthRef = useRef(dataSource.length);
+ // Whether later rounds were still unread as of the previous dataSource. A
+ // send can only append at the end of the conversation, so a pair appended
+ // while later rounds were unread is a forward read's next page.
+ const hadLaterMessagesRef = useRef(hasLaterMessages);
const { registerSpacerNode, spacerLayoutVersion } = useSpacerLayoutSignal();
@@ -536,6 +541,7 @@ export const useConversationScroll = ({
prevContextKeyRef.current = contextKey;
prevLengthRef.current = dataSource.length;
+ hadLaterMessagesRef.current = hasLaterMessages;
clearPin('context switch');
setUserMessageIndex(null);
setAssistantMessageIndex(null);
@@ -548,8 +554,10 @@ export const useConversationScroll = ({
useEffect(() => {
const newMessageCount = dataSource.length - prevLengthRef.current;
prevLengthRef.current = dataSource.length;
+ const appendedLaterPage = hadLaterMessagesRef.current;
+ hadLaterMessagesRef.current = hasLaterMessages;
- if (newMessageCount !== 2 || !isSecondLastMessageFromUser) return;
+ if (newMessageCount !== 2 || !isSecondLastMessageFromUser || appendedLaterPage) return;
const userMessage = displayMessages.at(-2);
const assistantMessage = displayMessages.at(-1);
@@ -577,6 +585,7 @@ export const useConversationScroll = ({
dataSource,
displayMessages,
getScrollOffset,
+ hasLaterMessages,
isSecondLastMessageFromUser,
mountedRef,
pinRef,
diff --git a/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.test.ts b/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.test.ts
index 31e45bb3751..3dd193e056b 100644
--- a/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.test.ts
@@ -15,7 +15,8 @@ const setup = (initial: {
const loadEarlierMessages = vi.fn().mockResolvedValue(undefined);
const props = { loadedCount: 10, ready: true, resolved: false, ...initial };
const hook = renderHook(
- (current: typeof props) => useDeepLinkHistoryBackfill({ ...current, loadEarlierMessages }),
+ (current: typeof props) =>
+ useDeepLinkHistoryBackfill({ ...current, loadPage: loadEarlierMessages }),
{ initialProps: props },
);
diff --git a/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.ts b/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.ts
index e1c0fd924ef..1e11419d1c5 100644
--- a/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.ts
+++ b/src/features/Conversation/ChatList/hooks/useDeepLinkHistoryBackfill.ts
@@ -1,29 +1,31 @@
import { useEffect, useRef } from 'react';
-/** Upper bound of older pages one deep link may pull in before giving up. */
+/** Upper bound of pages one deep link may pull in before giving up. */
export const MAX_DEEP_LINK_BACKFILL_PAGES = 50;
interface UseDeepLinkHistoryBackfillOptions {
/** Changes with every navigation to a deep link, even to the same message. */
deepLinkKey?: string;
- loadEarlierMessages: () => Promise<void>;
- /** Rows loaded so far; a page that adds none means the topic start was reached. */
+ /** Rows loaded so far; a page that adds none means the end of the topic was reached. */
loadedCount: number;
- /** The first page has settled and the list pages backward. */
+ /** Loads the next page toward the target: earlier history, or later rounds when reading forward. */
+ loadPage: () => Promise<void>;
+ /** The first page has settled. */
ready: boolean;
/** The target is among the loaded rows. */
resolved: boolean;
}
/**
- * A deep link (a search hit, a `#<messageId>` URL) can point at a message older
- * than the loaded window. Page older history in, one page per settled load,
- * until the target is loaded, a page adds nothing, or the page budget is spent.
+ * A deep link (a search hit, a `#<messageId>` URL, a saved reading position)
+ * can point at a message outside the loaded window. Page history in, one page
+ * per settled load, until the target is loaded, a page adds nothing, or the
+ * page budget is spent.
*/
export const useDeepLinkHistoryBackfill = ({
deepLinkKey,
loadedCount,
- loadEarlierMessages,
+ loadPage,
ready,
resolved,
}: UseDeepLinkHistoryBackfillOptions) => {
@@ -40,6 +42,6 @@ export const useDeepLinkHistoryBackfill = ({
progress.lastCount = loadedCount;
progress.pages += 1;
- void loadEarlierMessages();
- }, [deepLinkKey, loadedCount, loadEarlierMessages, ready, resolved]);
+ void loadPage();
+ }, [deepLinkKey, loadedCount, loadPage, ready, resolved]);
};
diff --git a/src/features/Conversation/ChatList/hooks/useReadingAnchor.test.ts b/src/features/Conversation/ChatList/hooks/useReadingAnchor.test.ts
new file mode 100644
index 00000000000..ad23fc9530e
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useReadingAnchor.test.ts
@@ -0,0 +1,247 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { type RefObject } from 'react';
+import { type VListHandle } from 'virtua';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { loadReadingAnchor, saveReadingAnchor } from '../utils/readingAnchorStore';
+import { useReadingAnchor } from './useReadingAnchor';
+
+const KEY = 'main_agt_1_tpc_share';
+const ROW_HEIGHT = 100;
+const HEADER_OFFSET = 1;
+
+const createHandle = () => {
+ const handle = {
+ findItemIndex: vi.fn((offset: number) => Math.floor(offset / ROW_HEIGHT)),
+ getItemOffset: vi.fn((index: number) => index * ROW_HEIGHT),
+ scrollOffset: 0,
+ scrollToIndex: vi.fn(),
+ };
+ return {
+ handle,
+ ref: { current: handle as unknown as VListHandle } as RefObject<VListHandle | null>,
+ };
+};
+
+const createScroller = () => {
+ const target = new EventTarget();
+ return target as unknown as HTMLElement;
+};
+
+const ids = (count: number) => Array.from({ length: count }, (_, i) => `msg_${i}`);
+
+const renderAnchor = (initial: { dataSource: string[]; enabled?: boolean }) => {
+ const { handle, ref } = createHandle();
+ const scroller = createScroller();
+ const loadPage = vi.fn().mockResolvedValue(undefined);
+ const hook = renderHook(
+ ({ dataSource, enabled }: { dataSource: string[]; enabled: boolean }) =>
+ useReadingAnchor({
+ contextKey: KEY,
+ dataSource,
+ enabled,
+ getScroller: () => scroller,
+ headerOffset: HEADER_OFFSET,
+ loadPage,
+ virtuaRef: ref,
+ }),
+ { initialProps: { dataSource: initial.dataSource, enabled: initial.enabled ?? true } },
+ );
+ return { ...hook, handle, loadPage, scroller };
+};
+
+describe('useReadingAnchor', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('records the message at the top of the viewport and its offset within it', () => {
+ const { handle, result, unmount } = renderAnchor({ dataSource: ids(10) });
+
+ // Row 4 is msg_3; the viewport top sits 30px into it.
+ handle.scrollOffset = 430;
+ act(() => result.current.onScroll(true));
+ unmount();
+
+ expect(loadReadingAnchor(KEY)).toMatchObject({ messageId: 'msg_3', offset: 30 });
+ });
+
+ it('clears the anchor once the reader is back at the header', () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_3', offset: 0, savedAt: Date.now() });
+ const { handle, result, unmount } = renderAnchor({ dataSource: ids(10) });
+
+ handle.scrollOffset = 20;
+ act(() => result.current.onScroll(true));
+ unmount();
+
+ expect(loadReadingAnchor(KEY)).toBeNull();
+ });
+
+ it('restores a saved anchor that is already loaded', async () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_3', offset: 30, savedAt: Date.now() });
+ const { handle, loadPage } = renderAnchor({ dataSource: ids(10) });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ expect(loadPage).not.toHaveBeenCalled();
+ expect(handle.scrollToIndex).toHaveBeenCalledWith(3 + HEADER_OFFSET, {
+ align: 'start',
+ offset: 30,
+ });
+ });
+
+ it('pages in later rows until the anchor is loaded, then scrolls to it', async () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_25', offset: 0, savedAt: Date.now() });
+ const { handle, loadPage, rerender } = renderAnchor({ dataSource: ids(10) });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(loadPage).toHaveBeenCalledTimes(1);
+ expect(handle.scrollToIndex).not.toHaveBeenCalled();
+
+ rerender({ dataSource: ids(20), enabled: true });
+ expect(loadPage).toHaveBeenCalledTimes(2);
+
+ rerender({ dataSource: ids(30), enabled: true });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ expect(loadPage).toHaveBeenCalledTimes(2);
+ expect(handle.scrollToIndex).toHaveBeenCalledWith(25 + HEADER_OFFSET, {
+ align: 'start',
+ offset: 0,
+ });
+ });
+
+ it('stops paging once a page adds nothing', async () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_deleted', offset: 0, savedAt: Date.now() });
+ const { loadPage, rerender } = renderAnchor({ dataSource: ids(10) });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ rerender({ dataSource: ids(10), enabled: true });
+
+ expect(loadPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('abandons the restore when the reader scrolls first', async () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_25', offset: 0, savedAt: Date.now() });
+ const { handle, rerender, result } = renderAnchor({ dataSource: ids(10) });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ handle.scrollOffset = 250;
+ act(() => result.current.onScroll(true));
+ rerender({ dataSource: ids(30), enabled: true });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ expect(handle.scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('abandons the restore on input that does not scroll while pages load', async () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_25', offset: 0, savedAt: Date.now() });
+ const { handle, rerender, scroller } = renderAnchor({ dataSource: ids(10) });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ // Home at the top or an upward wheel leaves the offset unchanged, so no
+ // scroll event reports it.
+ act(() => {
+ scroller.dispatchEvent(new Event('keydown'));
+ });
+ rerender({ dataSource: ids(30), enabled: true });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ expect(handle.scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('clears the anchor when that input cancels the restore on the header', async () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_25', offset: 0, savedAt: Date.now() });
+ const { handle, scroller, unmount } = renderAnchor({ dataSource: ids(10) });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ handle.scrollOffset = 20;
+ act(() => {
+ scroller.dispatchEvent(new Event('keydown'));
+ });
+ unmount();
+
+ expect(loadReadingAnchor(KEY)).toBeNull();
+ });
+
+ it('stops re-aiming once the reader takes over', async () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_3', offset: 0, savedAt: Date.now() });
+ const { handle, scroller } = renderAnchor({ dataSource: ids(10) });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ const callsBeforeInput = handle.scrollToIndex.mock.calls.length;
+ scroller.dispatchEvent(new Event('wheel'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500);
+ });
+
+ expect(handle.scrollToIndex.mock.calls.length).toBeLessThanOrEqual(callsBeforeInput + 1);
+ });
+
+ it('neither restores nor records when disabled', async () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_3', offset: 0, savedAt: Date.now() });
+ const { handle, result, unmount } = renderAnchor({ dataSource: ids(10), enabled: false });
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ handle.scrollOffset = 830;
+ act(() => result.current.onScroll(true));
+ unmount();
+
+ expect(handle.scrollToIndex).not.toHaveBeenCalled();
+ expect(loadReadingAnchor(KEY)?.messageId).toBe('msg_3');
+ });
+
+ it('records where a smooth or momentum scroll lands after the input ends', () => {
+ const { handle, result, unmount } = renderAnchor({ dataSource: ids(10) });
+
+ handle.scrollOffset = 250;
+ act(() => result.current.onScroll(true));
+ // The tail of the scroll arrives without fresh input.
+ handle.scrollOffset = 980;
+ act(() => result.current.onScroll(false));
+ unmount();
+
+ expect(loadReadingAnchor(KEY)).toMatchObject({ messageId: 'msg_8', offset: 80 });
+ });
+
+ it('keeps the saved anchor when a scroll without input fires before the restore', () => {
+ saveReadingAnchor(KEY, { messageId: 'msg_25', offset: 0, savedAt: Date.now() });
+ const { handle, result, unmount } = renderAnchor({ dataSource: ids(10) });
+
+ handle.scrollOffset = 0;
+ act(() => result.current.onScroll(false));
+ unmount();
+
+ expect(loadReadingAnchor(KEY)?.messageId).toBe('msg_25');
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useReadingAnchor.ts b/src/features/Conversation/ChatList/hooks/useReadingAnchor.ts
new file mode 100644
index 00000000000..9033e2d5c81
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useReadingAnchor.ts
@@ -0,0 +1,224 @@
+import type { RefObject } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import type { VListHandle } from 'virtua';
+
+import {
+ clearReadingAnchor,
+ loadReadingAnchor,
+ pruneReadingAnchors,
+ type ReadingAnchor,
+ saveReadingAnchor,
+} from '../utils/readingAnchorStore';
+import { useDeepLinkHistoryBackfill } from './useDeepLinkHistoryBackfill';
+
+const FLUSH_THROTTLE_MS = 200;
+/**
+ * Frames to keep re-aiming at the anchor while rows above it and the anchor
+ * row itself are measured; each re-aim uses virtua's latest measurements.
+ */
+const RESTORE_FRAMES = 30;
+const USER_SCROLL_INPUT_EVENTS = ['keydown', 'pointerdown', 'touchstart', 'wheel'] as const;
+
+interface UseReadingAnchorOptions {
+ contextKey: string;
+ /** Message row ids, in message-index space. */
+ dataSource: string[];
+ enabled: boolean;
+ getScroller: () => HTMLElement | null;
+ /** Synthetic rows before the first message in the virtua list. */
+ headerOffset: number;
+ /** Loads the next page toward rows not loaded yet. */
+ loadPage: () => Promise<void>;
+ virtuaRef: RefObject<VListHandle | null>;
+}
+
+interface PendingResume {
+ anchor: ReadingAnchor;
+ key: string;
+}
+
+const readPendingResume = (key: string, enabled: boolean): PendingResume | null => {
+ if (!enabled) return null;
+ const anchor = loadReadingAnchor(key);
+ return anchor ? { anchor, key } : null;
+};
+
+/**
+ * Remembers which message the reader had at the top of the viewport and, on
+ * the next visit to the same conversation, pages it in and scrolls back to it.
+ * Any scroll input before the anchor is reached cancels the pending restore.
+ */
+export const useReadingAnchor = ({
+ contextKey,
+ dataSource,
+ enabled,
+ getScroller,
+ headerOffset,
+ loadPage,
+ virtuaRef,
+}: UseReadingAnchorOptions) => {
+ // Read during the first render: a scroll event fired at mount must already
+ // see the pending restore, or it would record the top and clear the anchor.
+ const [pending, setPending] = useState(() => readPendingResume(contextKey, enabled));
+ const loadedForRef = useRef(`${enabled}:${contextKey}`);
+ const pendingRef = useRef(pending);
+ pendingRef.current = pending;
+ const dataSourceRef = useRef(dataSource);
+ dataSourceRef.current = dataSource;
+ const contextKeyRef = useRef(contextKey);
+ contextKeyRef.current = contextKey;
+
+ /** `null` clears the anchor: the reader is back at the start. */
+ const pendingWriteRef = useRef<{ anchor: ReadingAnchor | null; key: string } | undefined>(
+ undefined,
+ );
+ const flushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ /** The restore's own scrolls pass through positions that are not the reader's. */
+ const restoringRef = useRef(false);
+
+ useEffect(() => {
+ const loadedFor = `${enabled}:${contextKey}`;
+ if (loadedForRef.current === loadedFor) return;
+ loadedForRef.current = loadedFor;
+ setPending(readPendingResume(contextKey, enabled));
+ }, [contextKey, enabled]);
+
+ useEffect(() => {
+ pruneReadingAnchors();
+ }, []);
+
+ const targetIndex = pending ? dataSource.indexOf(pending.anchor.messageId) : -1;
+
+ useDeepLinkHistoryBackfill({
+ deepLinkKey: pending ? `reading-anchor:${pending.key}` : undefined,
+ loadedCount: dataSource.length,
+ loadPage,
+ ready: dataSource.length > 0,
+ resolved: targetIndex >= 0,
+ });
+
+ useEffect(() => {
+ const ref = virtuaRef.current;
+ if (!pending || targetIndex < 0 || !ref) return;
+ setPending(null);
+
+ const target = headerOffset + targetIndex;
+ const { offset } = pending.anchor;
+ const scroller = getScroller();
+ restoringRef.current = true;
+ let stopped = false;
+ let frame = 0;
+ const stop = () => {
+ stopped = true;
+ };
+ for (const type of USER_SCROLL_INPUT_EVENTS) {
+ scroller?.addEventListener(type, stop, { passive: true });
+ }
+ const cleanup = () => {
+ restoringRef.current = false;
+ for (const type of USER_SCROLL_INPUT_EVENTS) {
+ scroller?.removeEventListener(type, stop);
+ }
+ };
+
+ const step = () => {
+ const current = virtuaRef.current;
+ if (stopped || !current || frame >= RESTORE_FRAMES) {
+ cleanup();
+ return;
+ }
+ current.scrollToIndex(target, { align: 'start', offset });
+ frame += 1;
+ requestAnimationFrame(step);
+ };
+ step();
+ }, [getScroller, headerOffset, pending, targetIndex, virtuaRef]);
+
+ const flush = useCallback(() => {
+ if (flushTimerRef.current) {
+ clearTimeout(flushTimerRef.current);
+ flushTimerRef.current = null;
+ }
+ const write = pendingWriteRef.current;
+ if (!write) return;
+ pendingWriteRef.current = undefined;
+ if (write.anchor) saveReadingAnchor(write.key, write.anchor);
+ else clearReadingAnchor(write.key);
+ }, []);
+
+ /** Queues the viewport's top message, or a clear when it is on the header. */
+ const recordPosition = useCallback(() => {
+ const ref = virtuaRef.current;
+ if (!ref) return;
+
+ const row = ref.findItemIndex(ref.scrollOffset);
+ const messageIndex = row - headerOffset;
+ const messages = dataSourceRef.current;
+ let anchor: ReadingAnchor | null;
+ if (messageIndex < 0) {
+ anchor = null;
+ } else if (messageIndex < messages.length) {
+ anchor = {
+ messageId: messages[messageIndex],
+ offset: Math.max(0, ref.scrollOffset - ref.getItemOffset(row)),
+ savedAt: Date.now(),
+ };
+ } else {
+ // Footer and spacer rows carry no message to come back to.
+ return;
+ }
+
+ pendingWriteRef.current = { anchor, key: contextKeyRef.current };
+ if (flushTimerRef.current) return;
+ flushTimerRef.current = setTimeout(flush, FLUSH_THROTTLE_MS);
+ }, [flush, headerOffset, virtuaRef]);
+
+ /**
+ * Call on every scroll event. Records the landing position of smooth-scroll
+ * and momentum tails too, which arrive after the reader's input has ended.
+ * Scrolls without input do not record while a restore is pending or running.
+ */
+ const onScroll = useCallback(
+ (fromUserInput: boolean) => {
+ if (!enabled) return;
+ if (fromUserInput) {
+ if (pendingRef.current) setPending(null);
+ } else if (pendingRef.current || restoringRef.current) {
+ return;
+ }
+ recordPosition();
+ },
+ [enabled, recordPosition],
+ );
+
+ // While pages load, input that cannot scroll (Home at the top, an upward
+ // wheel) fires no scroll event, so listen for the input itself and record
+ // where the reader is: on the header that clears the stale anchor.
+ const isPending = !!pending;
+ useEffect(() => {
+ const scroller = getScroller();
+ if (!isPending || !scroller) return;
+ const cancel = () => {
+ setPending(null);
+ recordPosition();
+ };
+ for (const type of USER_SCROLL_INPUT_EVENTS) {
+ scroller.addEventListener(type, cancel, { passive: true });
+ }
+ return () => {
+ for (const type of USER_SCROLL_INPUT_EVENTS) {
+ scroller.removeEventListener(type, cancel);
+ }
+ };
+ }, [getScroller, isPending, recordPosition]);
+
+ useEffect(() => {
+ window.addEventListener('pagehide', flush);
+ return () => {
+ window.removeEventListener('pagehide', flush);
+ flush();
+ };
+ }, [flush]);
+
+ return { onScroll };
+};
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index bb9f2f6afde..75f58c53130 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -120,6 +120,12 @@ export interface ChatListProps {
* copilot, floating chat) must not replace what its host page prints.
*/
printable?: boolean;
+ /**
+ * Reopen the conversation where the reader stopped last time (e.g. a shared
+ * topic), paging in history until that message is loaded. Ignored while a
+ * message deep link is present.
+ */
+ rememberReadingPosition?: boolean;
/**
* Force showing welcome component even when messages exist
*/
@@ -148,6 +154,7 @@ const ChatList = memo<ChatListProps>(
messageDeepLink,
onForwardPagingUnsupported,
printable,
+ rememberReadingPosition,
showWelcome,
}) => {
// The chat store owns the transcript; this view keeps its sync mounted.
@@ -309,7 +316,7 @@ const ChatList = memo<ChatListProps>(
useDeepLinkHistoryBackfill({
deepLinkKey: messageDeepLink?.navigationKey,
loadedCount: dbMessages.length,
- loadEarlierMessages,
+ loadPage: loadEarlierMessages,
ready: messagesInit && paging === 'backward',
resolved: !!resolvedMessageDeepLink || deepLinkTargetLoaded,
});
@@ -391,6 +398,7 @@ const ChatList = memo<ChatListProps>(
messageDeepLink={resolvedMessageDeepLink}
paging={paging}
printable={printable}
+ rememberReadingPosition={rememberReadingPosition}
/>
</BackgroundRunHintContext>
</MessageActionProvider>
diff --git a/src/features/Conversation/ChatList/utils/readingAnchorStore.test.ts b/src/features/Conversation/ChatList/utils/readingAnchorStore.test.ts
new file mode 100644
index 00000000000..3944634854d
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/readingAnchorStore.test.ts
@@ -0,0 +1,73 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ clearReadingAnchor,
+ loadReadingAnchor,
+ pruneReadingAnchors,
+ READING_ANCHOR_KEY_PREFIX,
+ READING_ANCHOR_MAX_AGE_MS,
+ READING_ANCHOR_MAX_ENTRIES,
+ saveReadingAnchor,
+} from './readingAnchorStore';
+
+describe('readingAnchorStore', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-26T00:00:00Z'));
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('round-trips an anchor per conversation', () => {
+ const anchor = { messageId: 'msg_2', offset: 120, savedAt: Date.now() };
+ saveReadingAnchor('main_agt_1_tpc_1', anchor);
+
+ expect(loadReadingAnchor('main_agt_1_tpc_1')).toEqual(anchor);
+ expect(loadReadingAnchor('main_agt_1_tpc_2')).toBeNull();
+ });
+
+ it('keeps an anchor across days but drops it after the max age', () => {
+ saveReadingAnchor('k', { messageId: 'msg_1', offset: 0, savedAt: Date.now() });
+
+ vi.advanceTimersByTime(7 * 24 * 60 * 60 * 1000);
+ expect(loadReadingAnchor('k')?.messageId).toBe('msg_1');
+
+ vi.advanceTimersByTime(READING_ANCHOR_MAX_AGE_MS);
+ expect(loadReadingAnchor('k')).toBeNull();
+ expect(localStorage.getItem(`${READING_ANCHOR_KEY_PREFIX}:k`)).toBeNull();
+ });
+
+ it('drops a corrupt entry on read', () => {
+ localStorage.setItem(`${READING_ANCHOR_KEY_PREFIX}:k`, '{"messageId":1}');
+
+ expect(loadReadingAnchor('k')).toBeNull();
+ expect(localStorage.getItem(`${READING_ANCHOR_KEY_PREFIX}:k`)).toBeNull();
+ });
+
+ it('clears an anchor', () => {
+ saveReadingAnchor('k', { messageId: 'msg_1', offset: 0, savedAt: Date.now() });
+ clearReadingAnchor('k');
+
+ expect(loadReadingAnchor('k')).toBeNull();
+ });
+
+ it('prunes the oldest anchors above the cap', () => {
+ const now = Date.now();
+ for (let i = 0; i < READING_ANCHOR_MAX_ENTRIES + 2; i++) {
+ saveReadingAnchor(`k${i}`, { messageId: 'msg', offset: 0, savedAt: now - 1000 + i });
+ }
+
+ pruneReadingAnchors();
+
+ expect(loadReadingAnchor('k0')).toBeNull();
+ expect(loadReadingAnchor('k1')).toBeNull();
+ expect(loadReadingAnchor('k2')).not.toBeNull();
+ expect(loadReadingAnchor(`k${READING_ANCHOR_MAX_ENTRIES + 1}`)).not.toBeNull();
+ });
+});
diff --git a/src/features/Conversation/ChatList/utils/readingAnchorStore.ts b/src/features/Conversation/ChatList/utils/readingAnchorStore.ts
new file mode 100644
index 00000000000..910b0889e5a
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/readingAnchorStore.ts
@@ -0,0 +1,122 @@
+export const READING_ANCHOR_KEY_PREFIX = 'LOBEHUB_READING_ANCHOR';
+export const READING_ANCHOR_MAX_ENTRIES = 200;
+/**
+ * A reading anchor lets a reader come back to a long transcript (a shared
+ * topic) days later and continue where they stopped, so it outlives the
+ * 5-minute topic-switch scroll snapshot by design.
+ */
+export const READING_ANCHOR_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
+
+/**
+ * Where the reader stopped, as a message rather than a pixel offset: a paged
+ * transcript reopens with only its first rows loaded, so an offset from the top
+ * would land on whatever the first page happens to measure.
+ */
+export interface ReadingAnchor {
+ /** Row id of the message at the top of the viewport. */
+ messageId: string;
+ /** Pixels the viewport top sits below that row's top edge. */
+ offset: number;
+ savedAt: number;
+}
+
+const buildStorageKey = (key: string) => `${READING_ANCHOR_KEY_PREFIX}:${key}`;
+
+const getStorage = (): Storage | null => {
+ try {
+ if (typeof window === 'undefined') return null;
+ return window.localStorage;
+ } catch {
+ return null;
+ }
+};
+
+const isValidAnchor = (value: unknown): value is ReadingAnchor => {
+ if (!value || typeof value !== 'object') return false;
+ const v = value as Record<string, unknown>;
+ return (
+ typeof v.messageId === 'string' &&
+ v.messageId.length > 0 &&
+ typeof v.offset === 'number' &&
+ Number.isFinite(v.offset) &&
+ typeof v.savedAt === 'number' &&
+ Number.isFinite(v.savedAt)
+ );
+};
+
+const readAnchor = (storage: Storage, storageKey: string): ReadingAnchor | null => {
+ try {
+ const raw = storage.getItem(storageKey);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw) as unknown;
+ if (isValidAnchor(parsed) && Date.now() - parsed.savedAt <= READING_ANCHOR_MAX_AGE_MS)
+ return parsed;
+ } catch {
+ // fall through to removal
+ }
+ try {
+ storage.removeItem(storageKey);
+ } catch {
+ // ignore
+ }
+ return null;
+};
+
+/** Drops expired or corrupt anchors, then the oldest ones above the cap. */
+export const pruneReadingAnchors = (storage: Storage | null = getStorage()) => {
+ if (!storage) return;
+
+ const keys: string[] = [];
+ for (let i = 0; i < storage.length; i++) {
+ const key = storage.key(i);
+ if (key?.startsWith(`${READING_ANCHOR_KEY_PREFIX}:`)) keys.push(key);
+ }
+
+ const valid: { key: string; savedAt: number }[] = [];
+ for (const key of keys) {
+ const anchor = readAnchor(storage, key);
+ if (anchor) valid.push({ key, savedAt: anchor.savedAt });
+ }
+
+ if (valid.length <= READING_ANCHOR_MAX_ENTRIES) return;
+ valid.sort((a, b) => a.savedAt - b.savedAt);
+ for (const { key } of valid.slice(0, valid.length - READING_ANCHOR_MAX_ENTRIES)) {
+ try {
+ storage.removeItem(key);
+ } catch {
+ // ignore
+ }
+ }
+};
+
+export const loadReadingAnchor = (key: string): ReadingAnchor | null => {
+ const storage = getStorage();
+ return storage ? readAnchor(storage, buildStorageKey(key)) : null;
+};
+
+export const saveReadingAnchor = (key: string, anchor: ReadingAnchor): void => {
+ const storage = getStorage();
+ if (!storage) return;
+
+ const storageKey = buildStorageKey(key);
+ const payload = JSON.stringify(anchor);
+ try {
+ storage.setItem(storageKey, payload);
+ } catch (error) {
+ // Likely QuotaExceededError — free space and retry once.
+ try {
+ pruneReadingAnchors(storage);
+ storage.setItem(storageKey, payload);
+ } catch {
+ console.error('[readingAnchorStore] failed to persist reading anchor', error);
+ }
+ }
+};
+
+export const clearReadingAnchor = (key: string): void => {
+ try {
+ getStorage()?.removeItem(buildStorageKey(key));
+ } catch {
+ // ignore
+ }
+};