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.

🐛 fix: align topic and message search navigation (#19001)

YuTengjinga82edf7f8909
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index 091a99e3701..d60f8fdb95a 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -471,7 +471,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
);
return (
- <Flexbox data-testid="topic-item" style={{ position: 'relative' }}>
+ <Flexbox data-testid="topic-item" data-topic-id={id} style={{ position: 'relative' }}>
{metaCard ? (
<Popover
arrow={false}
diff --git a/src/features/AgentSidebar/Topic/List/index.test.tsx b/src/features/AgentSidebar/Topic/List/index.test.tsx
index 23d243b6522..784ca653525 100644
--- a/src/features/AgentSidebar/Topic/List/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/index.test.tsx
@@ -56,6 +56,10 @@ vi.mock('@/hooks/useFetchChatTopics', () => ({
useFetchChatTopics: vi.fn(),
}));
+vi.mock('@/hooks/useFetchActiveTopicDetail', () => ({
+ useFetchActiveTopicDetail: vi.fn(),
+}));
+
vi.mock('@/hooks/usePermission', () => ({
usePermission: (action: 'create_content') => ({
allowed: permissionMock[action],
diff --git a/src/features/AgentSidebar/Topic/List/index.tsx b/src/features/AgentSidebar/Topic/List/index.tsx
index 2ae7556fe18..99e3b068477 100644
--- a/src/features/AgentSidebar/Topic/List/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/index.tsx
@@ -6,6 +6,7 @@ import urlJoin from 'url-join';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import { useDeferredMount } from '@/hooks/useDeferredMount';
+import { useFetchActiveTopicDetail } from '@/hooks/useFetchActiveTopicDetail';
import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';
import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
@@ -36,6 +37,7 @@ const TopicList = memo(() => {
const { topicGroupMode } = useAgentTopicGroupMode();
useFetchChatTopics();
+ useFetchActiveTopicDetail();
// Route transitions must paint instantly: the mount commit shows a skeleton
// frame and the real list renders in a deferred (interruptible) follow-up
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
index b49a453b9a3..73817fd4f3e 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
@@ -3,7 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { MoreHorizontal } from 'lucide-react';
-import React, { memo } from 'react';
+import React, { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
@@ -15,6 +15,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
+import { useScrollActiveTopicIntoView } from '../../hooks/useScrollActiveTopicIntoView';
import { useNavigateToAgentTopics } from '../../hooks/useTopicNavigation';
import TopicItem from '../../List/Item';
@@ -25,19 +26,25 @@ const FlatMode = memo(() => {
const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);
const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
- const [hasMore, isExpandingPageSize, activeAgentId] = useChatStore((s) => [
+ const [hasMore, isExpandingPageSize, activeAgentId, activeTopicId] = useChatStore((s) => [
topicSelectors.hasMoreTopicsForSidebar(s),
topicSelectors.isExpandingPageSize(s),
s.activeAgentId,
+ s.activeTopicId,
]);
const activeTopicList = useChatStore(
topicSelectors.displayTopicsForSidebar(topicPageSize, topicSortBy, topicIncludeCompleted),
isEqual,
);
+ const renderedTopicIds = useMemo(
+ () => activeTopicList?.map((topic) => topic.id).join(':') ?? '',
+ [activeTopicList],
+ );
+ const listRef = useScrollActiveTopicIntoView(activeTopicId, renderedTopicIds);
return (
- <Flexbox gap={1}>
+ <Flexbox gap={1} ref={listRef}>
{activeTopicList?.map((topic) => (
<TopicItem
fav={topic.favorite}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
index 101a2e1a699..0f57a7b6a85 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
@@ -3,7 +3,7 @@
import { Accordion, Flexbox } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
import { MoreHorizontal } from 'lucide-react';
-import { type ComponentType, memo, useMemo } from 'react';
+import { type ComponentType, memo, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
@@ -18,6 +18,7 @@ import { preferenceSelectors } from '@/store/user/selectors';
import { type GroupedTopic } from '@/types/topic';
import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';
+import { useScrollActiveTopicIntoView } from '../hooks/useScrollActiveTopicIntoView';
import { useNavigateToAgentTopics } from '../hooks/useTopicNavigation';
export interface GroupItemComponentProps {
@@ -37,10 +38,11 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
const { topicGroupMode } = useAgentTopicGroupMode();
- const [hasMore, isExpandingPageSize, activeAgentId] = useChatStore((s) => [
+ const [hasMore, isExpandingPageSize, activeAgentId, activeTopicId] = useChatStore((s) => [
topicSelectors.hasMoreTopicsForSidebar(s),
topicSelectors.isExpandingPageSize(s),
s.activeAgentId,
+ s.activeTopicId,
]);
const groupSelector = useMemo(
@@ -57,9 +59,36 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
const groupIds = useMemo(() => groupTopics.map((group) => group.id), [groupTopics]);
const { expandedKeys, setExpandedKeys } = useTopicGroupCollapse(topicGroupMode, groupIds);
+ const activeGroupId = useMemo(
+ () =>
+ activeTopicId
+ ? groupTopics.find((group) => group.children.some((topic) => topic.id === activeTopicId))
+ ?.id
+ : undefined,
+ [activeTopicId, groupTopics],
+ );
+ const expandedActiveTargetRef = useRef<string | undefined>(undefined);
+
+ useEffect(() => {
+ if (!activeTopicId || !activeGroupId) return;
+
+ const target = `${activeTopicId}:${activeGroupId}`;
+ if (expandedActiveTargetRef.current === target) return;
+ expandedActiveTargetRef.current = target;
+
+ if (!expandedKeys.includes(activeGroupId)) {
+ setExpandedKeys([...expandedKeys, activeGroupId]);
+ }
+ }, [activeGroupId, activeTopicId, expandedKeys, setExpandedKeys]);
+
+ const listReady = useMemo(
+ () => `${groupIds.join(':')}|${expandedKeys.join(':')}`,
+ [expandedKeys, groupIds],
+ );
+ const listRef = useScrollActiveTopicIntoView(activeTopicId, listReady);
return (
- <Flexbox gap={2}>
+ <Flexbox gap={2} ref={listRef}>
<Accordion
expandedKeys={expandedKeys}
gap={2}
diff --git a/src/features/AgentSidebar/Topic/hooks/useScrollActiveTopicIntoView.test.ts b/src/features/AgentSidebar/Topic/hooks/useScrollActiveTopicIntoView.test.ts
new file mode 100644
index 00000000000..9ed0c54675b
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/hooks/useScrollActiveTopicIntoView.test.ts
@@ -0,0 +1,81 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import type { MutableRefObject } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useScrollActiveTopicIntoView } from './useScrollActiveTopicIntoView';
+
+const calls: { element: Element; options: unknown }[] = [];
+const originalScrollIntoView = Element.prototype.scrollIntoView;
+
+beforeEach(() => {
+ calls.length = 0;
+ Element.prototype.scrollIntoView = vi.fn(function (this: Element, options: unknown) {
+ calls.push({ element: this, options });
+ });
+});
+
+afterEach(() => {
+ Element.prototype.scrollIntoView = originalScrollIntoView;
+});
+
+describe('useScrollActiveTopicIntoView', () => {
+ it('scrolls the active topic row into the nearest visible position', () => {
+ const container = document.createElement('div');
+ const row = document.createElement('div');
+ row.dataset.topicId = 'topic-2';
+ container.append(row);
+
+ const { result, rerender } = renderHook(
+ ({ ready }) => useScrollActiveTopicIntoView('topic-2', ready),
+ { initialProps: { ready: '' } },
+ );
+ act(() => {
+ (result.current as MutableRefObject<HTMLDivElement | null>).current = container;
+ });
+ rerender({ ready: 'topic-2' });
+
+ expect(calls).toEqual([{ element: row, options: { block: 'nearest' } }]);
+ });
+
+ it('waits until an asynchronously loaded active row is rendered', () => {
+ const container = document.createElement('div');
+ const { result, rerender } = renderHook(
+ ({ ready }) => useScrollActiveTopicIntoView('topic-2', ready),
+ { initialProps: { ready: '' } },
+ );
+ act(() => {
+ (result.current as MutableRefObject<HTMLDivElement | null>).current = container;
+ });
+ rerender({ ready: 'topic-1' });
+ expect(calls).toHaveLength(0);
+
+ const row = document.createElement('div');
+ row.dataset.topicId = 'topic-2';
+ container.append(row);
+ rerender({ ready: 'topic-1:topic-2' });
+
+ expect(calls).toHaveLength(1);
+ });
+
+ it('does not reveal the same active topic again when unrelated list state changes', () => {
+ const container = document.createElement('div');
+ const row = document.createElement('div');
+ row.dataset.topicId = 'topic-2';
+ container.append(row);
+
+ const { result, rerender } = renderHook(
+ ({ ready }) => useScrollActiveTopicIntoView('topic-2', ready),
+ { initialProps: { ready: '' } },
+ );
+ act(() => {
+ (result.current as MutableRefObject<HTMLDivElement | null>).current = container;
+ });
+ rerender({ ready: 'topic-2' });
+ rerender({ ready: 'topic-2:unrelated-group' });
+
+ expect(calls).toHaveLength(1);
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/hooks/useScrollActiveTopicIntoView.ts b/src/features/AgentSidebar/Topic/hooks/useScrollActiveTopicIntoView.ts
new file mode 100644
index 00000000000..51b3af48811
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/hooks/useScrollActiveTopicIntoView.ts
@@ -0,0 +1,26 @@
+import { useEffect, useRef } from 'react';
+
+/**
+ * Reveals each route-selected topic once after its row becomes available.
+ *
+ * The list readiness signal may also change for unrelated accordion or ordering updates. Tracking
+ * only successful reveals prevents those updates from pulling the sidebar back to the active row.
+ */
+export const useScrollActiveTopicIntoView = (activeTopicId?: string | null, ready?: unknown) => {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const revealedTopicIdRef = useRef<string | undefined>(undefined);
+
+ useEffect(() => {
+ if (!activeTopicId || revealedTopicIdRef.current === activeTopicId) return;
+
+ const activeRow = containerRef.current?.querySelector<HTMLElement>(
+ `[data-topic-id="${CSS.escape(activeTopicId)}"]`,
+ );
+ if (!activeRow) return;
+
+ activeRow.scrollIntoView({ block: 'nearest' });
+ revealedTopicIdRef.current = activeTopicId;
+ }, [activeTopicId, ready]);
+
+ return containerRef;
+};
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 0a4293cbcbb..d34db60d29f 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -25,6 +25,7 @@ import {
} from '../hooks/useConversationScroll';
import { useSelectionMessageIds } from '../hooks/useSelectionMessageIds';
import { useTopicScrollPersist } from '../hooks/useTopicScrollPersist';
+import type { ResolvedMessageDeepLink } from '../utils/messageDeepLink';
import AutoScroll from './AutoScroll';
import { AT_BOTTOM_THRESHOLD } from './AutoScroll/const';
import { useAutoScrollEnabled } from './AutoScroll/useAutoScrollEnabled';
@@ -42,6 +43,7 @@ interface VirtualizedListProps {
footerSlot?: ReactNode;
headerSlot?: ReactNode;
itemContent: (index: number, data: string) => ReactNode;
+ messageDeepLink?: ResolvedMessageDeepLink;
}
/**
@@ -50,8 +52,9 @@ interface VirtualizedListProps {
* Based on ConversationStore data flow, no dependency on global ChatStore.
*/
const VirtualizedList = memo<VirtualizedListProps>(
- ({ dataSource, footerSlot, headerSlot, itemContent }) => {
+ ({ dataSource, footerSlot, headerSlot, itemContent, messageDeepLink }) => {
const virtuaRef = useRef<VListHandle>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastUserScrollIntentAtRef = useRef(0);
@@ -69,8 +72,10 @@ const VirtualizedList = memo<VirtualizedListProps>(
const contextKey = useConversationStore((s) => messageMapKey(s.context));
const { recordScroll } = useTopicScrollPersist({
contextKey,
+ containerRef,
dataSourceLength: dataSource.length,
headerOffset,
+ messageDeepLink,
virtuaRef,
});
@@ -300,6 +305,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
return (
<div
+ ref={containerRef}
style={{ height: '100%', position: 'relative' }}
onKeyDownCapture={handleKeyDown}
onPointerDownCapture={markUserScrollIntent}
diff --git a/src/features/Conversation/ChatList/hooks/useMessageDeepLink.test.ts b/src/features/Conversation/ChatList/hooks/useMessageDeepLink.test.ts
new file mode 100644
index 00000000000..ab38467b492
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useMessageDeepLink.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseMessageIdFromHash } from './useMessageDeepLink';
+
+describe('parseMessageIdFromHash', () => {
+ it('parses and decodes a message id', () => {
+ expect(parseMessageIdFromHash('#msg_%E4%B8%AD')).toBe('msg_中');
+ });
+
+ it('returns undefined for an empty hash', () => {
+ expect(parseMessageIdFromHash('')).toBeUndefined();
+ });
+
+ it('keeps a malformed encoded id usable', () => {
+ expect(parseMessageIdFromHash('#msg_%')).toBe('msg_%');
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useMessageDeepLink.ts b/src/features/Conversation/ChatList/hooks/useMessageDeepLink.ts
new file mode 100644
index 00000000000..164741934c7
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useMessageDeepLink.ts
@@ -0,0 +1,31 @@
+import { useCallback, useMemo } from 'react';
+import { useLocation, useNavigate } from 'react-router';
+
+import type { MessageDeepLink } from '../utils/messageDeepLink';
+
+export const parseMessageIdFromHash = (hash: string) => {
+ const encodedId = hash.replace(/^#/, '');
+ if (!encodedId) return;
+
+ try {
+ return decodeURIComponent(encodedId);
+ } catch {
+ return encodedId;
+ }
+};
+
+/** Reads and consumes a message hash after the conversation has located the target. */
+export const useMessageDeepLink = (): MessageDeepLink | undefined => {
+ const location = useLocation();
+ const navigate = useNavigate();
+ const messageId = useMemo(() => parseMessageIdFromHash(location.hash), [location.hash]);
+ const clearHash = useCallback(() => {
+ navigate(`${location.pathname}${location.search}`, { replace: true });
+ }, [location.pathname, location.search, navigate]);
+
+ return useMemo(
+ () =>
+ messageId ? { id: messageId, navigationKey: location.key, onHandled: clearHash } : undefined,
+ [clearHash, location.key, messageId],
+ );
+};
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
index c2eab7bca9f..52564379773 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
@@ -48,6 +48,216 @@ describe('useTopicScrollPersist', () => {
});
describe('initial restore', () => {
+ it('lets a message deep link override the saved scroll position', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 5000,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 6000 });
+ const onHandled = vi.fn();
+
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ headerOffset: 1,
+ messageDeepLink: {
+ displayMessageId: 'assistant-group',
+ id: 'assistant-child',
+ index: 12,
+ navigationKey: 'navigation-1',
+ onHandled,
+ },
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(4);
+
+ expect(handle.scrollToIndex).toHaveBeenCalledWith(13, { align: 'center' });
+ expect(handle.scrollTo).not.toHaveBeenCalled();
+ expect(onHandled).toHaveBeenCalledTimes(1);
+ });
+
+ it('centers the exact nested message after its virtual row mounts', async () => {
+ const handle = createFakeVList({ scrollSize: 6000 });
+ const container = document.createElement('div');
+ const target = document.createElement('div');
+ target.id = 'assistant-child';
+ container.append(target);
+ document.body.append(container);
+ const originalScrollIntoView = Element.prototype.scrollIntoView;
+ const scrollIntoView = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+
+ try {
+ renderHook(() =>
+ useTopicScrollPersist({
+ containerRef: { current: container },
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ messageDeepLink: {
+ displayMessageId: 'assistant-group',
+ id: 'assistant-child',
+ index: 12,
+ navigationKey: 'navigation-1',
+ },
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(4);
+
+ expect(scrollIntoView).toHaveBeenCalledWith({ block: 'center' });
+ } finally {
+ container.remove();
+ Element.prototype.scrollIntoView = originalScrollIntoView;
+ }
+ });
+
+ it('keeps the deep link pending when only the owning row is rendered', async () => {
+ const handle = createFakeVList({ scrollSize: 6000 });
+ const container = document.createElement('div');
+ const topLevelMessage = document.createElement('div');
+ topLevelMessage.id = 'assistant-group';
+ container.append(topLevelMessage);
+ document.body.append(container);
+ const onHandled = vi.fn();
+ const originalScrollIntoView = Element.prototype.scrollIntoView;
+ const scrollIntoView = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+
+ try {
+ renderHook(() =>
+ useTopicScrollPersist({
+ containerRef: { current: container },
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ messageDeepLink: {
+ displayMessageId: 'assistant-group',
+ id: 'assistant-child',
+ index: 12,
+ navigationKey: 'navigation-1',
+ onHandled,
+ },
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(40);
+
+ expect(scrollIntoView).toHaveBeenCalledWith({ block: 'center' });
+ expect(onHandled).not.toHaveBeenCalled();
+ } finally {
+ container.remove();
+ Element.prototype.scrollIntoView = originalScrollIntoView;
+ }
+ });
+
+ it('consumes a deep link when animation frames are suspended', async () => {
+ const handle = createFakeVList({ scrollSize: 6000 });
+ const container = document.createElement('div');
+ const target = document.createElement('div');
+ target.id = 'assistant-child';
+ container.append(target);
+ document.body.append(container);
+ const onHandled = vi.fn();
+ const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
+ const originalScrollIntoView = Element.prototype.scrollIntoView;
+ const scrollIntoView = vi.fn();
+ globalThis.requestAnimationFrame = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+
+ try {
+ renderHook(() =>
+ useTopicScrollPersist({
+ containerRef: { current: container },
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ messageDeepLink: {
+ displayMessageId: 'assistant-group',
+ id: 'assistant-child',
+ index: 12,
+ navigationKey: 'navigation-1',
+ onHandled,
+ },
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await vi.advanceTimersByTimeAsync(32);
+
+ expect(scrollIntoView).toHaveBeenCalledWith({ block: 'center' });
+ expect(onHandled).toHaveBeenCalledTimes(1);
+ } finally {
+ container.remove();
+ globalThis.requestAnimationFrame = originalRequestAnimationFrame;
+ Element.prototype.scrollIntoView = originalScrollIntoView;
+ }
+ });
+
+ it('cancels a pending snapshot restore when a deep link arrives', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 5000,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
+ const { rerender } = renderHook(
+ ({ navigationKey }: { navigationKey?: string }) =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ messageDeepLink: navigationKey
+ ? {
+ displayMessageId: 'target',
+ id: 'target',
+ index: 8,
+ navigationKey,
+ }
+ : undefined,
+ virtuaRef: refOf(handle),
+ }),
+ { initialProps: { navigationKey: undefined as string | undefined } },
+ );
+
+ await advanceFrames(3);
+ rerender({ navigationKey: 'navigation-1' });
+ await advanceFrames(4);
+ handle.scrollSize = 6000;
+ await advanceFrames(6);
+
+ expect(handle.scrollToIndex).toHaveBeenCalledWith(8, { align: 'center' });
+ expect(handle.scrollTo).not.toHaveBeenCalled();
+ });
+
+ it('handles another hash navigation within the same topic', async () => {
+ const handle = createFakeVList({ scrollSize: 6000 });
+ const { rerender } = renderHook(
+ ({ index, navigationKey }: { index: number; navigationKey: string }) =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ messageDeepLink: {
+ displayMessageId: `message-${index}`,
+ id: `message-${index}`,
+ index,
+ navigationKey,
+ },
+ virtuaRef: refOf(handle),
+ }),
+ { initialProps: { index: 8, navigationKey: 'navigation-1' } },
+ );
+
+ await advanceFrames(4);
+ rerender({ index: 20, navigationKey: 'navigation-2' });
+ await advanceFrames(4);
+
+ expect(handle.scrollToIndex).toHaveBeenNthCalledWith(1, 8, { align: 'center' });
+ expect(handle.scrollToIndex).toHaveBeenNthCalledWith(2, 20, { align: 'center' });
+ });
+
it('falls back to scrollToIndex(last, end) when there is no snapshot', async () => {
const handle = createFakeVList({ scrollSize: 5000 });
renderHook(() =>
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
index 9bc392c5f47..0ad2f5b32ed 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef } from 'react';
import type { VListHandle } from 'virtua';
import { AT_BOTTOM_THRESHOLD } from '../components/AutoScroll/const';
+import type { ResolvedMessageDeepLink } from '../utils/messageDeepLink';
import {
isDraftPromotionKey,
loadScrollSnapshot,
@@ -12,6 +13,8 @@ import {
} from '../utils/scrollSnapshotStore';
const FLUSH_THROTTLE_MS = 200;
+const DEEP_LINK_MAX_ATTEMPTS = 30;
+const DEEP_LINK_RETRY_MS = 16;
// Cap polling for virtua's scrollSize to settle so we don't loop forever when
// the saved offset is unreachable (e.g. messages were trimmed since save).
const RESTORE_MAX_FRAMES = 30;
@@ -23,6 +26,7 @@ interface PendingWrite {
}
interface UseTopicScrollPersistOptions {
+ containerRef?: RefObject<HTMLDivElement | null>;
contextKey: string;
dataSourceLength: number;
/**
@@ -31,9 +35,47 @@ interface UseTopicScrollPersistOptions {
* scrollToIndex lands on the right virtua row.
*/
headerOffset?: number;
+ messageDeepLink?: ResolvedMessageDeepLink;
virtuaRef: RefObject<VListHandle | null>;
}
+const findDeepLinkElement = (
+ container: HTMLDivElement,
+ messageId: string,
+ displayMessageId: string,
+) => {
+ const document = container.ownerDocument;
+ const exactCandidateIds = [messageId, `${messageId}__answer`, `${messageId}__workflow`];
+
+ for (const id of exactCandidateIds) {
+ const element = document.getElementById(id);
+ if (element && container.contains(element)) return { element, exact: true };
+ }
+
+ const messageElements = Array.from(container.querySelectorAll<HTMLElement>('[data-message-id]'));
+ const exactMessageElement = messageElements.find(
+ (element) => element.dataset.messageId === messageId,
+ );
+ if (exactMessageElement) return { element: exactMessageElement, exact: true };
+
+ if (messageId === displayMessageId) return;
+
+ const fallbackCandidateIds = [
+ displayMessageId,
+ `${displayMessageId}__answer`,
+ `${displayMessageId}__workflow`,
+ ];
+ for (const id of fallbackCandidateIds) {
+ const element = document.getElementById(id);
+ if (element && container.contains(element)) return { element, exact: false };
+ }
+
+ const displayMessageElement = messageElements.find(
+ (element) => element.dataset.messageId === displayMessageId,
+ );
+ return displayMessageElement ? { element: displayMessageElement, exact: false } : undefined;
+};
+
/**
* Persists per-topic chat scroll position to localStorage.
*
@@ -46,9 +88,11 @@ interface UseTopicScrollPersistOptions {
* contextKey-change branch, preserving scroll instead of restoring.
*/
export const useTopicScrollPersist = ({
+ containerRef,
contextKey,
dataSourceLength,
headerOffset = 0,
+ messageDeepLink,
virtuaRef,
}: UseTopicScrollPersistOptions) => {
const pendingWriteRef = useRef<PendingWrite | null>(null);
@@ -73,6 +117,8 @@ export const useTopicScrollPersist = ({
// recordScroll and overwrite the snapshot — typically with offset 0 when
// virtua clamps the target, locking the user at the top on every revisit.
const restoringRef = useRef(false);
+ const handledDeepLinkRef = useRef<string | undefined>(undefined);
+ const restoreSequenceRef = useRef(0);
const flushNow = useCallback(() => {
if (flushTimerRef.current) {
@@ -152,17 +198,25 @@ export const useTopicScrollPersist = ({
// Restore (or fall back to scroll-to-bottom) once data is available for
// the active contextKey. Re-runs on contextKey or data length change.
useEffect(() => {
- if (!needsRestoreRef.current) return;
+ const deepLinkKey = messageDeepLink
+ ? `${contextKey}:${messageDeepLink.navigationKey}`
+ : undefined;
+ const shouldHandleDeepLink = !!messageDeepLink && handledDeepLinkRef.current !== deepLinkKey;
+
+ if (!needsRestoreRef.current && !shouldHandleDeepLink) return;
if (!virtuaRef.current || dataSourceLength === 0) return;
needsRestoreRef.current = false;
restoringRef.current = true;
+ const restoreSequence = ++restoreSequenceRef.current;
// After two rAFs the programmatic scroll's onScroll volley has flushed, so
// we can re-enable recording and record where the restore landed.
const finalize = (convergeSnapshot: boolean) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
+ if (restoreSequenceRef.current !== restoreSequence) return;
+
const ref = virtuaRef.current;
if (ref) {
const isAtBottom =
@@ -188,6 +242,64 @@ export const useTopicScrollPersist = ({
});
};
+ if (shouldHandleDeepLink && messageDeepLink) {
+ const targetDeepLink = messageDeepLink;
+ handledDeepLinkRef.current = deepLinkKey;
+ virtuaRef.current.scrollToIndex(headerOffset + targetDeepLink.index, { align: 'center' });
+
+ const container = containerRef?.current;
+ if (!container) {
+ targetDeepLink.onHandled?.();
+ finalize(false);
+ return;
+ }
+
+ // `scrollToIndex` first mounts the virtual row. Wait until its real DOM
+ // node exists, then center the exact nested assistant block when
+ // available. Timer polling keeps this progressing when Chromium suspends
+ // animation frames for a non-painting view, while still allowing virtua
+ // to measure between attempts.
+ let attempts = 0;
+ const locateTarget = () => {
+ if (restoreSequenceRef.current !== restoreSequence) return;
+
+ const ref = virtuaRef.current;
+ if (!ref) {
+ restoringRef.current = false;
+ return;
+ }
+
+ const targetMatch = findDeepLinkElement(
+ container,
+ targetDeepLink.id,
+ targetDeepLink.displayMessageId,
+ );
+ if (targetMatch?.exact) {
+ targetMatch.element.scrollIntoView({ block: 'center' });
+ targetDeepLink.onHandled?.();
+ finalize(false);
+ return;
+ }
+
+ if (attempts >= DEEP_LINK_MAX_ATTEMPTS) {
+ // A nested message can be absent while its process fold is collapsed
+ // or its compressed group is showing the summary tab. Keep the hash
+ // pending instead of consuming the deep link at the owning row, so a
+ // later render can retry the exact target.
+ handledDeepLinkRef.current = undefined;
+ targetMatch?.element.scrollIntoView({ block: 'center' });
+ finalize(false);
+ return;
+ }
+
+ attempts += 1;
+ ref.scrollToIndex(headerOffset + targetDeepLink.index, { align: 'center' });
+ setTimeout(locateTarget, DEEP_LINK_RETRY_MS);
+ };
+ setTimeout(locateTarget, DEEP_LINK_RETRY_MS);
+ return;
+ }
+
const snapshot = loadScrollSnapshot(contextKey);
const targetOffset = snapshot && !snapshot.atBottom ? snapshot.offset : null;
@@ -204,6 +316,8 @@ export const useTopicScrollPersist = ({
// below-the-fold heights yet.
let attempts = 0;
const tryScroll = () => {
+ if (restoreSequenceRef.current !== restoreSequence) return;
+
const ref = virtuaRef.current;
if (!ref) {
restoringRef.current = false;
@@ -220,7 +334,15 @@ export const useTopicScrollPersist = ({
requestAnimationFrame(tryScroll);
};
requestAnimationFrame(tryScroll);
- }, [contextKey, dataSourceLength, flushNow, headerOffset, virtuaRef]);
+ }, [
+ containerRef,
+ contextKey,
+ dataSourceLength,
+ flushNow,
+ headerOffset,
+ messageDeepLink,
+ virtuaRef,
+ ]);
// One-shot housekeeping: drop expired entries and enforce the cap.
useEffect(() => {
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index 1fcf3c3cdea..63ba38842e6 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -28,6 +28,8 @@ import VirtualizedList from './components/VirtualizedList';
import { useAgentSignalReceipts } from './hooks/useAgentSignalReceipts';
import { useMessageRefreshError } from './hooks/useMessageRefreshError';
import { resolveMessageListFeedback } from './resolveMessageListFeedback';
+import type { MessageDeepLink } from './utils/messageDeepLink';
+import { resolveMessageDeepLink } from './utils/messageDeepLink';
const MessageAuthorConfigLoader = memo<{ agentId: string; isLogin: boolean | undefined }>(
({ agentId, isLogin }) => {
@@ -77,6 +79,8 @@ export interface ChatListProps {
* Custom item renderer. If not provided, uses default ChatItem.
*/
itemContent?: (index: number, id: string) => ReactNode;
+ /** Message hash target to locate after the virtual list has rendered. */
+ messageDeepLink?: MessageDeepLink;
/**
* Force showing welcome component even when messages exist
*/
@@ -100,6 +104,7 @@ const ChatList = memo<ChatListProps>(
headerSlot,
welcome,
itemContent,
+ messageDeepLink,
showWelcome,
}) => {
// Fetch messages (SWR key is null when skipFetch is true)
@@ -141,6 +146,10 @@ const ChatList = memo<ChatListProps>(
[allDisplayMessages, filterItem],
);
const displayMessageIds = useMemo(() => displayMessages.map((m) => m.id), [displayMessages]);
+ const resolvedMessageDeepLink = useMemo(
+ () => resolveMessageDeepLink(displayMessages, messageDeepLink),
+ [displayMessages, messageDeepLink],
+ );
const overlayHeight = useConversationStore(inputSelectors.chatInputOverlayHeight);
const latestMessageId = displayMessageIds.at(-1);
@@ -265,6 +274,7 @@ const ChatList = memo<ChatListProps>(
footerSlot={footerSlot}
headerSlot={headerSlot}
itemContent={itemContent ?? defaultItemContent}
+ messageDeepLink={resolvedMessageDeepLink}
/>
</MessageActionProvider>
);
diff --git a/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts b/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts
new file mode 100644
index 00000000000..2cf976f5fb6
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/messageDeepLink.test.ts
@@ -0,0 +1,66 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { resolveMessageDeepLink } from './messageDeepLink';
+
+const message = (id: string, overrides: Partial<UIChatMessage> = {}): UIChatMessage => ({
+ content: '',
+ createdAt: 0,
+ id,
+ role: 'user',
+ updatedAt: 0,
+ ...overrides,
+});
+
+const deepLink = (id: string) => ({ id, navigationKey: 'navigation-1' });
+
+describe('resolveMessageDeepLink', () => {
+ it('returns the top-level virtual row for a direct message', () => {
+ const messages = [message('first'), message('target')];
+
+ expect(resolveMessageDeepLink(messages, deepLink('target'))).toMatchObject({
+ displayMessageId: 'target',
+ index: 1,
+ });
+ });
+
+ it('returns the owning assistant group for a nested assistant message', () => {
+ const messages = [
+ message('user'),
+ message('assistant-group', {
+ children: [
+ { content: 'first', id: 'assistant-1' },
+ { content: 'search hit', id: 'assistant-2' },
+ ],
+ role: 'assistantGroup',
+ }),
+ ];
+
+ expect(resolveMessageDeepLink(messages, deepLink('assistant-2'))).toMatchObject({
+ displayMessageId: 'assistant-group',
+ index: 1,
+ });
+ });
+
+ it('resolves nested task, council, and compressed messages to their virtual row', () => {
+ const messages = [
+ message('tasks-row', { tasks: [message('task-hit', { role: 'task' })], role: 'tasks' }),
+ message('council-row', {
+ members: [message('council-hit', { role: 'assistant' })],
+ role: 'agentCouncil',
+ }),
+ message('compressed-row', {
+ compressedMessages: [message('compressed-hit')],
+ role: 'compressedGroup',
+ }),
+ ];
+
+ expect(resolveMessageDeepLink(messages, deepLink('task-hit'))?.index).toBe(0);
+ expect(resolveMessageDeepLink(messages, deepLink('council-hit'))?.index).toBe(1);
+ expect(resolveMessageDeepLink(messages, deepLink('compressed-hit'))?.index).toBe(2);
+ });
+
+ it('returns undefined when the message is not rendered by the list', () => {
+ expect(resolveMessageDeepLink([message('first')], deepLink('missing'))).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/ChatList/utils/messageDeepLink.ts b/src/features/Conversation/ChatList/utils/messageDeepLink.ts
new file mode 100644
index 00000000000..18224c98fff
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/messageDeepLink.ts
@@ -0,0 +1,60 @@
+import type { AssistantContentBlock, ChatToolPayload, UIChatMessage } from '@lobechat/types';
+
+export interface MessageDeepLink {
+ id: string;
+ navigationKey: string;
+ onHandled?: () => void;
+}
+
+export interface ResolvedMessageDeepLink extends MessageDeepLink {
+ displayMessageId: string;
+ index: number;
+}
+
+const toolsContainMessage = (tools: ChatToolPayload[] | undefined, messageId: string) =>
+ tools?.some((tool) => tool.result_msg_id === messageId) ?? false;
+
+function assistantBlockContainsMessage(block: AssistantContentBlock, messageId: string): boolean {
+ return (
+ block.id === messageId ||
+ toolsContainMessage(block.tools, messageId) ||
+ block.council?.some((message) => messageContainsMessage(message, messageId)) === true
+ );
+}
+
+function messageContainsMessage(message: UIChatMessage, messageId: string): boolean {
+ return (
+ message.id === messageId ||
+ toolsContainMessage(message.tools, messageId) ||
+ message.children?.some((block) => assistantBlockContainsMessage(block, messageId)) === true ||
+ message.taskCompletions?.some((block) => assistantBlockContainsMessage(block, messageId)) ===
+ true ||
+ message.compressedMessages?.some((child) => messageContainsMessage(child, messageId)) ===
+ true ||
+ message.members?.some((member) => messageContainsMessage(member, messageId)) === true ||
+ message.tasks?.some((task) => messageContainsMessage(task, messageId)) === true ||
+ message.pinnedMessages?.some((pinned) => pinned.id === messageId) === true ||
+ message.signalCallbacks?.some(
+ (block) =>
+ block.sourceToolMessageId === messageId ||
+ block.callbacks.some((callback) => callback.id === messageId),
+ ) === true
+ );
+}
+
+/** Resolves a raw database message id to the virtual list row that renders it. */
+export const resolveMessageDeepLink = (
+ messages: UIChatMessage[],
+ deepLink: MessageDeepLink | undefined,
+): ResolvedMessageDeepLink | undefined => {
+ if (!deepLink) return;
+
+ const index = messages.findIndex((message) => messageContainsMessage(message, deepLink.id));
+ if (index < 0) return;
+
+ return {
+ ...deepLink,
+ displayMessageId: messages[index].id,
+ index,
+ };
+};
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 3144fe8a4b2..be126855a4f 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -14,6 +14,7 @@ import {
} from '@/features/AgentTransferMigration';
import ChatMiniMap from '@/features/ChatMiniMap';
import { ChatList, ConversationProvider } from '@/features/Conversation';
+import { useMessageDeepLink } from '@/features/Conversation/ChatList/hooks/useMessageDeepLink';
import ComposerDraftReceiver from '@/features/Conversation/ComposerDraftReceiver';
import { useChatFollowUp } from '@/features/Conversation/hooks/useChatFollowUp';
import {
@@ -65,13 +66,11 @@ const styles = createStaticStyles(({ css }) => ({
const Conversation = memo(() => {
const { t } = useTranslation('chat');
const context = useAgentContext();
+ const messageDeepLink = useMessageDeepLink();
// Get raw dbMessages from ChatStore for this context
// ConversationStore will parse them internally to generate displayMessages
- const chatKey = useMemo(
- () => messageMapKey(context),
- [context.agentId, context.topicId, context.threadId],
- );
+ const chatKey = messageMapKey(context);
const replaceMessages = useChatStore((s) => s.replaceMessages);
const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);
@@ -157,6 +156,7 @@ const Conversation = memo(() => {
) : (
<ChatList
headerSlot={<div aria-hidden className={styles.floatingHeaderSpacer} />}
+ messageDeepLink={messageDeepLink}
welcome={<AgentHome />}
footerSlot={
isSubagentThread ? (
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
index 04dee3f3684..adc3b717a0a 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/index.tsx
@@ -6,6 +6,7 @@ import urlJoin from 'url-join';
import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useFetchActiveTopicDetail } from '@/hooks/useFetchActiveTopicDetail';
import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentGroupStore } from '@/store/agentGroup';
@@ -32,6 +33,7 @@ const TopicList = memo(() => {
const topicGroupMode = useUserStore(preferenceSelectors.topicGroupMode);
useFetchChatTopics();
+ useFetchActiveTopicDetail();
// Show skeleton when current session's topic data is not yet loaded
if (isUndefinedTopics) return <SkeletonList />;
diff --git a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx b/src/routes/(main)/group/features/Conversation/ConversationArea.tsx
index 028d0aab68f..4d3ada2123f 100644
--- a/src/routes/(main)/group/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/group/features/Conversation/ConversationArea.tsx
@@ -2,7 +2,7 @@
import { Flexbox } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import { memo, Suspense, useMemo } from 'react';
+import { memo, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -11,6 +11,7 @@ import {
} from '@/features/AgentTransferMigration';
import ChatMiniMap from '@/features/ChatMiniMap';
import { ChatList, ConversationProvider } from '@/features/Conversation';
+import { useMessageDeepLink } from '@/features/Conversation/ChatList/hooks/useMessageDeepLink';
import {
ForwardMessageDispatcher,
MessageForwardFooter,
@@ -40,13 +41,11 @@ interface ConversationAreaProps {
const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {
const { t } = useTranslation('chat');
const context = useGroupContext();
+ const messageDeepLink = useMessageDeepLink();
// Get raw dbMessages from ChatStore for this context
// ConversationStore will parse them internally to generate displayMessages
- const chatKey = useMemo(
- () => messageMapKey(context),
- [context.agentId, context.topicId, context.threadId],
- );
+ const chatKey = messageMapKey(context);
const replaceMessages = useChatStore((s) => s.replaceMessages);
const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);
@@ -87,7 +86,7 @@ const Conversation = memo<ConversationAreaProps>(({ mobile = false }) => {
{topicPending ? (
<TopicMigrationPlaceholder groupId={context.groupId} topicId={context.topicId} />
) : (
- <ChatList welcome={<WelcomeChatItem />} />
+ <ChatList messageDeepLink={messageDeepLink} welcome={<WelcomeChatItem />} />
)}
</Flexbox>
{topicPending ? (
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index b424929a5e1..18403660b03 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -551,6 +551,120 @@ describe('topicSelectors', () => {
]);
expect(topicSelectors.displayTopicsForSidebar(20, 'updatedAt', true)(state)).toHaveLength(2);
});
+
+ it('keeps the active topic visible when it falls outside the configured page', () => {
+ const state = merge(initialStore, {
+ activeAgentId: 'agent-1',
+ activeTopicId: 'older-active',
+ topicDataMap: {
+ [topicMapKey({ agentId: 'agent-1' })]: {
+ currentPage: 0,
+ hasMore: true,
+ items: [
+ { id: 'newest', updatedAt: 3 },
+ { id: 'newer', updatedAt: 2 },
+ { id: 'older-active', updatedAt: 1 },
+ ],
+ pageSize: 2,
+ total: 3,
+ },
+ },
+ });
+
+ expect(
+ topicSelectors
+ .displayTopicsForSidebar(
+ 2,
+ 'updatedAt',
+ false,
+ )(state)
+ ?.map(({ id }) => id),
+ ).toEqual(['newest', 'newer', 'older-active']);
+ });
+
+ it('keeps an active completed topic from the detail cache visible', () => {
+ const state = merge(initialStore, {
+ activeAgentId: 'agent-1',
+ activeTopicId: 'archived-active',
+ topicDataMap: {
+ [topicMapKey({ agentId: 'agent-1' })]: {
+ currentPage: 0,
+ hasMore: true,
+ items: [{ id: 'visible', status: 'active', updatedAt: 2 }],
+ pageSize: 20,
+ total: 2,
+ },
+ },
+ topicDetailMap: {
+ 'archived-active': { id: 'archived-active', status: 'completed', updatedAt: 1 },
+ },
+ });
+
+ expect(
+ topicSelectors
+ .displayTopicsForSidebar(
+ 20,
+ 'updatedAt',
+ false,
+ )(state)
+ ?.map(({ id }) => id),
+ ).toEqual(['visible', 'archived-active']);
+ });
+
+ it('keeps an injected active favorite before regular topics', () => {
+ const state = merge(initialStore, {
+ activeAgentId: 'agent-1',
+ activeTopicId: 'archived-favorite',
+ topicDataMap: {
+ [topicMapKey({ agentId: 'agent-1' })]: {
+ currentPage: 0,
+ hasMore: true,
+ items: [
+ { favorite: true, id: 'visible-favorite', updatedAt: 3 },
+ { id: 'regular', updatedAt: 2 },
+ ],
+ pageSize: 20,
+ total: 3,
+ },
+ },
+ topicDetailMap: {
+ 'archived-favorite': {
+ favorite: true,
+ id: 'archived-favorite',
+ status: 'completed',
+ updatedAt: 1,
+ },
+ },
+ });
+
+ expect(
+ topicSelectors
+ .displayTopicsForSidebar(
+ 20,
+ 'updatedAt',
+ false,
+ )(state)
+ ?.map(({ id }) => id),
+ ).toEqual(['visible-favorite', 'archived-favorite', 'regular']);
+ });
+
+ it('does not duplicate an active topic already in the visible page', () => {
+ const state = merge(initialStore, {
+ activeAgentId: 'agent-1',
+ activeTopicId: 'active',
+ topicDataMap: {
+ [topicMapKey({ agentId: 'agent-1' })]: {
+ currentPage: 0,
+ hasMore: false,
+ items: [{ id: 'active', updatedAt: 1 }],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ });
+
+ expect(topicSelectors.displayTopicsForSidebar(20)(state)).toHaveLength(1);
+ });
});
describe('groupedTopicsForSidebar', () => {
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index f68ffcc39d0..ad4a4ca53a9 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -231,7 +231,33 @@ const displayTopicsForSidebar =
// Favorites first, then sorted by the chosen timestamp, then page-sliced
const favTopics = visibleTopics.filter((t) => t.favorite);
const rest = visibleTopics.filter((t) => !t.favorite);
- return [...sortTopics(favTopics, sortBy), ...sortTopics(rest, sortBy)].slice(0, pageSize);
+ const pagedTopics = [...sortTopics(favTopics, sortBy), ...sortTopics(rest, sortBy)].slice(
+ 0,
+ pageSize,
+ );
+ const activeTopic = currentActiveTopic(s);
+
+ // A search result or direct URL can open a topic outside the sidebar's
+ // first page (or an archived topic excluded by the completed filter). Keep
+ // the configured page intact and add that one active row so selection never
+ // disappears merely because the route target was filtered out. An injected
+ // favorite stays in the favorite prefix instead of falling below regular rows.
+ if (
+ activeTopic &&
+ activeTopic.trigger !== 'cron' &&
+ !pagedTopics.some((topic) => topic.id === activeTopic.id)
+ ) {
+ if (activeTopic.favorite) {
+ const pagedFavorites = pagedTopics.filter((topic) => topic.favorite);
+ const pagedRest = pagedTopics.filter((topic) => !topic.favorite);
+
+ return [...sortTopics([...pagedFavorites, activeTopic], sortBy), ...pagedRest];
+ }
+
+ return [...pagedTopics, activeTopic];
+ }
+
+ return pagedTopics;
};
const getGroupFn = (