🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(topic): let workspace members show only their own topics (#21366)
Arvin Xu110c5631dd9d
diff --git a/apps/server/src/routers/lambda/topic/queries.ts b/apps/server/src/routers/lambda/topic/queries.tsindex 2d05f6b56ff..ed4d6248a76 100644--- a/apps/server/src/routers/lambda/topic/queries.ts+++ b/apps/server/src/routers/lambda/topic/queries.ts@@ -133,6 +133,8 @@ export const queryRouter = router({groupId: z.string().nullish(),includeTriggers: z.array(z.string()).optional(),isInbox: z.boolean().optional(),+ /** Only topics the caller created — the workspace "only mine" filter. */+ onlyMine: z.boolean().optional(),pageSize: z.number().max(100).optional(),sessionId: z.string().nullish(),/**@@ -399,6 +401,8 @@ export const queryRouter = router({agentId: z.string().optional(),groupId: z.string().nullish(),keywords: z.string(),+ /** Only topics the caller created — the workspace "only mine" filter. */+ onlyMine: z.boolean().optional(),sessionId: z.string().nullish(),}),)@@ -412,11 +416,13 @@ export const queryRouter = router({await assertCanUseConversationTargets(guardCtx(ctx), [resolved]);- const byAgent = ctx.topicModel.queryByKeyword(input.keywords, {+ const searchOptions = { onlyMine: input.onlyMine };+ const scope = {agentId: resolved.agentId ?? undefined,containerId: resolved.sessionId,groupId: input.groupId,- });+ };+ const byAgent = ctx.topicModel.queryByKeyword(input.keywords, scope, searchOptions);if (!resolved.agentId || !resolved.sessionId || input.groupId) return byAgent;// Legacy topics can still lack agentId before the existing on-read@@ -424,7 +430,11 @@ export const queryRouter = router({// only unassigned legacy rows may supplement the canonical Agent result.const [current, legacy] = await Promise.all([byAgent,- ctx.topicModel.queryByKeyword(input.keywords, { containerId: resolved.sessionId }),+ ctx.topicModel.queryByKeyword(+ input.keywords,+ { containerId: resolved.sessionId },+ searchOptions,+ ),]);return [...new Map(diff --git a/apps/server/src/services/aiChat/index.ts b/apps/server/src/services/aiChat/index.tsindex c2881d1d1b0..89dc29b3ec3 100644--- a/apps/server/src/services/aiChat/index.ts+++ b/apps/server/src/services/aiChat/index.ts@@ -23,6 +23,7 @@ interface GetMessagesAndTopicsParams {excludeStatuses?: string[];excludeTriggers?: string[];includeTriggers?: string[];+ onlyMine?: boolean;};topicId?: string;topicPageSize?: number;diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex cfe0db598fd..fd748fbb9ea 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -83,6 +83,7 @@"filter.groupMode.byTime": "By time","filter.groupMode.flat": "Flat","filter.noDevice": "No device",+ "filter.onlyMine": "Only my topics","filter.organize": "Organize","filter.showCompleted": "Include Archived","filter.sort": "Sort by",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex cdedcf6b4f3..facb541e4fe 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -83,6 +83,7 @@"filter.groupMode.byTime": "按时间阶段","filter.groupMode.flat": "平铺","filter.noDevice": "未绑定设备",+ "filter.onlyMine": "只看我创建的","filter.organize": "整理","filter.showCompleted": "显示已归档","filter.sort": "排序",diff --git a/packages/database/src/models/__tests__/topics/topic.query.onlyMine.test.ts b/packages/database/src/models/__tests__/topics/topic.query.onlyMine.test.tsnew file mode 100644index 00000000000..4e51181ba62--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topic.query.onlyMine.test.ts@@ -0,0 +1,113 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, chatGroups, messages, topics, users, workspaces } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { TopicModel } from '../../topic';++const userId = 'topic-only-mine-user';+const userId2 = 'topic-only-mine-user-2';+const workspaceId = 'topic-only-mine-workspace';+const serverDB: LobeChatDatabase = await getTestDB();+const topicModel = new TopicModel(serverDB, userId, workspaceId);+const isServerDB = process.env.TEST_SERVER_DB === '1';++describe('TopicModel - query onlyMine', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.transaction(async (tx) => {+ await tx.insert(users).values([{ id: userId }, { id: userId2 }]);+ await tx.insert(workspaces).values({+ id: workspaceId,+ name: 'Topic Only Mine Workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ });+ await tx.insert(agents).values({ id: 'ws-agent', userId, workspaceId });+ await tx.insert(chatGroups).values({+ id: 'ws-group',+ title: 'Workspace Group',+ userId,+ workspaceId,+ });+ await tx.insert(topics).values([+ { agentId: 'ws-agent', id: 'agent-mine', userId, workspaceId },+ { agentId: 'ws-agent', id: 'agent-other', userId: userId2, workspaceId },+ { groupId: 'ws-group', id: 'group-mine', userId, workspaceId },+ { groupId: 'ws-group', id: 'group-other', userId: userId2, workspaceId },+ ]);+ });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ it('lists every member topic under a workspace agent by default', async () => {+ const result = await topicModel.query({ agentId: 'ws-agent' });++ expect(result.items.map((topic) => topic.id).sort()).toEqual(['agent-mine', 'agent-other']);+ expect(result.total).toBe(2);+ });++ it('keeps only the caller topics under an agent when onlyMine is set', async () => {+ const result = await topicModel.query({ agentId: 'ws-agent', onlyMine: true });++ expect(result.items.map((topic) => topic.id)).toEqual(['agent-mine']);+ expect(result.total).toBe(1);+ });++ it('keeps only the caller topics under a group when onlyMine is set', async () => {+ const result = await topicModel.query({ groupId: 'ws-group', onlyMine: true });++ expect(result.items.map((topic) => topic.id)).toEqual(['group-mine']);+ expect(result.total).toBe(1);+ });++ // Keyword search uses pg_search (BM25), which only the server test DB has.+ describe.skipIf(!isServerDB)('queryByKeyword', () => {+ beforeEach(async () => {+ await serverDB.insert(topics).values([+ { agentId: 'ws-agent', id: 'search-mine', title: 'Release plan', userId, workspaceId },+ {+ agentId: 'ws-agent',+ id: 'search-other',+ title: 'Release retro',+ userId: userId2,+ workspaceId,+ },+ ]);+ await serverDB.insert(messages).values([+ {+ content: 'release checklist',+ id: 'msg-other',+ role: 'user',+ topicId: 'agent-other',+ userId: userId2,+ workspaceId,+ },+ ]);+ });++ it('finds every member topic by default', async () => {+ const result = await topicModel.queryByKeyword('release', { agentId: 'ws-agent' });++ expect(result.map((topic) => topic.id).sort()).toEqual([+ 'agent-other',+ 'search-mine',+ 'search-other',+ ]);+ });++ /** @example With "only mine" on, a search must not bring back teammates' topics the list hides. */+ it('keeps only the caller topics, by title and by message, when onlyMine is set', async () => {+ const result = await topicModel.queryByKeyword(+ 'release',+ { agentId: 'ws-agent' },+ { onlyMine: true },+ );++ expect(result.map((topic) => topic.id)).toEqual(['search-mine']);+ });+ });+});diff --git a/packages/database/src/models/topic/find.ts b/packages/database/src/models/topic/find.tsindex 86b8d4abd2b..b0f9e08bafe 100644--- a/packages/database/src/models/topic/find.ts+++ b/packages/database/src/models/topic/find.ts@@ -211,9 +211,14 @@ export const queryByKeyword = async (ctx: TopicModelContext,keyword: string,scope?: string | null | TopicKeywordScope,+ { onlyMine }: { onlyMine?: boolean } = {},): Promise<TopicItem[]> => {if (!keyword.trim()) return [];+ // Mirrors the list's workspace "only mine" filter, so a search never brings+ // back the other members' topics the list is hiding.+ const onlyMineCondition = onlyMine ? eq(topics.userId, ctx.userId) : undefined;+// Backward compatibility: a bare string / null second argument is treated// as the legacy `containerId` (sessionId or groupId).const scopeOptions: TopicKeywordScope =@@ -251,6 +256,7 @@ export const queryByKeyword = async (ctx.ownership(),ctx.notShareVisitor(),scopeCondition,+ onlyMineCondition,topicCandidateIds? inJsonStringArray(topics.id, topicCandidateIds): sql`${topics.title} @@@ ${bm25Query}`,@@ -272,6 +278,7 @@ export const queryByKeyword = async (ctx.ownership(),ctx.notShareVisitor(),scopeCondition,+ onlyMineCondition,),).groupBy(messages.topicId),diff --git a/packages/database/src/models/topic/list.ts b/packages/database/src/models/topic/list.tsindex 7e71079c75f..1a70d7da161 100644--- a/packages/database/src/models/topic/list.ts+++ b/packages/database/src/models/topic/list.ts@@ -76,6 +76,7 @@ export const query = async (groupId,isInbox,legacySessionId,+ onlyMine,sortBy,timing,triggers,@@ -185,6 +186,9 @@ export const query = async (excludeStatuses && excludeStatuses.length > 0? or(isNull(topics.status), not(inArray(topics.status, excludeStatuses as ChatTopicStatus[]))): undefined;+ // In a workspace `ownership()` matches every member's rows; this narrows the+ // list to the caller's own topics.+ const onlyMineCondition = onlyMine ? eq(topics.userId, ctx.userId) : undefined;// Topics created before the marker existed carry neither key and therefore// match no target — they cannot: what they configured was never recorded// anywhere in the row. `topics_agent_id_idx` still drives the scan, so the@@ -203,6 +207,7 @@ export const query = async (excludeTriggerCondition,triggerCondition,excludeStatusCondition,+ onlyMineCondition,);const [items, totalResult] = await Promise.all([@@ -290,6 +295,7 @@ export const query = async (excludeTriggerCondition,triggerCondition,excludeStatusCondition,+ onlyMineCondition,);const [items, totalResult] = await Promise.all([@@ -364,6 +370,7 @@ export const query = async (excludeTriggerCondition,triggerCondition,excludeStatusCondition,+ onlyMineCondition,);const [items, totalResult] = await Promise.all([diff --git a/packages/database/src/models/topic/types.ts b/packages/database/src/models/topic/types.tsindex 92c4b753a38..cd56e0ce4e8 100644--- a/packages/database/src/models/topic/types.ts+++ b/packages/database/src/models/topic/types.ts@@ -163,6 +163,11 @@ export interface QueryTopicParams {isInbox?: boolean;/** Include unassigned legacy topics only after the caller resolves this Session to the Agent. */legacySessionId?: string | null;+ /**+ * Only topics the caller created (`topics.userId`). Meaningful in a+ * workspace, where the list otherwise shows every member's topics.+ */+ onlyMine?: boolean;pageSize?: number;/*** Server-side ordering. Defaults to `updatedAt`. `status` orders by statusdiff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.tsindex 25c4426e088..9929e27d494 100644--- a/packages/locales/src/default/topic.ts+++ b/packages/locales/src/default/topic.ts@@ -120,6 +120,7 @@ export default {'filter.groupMode.byTime': 'By time','filter.groupMode.flat': 'Flat','filter.noDevice': 'No device',+ 'filter.onlyMine': 'Only my topics','filter.organize': 'Organize','filter.showCompleted': 'Include Archived','filter.sort': 'Sort by',diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex f1fcac1305b..1bba6204407 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -123,6 +123,7 @@ export interface SendMessageServerParams {excludeStatuses?: string[];excludeTriggers?: string[];includeTriggers?: string[];+ onlyMine?: boolean;};// if there is activeTopicId, then add topicId to messagetopicId?: string;@@ -213,6 +214,7 @@ export const AiSendMessageServerSchema = z.object({excludeStatuses: z.array(z.string()).optional(),excludeTriggers: z.array(z.string()).optional(),includeTriggers: z.array(z.string()).optional(),+ onlyMine: z.boolean().optional(),}).optional(),topicPageSize: z.number().int().min(1).max(100).optional(),diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 7a4e896116d..5a327bed971 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -838,6 +838,11 @@ export interface QueryTopicParams {* When true, also includes legacy inbox topics (sessionId IS NULL AND groupId IS NULL AND agentId IS NULL)*/isInbox?: boolean;+ /**+ * Only topics the caller created (`topics.userId`). Meaningful in a+ * workspace, where the list otherwise shows every member's topics.+ */+ onlyMine?: boolean;pageSize?: number;/*** Server-side ordering. Defaults to `updatedAt`. Use `status` to back thediff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 2a0dc649833..f0d9f2699f3 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -120,6 +120,11 @@ export interface WorkspaceUserPreference {* ignored; nothing reads or writes this map.*/sidebarPinnedOverrides?: Record<string /* itemId */, boolean>;+ /**+ * Topic sidebars list only the topics this member created, hiding the other+ * members' topics under the same agent / group.+ */+ topicOnlyMine?: boolean;}export interface LobeUser {diff --git a/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx b/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsxindex 39634c24bda..f2ef24d0d00 100644--- a/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx+++ b/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx@@ -9,6 +9,7 @@ import { VList } from 'virtua';import AsyncError from '@/components/AsyncError';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import TopicEmpty from '@/features/TopicEmpty';+import { useSidebarTopicSearch } from '@/hooks/useSidebarTopicSearch';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';@@ -26,23 +27,15 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {const fetchedCountRef = useRef(-1);const initializedRef = useRef(false);- const [- hasMore,- isLoadingMore,- loadMoreError,- isExpandingPageSize,- loadMoreTopics,- activeAgentId,- useSearchTopics,- ] = useChatStore((s) => [- topicSelectors.hasMoreTopics(s),- topicSelectors.isLoadingMoreTopics(s),- topicSelectors.loadMoreTopicsError(s),- topicSelectors.isExpandingPageSize(s),- s.loadMoreTopics,- s.activeAgentId,- s.useSearchTopics,- ]);+ const [hasMore, isLoadingMore, loadMoreError, isExpandingPageSize, loadMoreTopics] = useChatStore(+ (s) => [+ topicSelectors.hasMoreTopics(s),+ topicSelectors.isLoadingMoreTopics(s),+ topicSelectors.loadMoreTopicsError(s),+ topicSelectors.isExpandingPageSize(s),+ s.loadMoreTopics,+ ],+ );// Use server-side search if there's a keywordconst trimmedKeyword = searchKeyword.trim();@@ -59,10 +52,7 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {}, [isSearching]);// Only search when there's a keyword (pass undefined to disable SWR)- useSearchTopics(isSearching ? trimmedKeyword : undefined, {- agentId: activeAgentId,- groupId: undefined,- });+ useSidebarTopicSearch(isSearching ? trimmedKeyword : undefined);const searchResults = useChatStore(topicSelectors.searchTopics, isEqual);const allTopicList = useChatStore(topicSelectors.displayTopics, isEqual);diff --git a/src/features/AgentSidebar/Topic/List/index.test.tsx b/src/features/AgentSidebar/Topic/List/index.test.tsxindex 7f2fabb95fd..b536d661a48 100644--- a/src/features/AgentSidebar/Topic/List/index.test.tsx+++ b/src/features/AgentSidebar/Topic/List/index.test.tsx@@ -122,6 +122,7 @@ vi.mock('@/store/user/selectors', () => ({topicSortBy: (state: { topicSortBy: string }) => state.topicSortBy,},userProfileSelectors: { userId: () => 'test-user-id' },+ workspaceUserSettingsSelectors: { topicOnlyMine: () => () => false },}));vi.mock('../AllTopicsDrawer', () => ({diff --git a/src/features/AgentSidebar/Topic/TopicSearchBar/index.tsx b/src/features/AgentSidebar/Topic/TopicSearchBar/index.tsxindex 5f6ab98e11f..c56fd3e8986 100644--- a/src/features/AgentSidebar/Topic/TopicSearchBar/index.tsx+++ b/src/features/AgentSidebar/Topic/TopicSearchBar/index.tsx@@ -5,6 +5,7 @@ import { useUnmount } from 'ahooks';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useSidebarTopicSearch } from '@/hooks/useSidebarTopicSearch';import { useChatStore } from '@/store/chat';import { useServerConfigStore } from '@/store/serverConfig';@@ -14,12 +15,8 @@ const TopicSearchBar = memo<{ onClear?: () => void }>(({ onClear }) => {const [tempValue, setTempValue] = useState('');const [searchKeyword, setSearchKeywords] = useState('');const mobile = useServerConfigStore((s) => s.isMobile);- const [activeAgentId, useSearchTopics] = useChatStore((s) => [- s.activeAgentId,- s.useSearchTopics,- ]);- useSearchTopics(searchKeyword, { agentId: activeAgentId });+ useSidebarTopicSearch(searchKeyword);useUnmount(() => {useChatStore.setState({ inSearchingMode: false, isSearchingTopic: false });diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsxindex 50a2c867324..04c42b10fc8 100644--- a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx+++ b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx@@ -14,6 +14,15 @@ const preferenceMock = vi.hoisted(() => ({updatePreference: vi.fn(),}));const updateAgentModeMock = vi.hoisted(() => vi.fn());+const workspaceMock = vi.hoisted(() => ({+ hasActiveWorkspace: false,+ topicOnlyMine: false,+ updateWorkspaceUserPreference: vi.fn(),+}));++vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({+ useHasActiveWorkspace: () => workspaceMock.hasActiveWorkspace,+}));vi.mock('./TopicListScope', () => ({useTopicListScope: () => scopeMock.scope,@@ -40,6 +49,7 @@ vi.mock('@/store/user', () => ({useUserStore: (selector: (state: unknown) => unknown) =>selector({updatePreference: preferenceMock.updatePreference,+ updateWorkspaceUserPreference: workspaceMock.updateWorkspaceUserPreference,}),}));@@ -48,6 +58,9 @@ vi.mock('@/store/user/selectors', () => ({topicSortBy: () => preferenceMock.topicSortBy,topicIncludeCompleted: () => preferenceMock.topicIncludeCompleted,},+ workspaceUserSettingsSelectors: {+ topicOnlyMine: () => () => workspaceMock.topicOnlyMine,+ },}));const organizeLabels = (items: any[]): string[] => {@@ -55,6 +68,8 @@ const organizeLabels = (items: any[]): string[] => {return organize.children.map((child: any) => child.label);};+const filterGroup = (items: any[]) => items.find((item) => item.key === 'filter');+describe('useTopicFilterDropdownMenu group modes', () => {beforeEach(() => {scopeMock.scope = null;@@ -109,3 +124,35 @@ describe('useTopicFilterDropdownMenu group modes', () => {expect(filter.children.map((child: any) => child.key)).toEqual(['showCompleted']);});});++describe('useTopicFilterDropdownMenu only-mine filter', () => {+ beforeEach(() => {+ scopeMock.scope = null;+ workspaceMock.hasActiveWorkspace = false;+ workspaceMock.topicOnlyMine = false;+ vi.clearAllMocks();+ });++ /** @example Every personal topic is the caller's, so the filter would do nothing there. */+ it('hides the only-mine filter outside a workspace', () => {+ const { result } = renderHook(() => useTopicFilterDropdownMenu());++ const keys = filterGroup(result.current()).children.map((child: any) => child.key);+ expect(keys).toEqual(['showCompleted']);+ });++ it('toggles the per-workspace only-mine preference inside a workspace', () => {+ workspaceMock.hasActiveWorkspace = true;++ const { result } = renderHook(() => useTopicFilterDropdownMenu());+ const item = filterGroup(result.current()).children.find(+ (child: any) => child.key === 'onlyMine',+ );++ expect(item.label).toBe('filter.onlyMine');+ item.onClick();+ expect(workspaceMock.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ topicOnlyMine: true,+ });+ });+});diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.tsxindex 0ba23f507dd..46a0d865425 100644--- a/src/features/AgentSidebar/Topic/useFilterMenu.tsx+++ b/src/features/AgentSidebar/Topic/useFilterMenu.tsx@@ -10,6 +10,7 @@ import type { TopicGroupMode, TopicSortBy } from '@/types/topic';import { useAgentTopicGroupMode } from './hooks/useAgentTopicGroupMode';import { useTopicListScope } from './TopicListScope';+import { useOnlyMineFilterItem } from './useOnlyMineFilterItem';import { useProjectTopicFilterItems } from './useProjectTopicFilterItems';export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {@@ -17,6 +18,7 @@ export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {const { topicGroupMode, updateTopicGroupMode } = useAgentTopicGroupMode();const scope = useTopicListScope();const projectFilterItems = useProjectTopicFilterItems();+ const onlyMineItem = useOnlyMineFilterItem();const [topicSortBy, topicIncludeCompleted, updatePreference] = useUserStore((s) => [preferenceSelectors.topicSortBy(s),@@ -75,6 +77,7 @@ export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {updatePreference({ topicIncludeCompleted: !topicIncludeCompleted });},},+ ...(onlyMineItem ? [onlyMineItem] : []),],key: 'filter',label: t('filter.filter'),@@ -85,6 +88,7 @@ export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {topicGroupMode,topicSortBy,topicIncludeCompleted,+ onlyMineItem,updatePreference,updateTopicGroupMode,projectFilterItems,diff --git a/src/features/AgentSidebar/Topic/useOnlyMineFilterItem.tsx b/src/features/AgentSidebar/Topic/useOnlyMineFilterItem.tsxnew file mode 100644index 00000000000..45d1993be3f--- /dev/null+++ b/src/features/AgentSidebar/Topic/useOnlyMineFilterItem.tsx@@ -0,0 +1,34 @@+import type { DropdownItem } from '@lobehub/ui';+import { Icon } from '@lobehub/ui';+import { LucideCheck } from 'lucide-react';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';+import { useTopicOnlyMine } from '@/hooks/useTopicOnlyMine';+import { useUserStore } from '@/store/user';++/**+ * "Only my topics" toggle for the topic filter menus. A workspace lists every+ * member's topics under a shared agent, so the toggle exists only there and is+ * stored per member per workspace. Returns `null` in personal mode.+ */+export const useOnlyMineFilterItem = (): DropdownItem | null => {+ const { t } = useTranslation('topic');+ const hasActiveWorkspace = useHasActiveWorkspace();+ const onlyMine = useTopicOnlyMine();+ const updateWorkspaceUserPreference = useUserStore((s) => s.updateWorkspaceUserPreference);++ return useMemo(() => {+ if (!hasActiveWorkspace) return null;++ return {+ icon: onlyMine ? <Icon icon={LucideCheck} /> : <div />,+ key: 'onlyMine',+ label: t('filter.onlyMine'),+ onClick: () => {+ void updateWorkspaceUserPreference({ topicOnlyMine: !onlyMine });+ },+ };+ }, [hasActiveWorkspace, onlyMine, updateWorkspaceUserPreference, t]);+};diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts b/src/features/AgentSidebar/Topic/useScopedTopics.test.tsindex 44f59d7f134..d7d0b33cc95 100644--- a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts+++ b/src/features/AgentSidebar/Topic/useScopedTopics.test.ts@@ -8,13 +8,15 @@ import {TopicListRevealContext,TopicListScopeContext,} from './TopicListScope';-import { pinCoordinatorGroup, useScopedSidebarTopics } from './useScopedTopics';+import { pinCoordinatorGroup, useOnlyMineTopics, useScopedSidebarTopics } from './useScopedTopics';const fixture = vi.hoisted(() => ({ topicId: undefined as string | undefined }));+const userFixture = vi.hoisted(() => ({ topicOnlyMine: false, userId: 'me' }));const updateSystemStatus = vi.hoisted(() => vi.fn());const rows = [{id: 'old',+ userId: 'me',title: 'Old',agentId: 'agent-a',createdAt: 10,@@ -25,6 +27,7 @@ const rows = [},{id: 'new',+ userId: 'teammate',title: 'New',agentId: 'agent-b',createdAt: 30,@@ -34,6 +37,7 @@ const rows = [},{id: 'star',+ userId: 'me',title: 'Favorite',agentId: 'agent-a',createdAt: 5,@@ -43,6 +47,7 @@ const rows = [},{id: 'done',+ userId: 'teammate',title: 'Completed',agentId: 'agent-b',createdAt: 50,@@ -62,6 +67,15 @@ vi.mock('@/store/chat', () => ({ useChatStore: () => new Set<string>() }));vi.mock('@/store/global', () => ({useGlobalStore: (selector: (s: unknown) => unknown) => selector({ updateSystemStatus }),}));+vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: typeof userFixture) => unknown) => selector(userFixture),+}));+vi.mock('@/store/user/selectors', () => ({+ userProfileSelectors: { userId: (s: typeof userFixture) => s.userId },+ workspaceUserSettingsSelectors: {+ topicOnlyMine: () => (s: typeof userFixture) => s.topicOnlyMine,+ },+}));vi.mock('i18next', () => ({ t: (key: string) => key }));const RevealHost = ({ children }: PropsWithChildren) => {@@ -82,8 +96,22 @@ const wrapper = ({ children }: PropsWithChildren) =>describe('Project topics use the canonical Agent sidebar rules', () => {beforeEach(() => {fixture.topicId = undefined;+ userFixture.topicOnlyMine = false;updateSystemStatus.mockClear();});+ it('lists only the caller topics with the workspace only-mine filter, keeping the open one', () => {+ userFixture.topicOnlyMine = true;+ const { result, rerender } = renderHook(+ () => useScopedSidebarTopics(20, 'updatedAt', 'flat', false),+ { wrapper },+ );+ expect(result.current.topics.map((topic) => topic.id)).toEqual(['star', 'old']);+ expect(result.current.hasMore).toBe(false);++ fixture.topicId = 'new';+ rerender();+ expect(result.current.topics.map((topic) => topic.id)).toEqual(['star', 'old', 'new']);+ });it('pins favorites and orders the rest by the selected timestamp across Agents', () => {const { result, rerender } = renderHook(({ sort }: { sort: 'createdAt' | 'updatedAt' }) =>@@ -238,3 +266,25 @@ describe('pinCoordinatorGroup', () => {expect(pinCoordinatorGroup(groups, undefined)).toBe(groups);});});++describe('useOnlyMineTopics', () => {+ beforeEach(() => {+ userFixture.topicOnlyMine = false;+ });++ /** @example A project holding only teammates' topics must show its empty state, not a blank list. */+ it('leaves nothing when every topic belongs to a teammate', () => {+ userFixture.topicOnlyMine = true;+ const teammates = rows.filter((topic) => topic.userId === 'teammate');++ const { result } = renderHook(() => useOnlyMineTopics(teammates));++ expect(result.current).toEqual([]);+ });++ it('keeps every topic when the filter is off', () => {+ const { result } = renderHook(() => useOnlyMineTopics(rows));++ expect(result.current).toHaveLength(rows.length);+ });+});diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.ts b/src/features/AgentSidebar/Topic/useScopedTopics.tsindex a8310888300..1289ad47c63 100644--- a/src/features/AgentSidebar/Topic/useScopedTopics.ts+++ b/src/features/AgentSidebar/Topic/useScopedTopics.ts@@ -2,6 +2,7 @@ import { useMemo } from 'react';import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';+import { useTopicOnlyMine } from '@/hooks/useTopicOnlyMine';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';import { groupSidebarTopics, selectSidebarTopics } from '@/store/chat/slices/topic/selectors';@@ -10,6 +11,8 @@ import {useProjectDirectoryStore,useProjectTopics,} from '@/store/projectWorkingDirectory';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';import type { ChatTopic, GroupedTopic, TopicGroupMode, TopicSortBy } from '@/types/topic';import { filterTopics } from '@/utils/client/topic';@@ -49,6 +52,19 @@ export const pinCoordinatorGroup = (groups: GroupedTopic[], coordinatorAgentId?:export const useScopedTopic = (id?: string) =>useScopedTopics().topics?.find((topic) => topic.id === id);+/**+ * Project topics arrive in full, so the workspace "only mine" filter applies on+ * the client: keep only the caller's rows when it is on.+ */+export const useOnlyMineTopics = <T extends { userId?: string | null }>(topics: T[]): T[] => {+ const onlyMine = useTopicOnlyMine();+ const userId = useUserStore(userProfileSelectors.userId);+ return useMemo(+ () => (onlyMine ? topics.filter((topic) => topic.userId === userId) : topics),+ [topics, onlyMine, userId],+ );+};+export const useScopedSidebarTopics = (pageSize: number,sortBy: TopicSortBy,@@ -65,20 +81,28 @@ export const useScopedSidebarTopics = (const directories = useProjectDirectories(scope?.projectId);const filter = useTopicListFilter()?.filter;const filtering = !!(filter?.status || filter?.device);+ const sidebarTopics = useMemo(+ () =>+ (topics ?? []).filter(+ (topic: ChatTopic) =>+ !topic.trigger || !MAIN_SIDEBAR_EXCLUDE_TRIGGERS.includes(topic.trigger),+ ),+ [topics],+ );+ const listed = useOnlyMineTopics(sidebarTopics);// The status / device filter is an explicit ask, so it narrows the list- // strictly — unlike the archived toggle, which keeps the open topic in view.- const candidates = useMemo(() => {- const list: ChatTopic[] = (topics ?? []).filter(- (topic) => !topic.trigger || !MAIN_SIDEBAR_EXCLUDE_TRIGGERS.includes(topic.trigger),- );- return {- active: filtering ? undefined : list.find((topic) => topic.id === topicId),+ // strictly — unlike "only mine" and the archived toggle, which keep the open+ // topic in view.+ const candidates = useMemo(+ () => ({+ active: filtering ? undefined : sidebarTopics.find((topic) => topic.id === topicId),filtered:filter && filtering- ? filterTopics(list, filter, { directories, loadingTopicIds: running })- : list,- };- }, [topics, topicId, filter, filtering, directories, running]);+ ? filterTopics(listed, filter, { directories, loadingTopicIds: running })+ : listed,+ }),+ [sidebarTopics, listed, topicId, filter, filtering, directories, running],+ );const visible = useMemo(() =>selectSidebarTopics(diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsxindex 0816b8b25b4..f81c2c37fa1 100644--- a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx@@ -18,8 +18,9 @@ import {TopicListScopeContext,useTopicListFilter,} from '@/features/AgentSidebar/Topic/TopicListScope';-import { useScopedTopics } from '@/features/AgentSidebar/Topic/useScopedTopics';+import { useOnlyMineTopics, useScopedTopics } from '@/features/AgentSidebar/Topic/useScopedTopics';import SkeletonList from '@/features/NavPanel/components/SkeletonList';+import { useWorkspacePreferenceReady } from '@/hooks/useWorkspacePreferenceReady';import {useProjectDirectories,useProjectDirectoryStore,@@ -62,7 +63,8 @@ function ProjectTopicList({const filterState = useTopicListFilter();const request = useProjectDirectoryStore((s) => s.useFetchProjectTopics)(projectId);const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);- const topics = useProjectTopics(projectId);+ // The empty state must follow what the list shows, "only mine" included.+ const topics = useOnlyMineTopics(useProjectTopics(projectId));const directories = useProjectDirectories(projectId);const { topics: scopedTopics } = useScopedTopics();const filter = filterState?.filter;@@ -73,6 +75,10 @@ function ProjectTopicList({filterTopics(scopedTopics, filter, { directories }).length === 0,[filter, scopedTopics, directories],);+ // The rows are filtered client-side by the workspace "only mine" choice, and+ // nothing else on a project route syncs that preference. Hold the list until+ // it is known so the unfiltered rows never paint.+ const isPreferenceLoading = !useWorkspacePreferenceReady();return (<Flexbox gap={1} paddingBlock={12}><Flexbox horizontal align="center" justify="space-between" paddingInline={8}>@@ -105,7 +111,7 @@ function ProjectTopicList({onRetry={() => Promise.all([request.revalidate(), directoriesRequest.revalidate()])}/>) : null}- {!request.hasData ? (+ {!request.hasData || isPreferenceLoading ? (<SkeletonList />) : !topics.length && !request.error ? (<Text style={{ paddingInline: 8 }} type="secondary">@@ -119,7 +125,7 @@ function ProjectTopicList({</Button></Flexbox>) : null}- {topicGroupMode === 'flat' ? (+ {isPreferenceLoading ? null : topicGroupMode === 'flat' ? (<FlatMode />) : topicGroupMode === 'byStatus' ? (<ByStatusMode />diff --git a/src/hooks/chatTopicListQuery.test.ts b/src/hooks/chatTopicListQuery.test.tsindex 6c48ba04b87..b0282004a40 100644--- a/src/hooks/chatTopicListQuery.test.ts+++ b/src/hooks/chatTopicListQuery.test.ts@@ -13,6 +13,7 @@ const globalStateMock = vi.hoisted(() => ({ topicPageSize: 20 }));const userStateMock = vi.hoisted(() => ({topicGroupMode: 'byTime' as string,topicIncludeCompleted: false,+ topicOnlyMine: false,}));vi.mock('@/store/agent', () => ({ useAgentStore: { getState: () => agentStateMock } }));@@ -40,6 +41,9 @@ vi.mock('@/store/user/selectors', () => ({topicGroupMode: (s: typeof userStateMock) => s.topicGroupMode,topicIncludeCompleted: (s: typeof userStateMock) => s.topicIncludeCompleted,},+ workspaceUserSettingsSelectors: {+ topicOnlyMine: () => (s: typeof userStateMock) => s.topicOnlyMine,+ },}));describe('deriveSidebarTopicListQuery', () => {@@ -48,6 +52,7 @@ describe('deriveSidebarTopicListQuery', () => {deriveSidebarTopicListQuery({includeCompleted: false,isGroupSession: false,+ onlyMine: false,topicGroupMode: 'byTime',}),).toEqual({@@ -62,6 +67,7 @@ describe('deriveSidebarTopicListQuery', () => {deriveSidebarTopicListQuery({includeCompleted: true,isGroupSession: false,+ onlyMine: false,topicGroupMode: 'byTime',}).excludeStatuses,).toBeUndefined();@@ -72,6 +78,7 @@ describe('deriveSidebarTopicListQuery', () => {deriveSidebarTopicListQuery({includeCompleted: false,isGroupSession: false,+ onlyMine: false,topicGroupMode: 'byStatus',}).sortBy,).toBe('status');@@ -80,10 +87,31 @@ describe('deriveSidebarTopicListQuery', () => {deriveSidebarTopicListQuery({includeCompleted: false,isGroupSession: true,+ onlyMine: false,topicGroupMode: 'byStatus',}).sortBy,).toBeUndefined();});++ it('asks the server for only the caller topics when the workspace filter is on', () => {+ expect(+ deriveSidebarTopicListQuery({+ includeCompleted: false,+ isGroupSession: false,+ onlyMine: true,+ topicGroupMode: 'byTime',+ }).onlyMine,+ ).toBe(true);++ expect(+ deriveSidebarTopicListQuery({+ includeCompleted: false,+ isGroupSession: false,+ onlyMine: false,+ topicGroupMode: 'byTime',+ }).onlyMine,+ ).toBeUndefined();+ });});describe('getSidebarTopicListParams', () => {@@ -93,6 +121,7 @@ describe('getSidebarTopicListParams', () => {globalStateMock.topicPageSize = 20;userStateMock.topicGroupMode = 'byTime';userStateMock.topicIncludeCompleted = false;+ userStateMock.topicOnlyMine = false;});it('returns nothing without a session', () => {@@ -125,6 +154,12 @@ describe('getSidebarTopicListParams', () => {expect(getSidebarTopicListParams({ agentId: 'agent-7' })?.sortBy).toBe('status');});+ it('carries the workspace only-mine filter into the pre-paint request', () => {+ userStateMock.topicOnlyMine = true;++ expect(getSidebarTopicListParams({ agentId: 'agent-7' })?.onlyMine).toBe(true);+ });+it('never flags a group session as inbox and keeps its default ordering', () => {userStateMock.topicGroupMode = 'byStatus';diff --git a/src/hooks/chatTopicListQuery.ts b/src/hooks/chatTopicListQuery.tsindex a4ac5f4cc55..0e7a69c55aa 100644--- a/src/hooks/chatTopicListQuery.ts+++ b/src/hooks/chatTopicListQuery.ts@@ -1,5 +1,6 @@import type { TopicQuerySortBy } from '@lobechat/types';+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';import { resolveAgentTopicGroupMode } from '@/features/AgentSidebar/Topic/utils/topicGroupMode';import { useAgentStore } from '@/store/agent';@@ -11,7 +12,7 @@ import {import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useUserStore } from '@/store/user';-import { preferenceSelectors } from '@/store/user/selectors';+import { preferenceSelectors, workspaceUserSettingsSelectors } from '@/store/user/selectors';import type { TopicGroupMode } from '@/types/topic';const EXCLUDE_STATUSES_COMPLETED = ['completed'];@@ -23,6 +24,7 @@ const EXCLUDE_STATUSES_COMPLETED = ['completed'];export interface SidebarTopicListQuery {excludeStatuses?: string[];excludeTriggers?: string[];+ onlyMine?: boolean;sortBy?: TopicQuerySortBy;}@@ -40,14 +42,17 @@ export interface SidebarTopicListQuery {export const deriveSidebarTopicListQuery = ({includeCompleted,isGroupSession,+ onlyMine,topicGroupMode,}: {includeCompleted: boolean;isGroupSession: boolean;+ onlyMine: boolean;topicGroupMode: TopicGroupMode;}): SidebarTopicListQuery => ({excludeStatuses: includeCompleted ? undefined : EXCLUDE_STATUSES_COMPLETED,excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,+ onlyMine: onlyMine || undefined,sortBy: !isGroupSession && topicGroupMode === 'byStatus' ? 'status' : undefined,});@@ -84,11 +89,13 @@ export const getSidebarTopicListParams = (session: {const agentState = useAgentStore.getState();const inboxAgentId = builtinAgentSelectors.inboxAgentId(agentState);+ const userState = useUserStore.getState();return normalizeTopicListParams({...deriveSidebarTopicListQuery({- includeCompleted: preferenceSelectors.topicIncludeCompleted(useUserStore.getState()),+ includeCompleted: preferenceSelectors.topicIncludeCompleted(userState),isGroupSession: !!groupId,+ onlyMine: workspaceUserSettingsSelectors.topicOnlyMine(getActiveWorkspaceId())(userState),topicGroupMode: getTopicGroupModeForAgent(agentId),}),agentId,diff --git a/src/hooks/useFetchChatTopics.test.ts b/src/hooks/useFetchChatTopics.test.tsindex 268eda961f5..df0569fb6a5 100644--- a/src/hooks/useFetchChatTopics.test.ts+++ b/src/hooks/useFetchChatTopics.test.ts@@ -15,7 +15,9 @@ const mocks = vi.hoisted(() => ({),topicGroupMode: 'byStatus' as string,topicIncludeCompleted: false,+ topicOnlyMine: false,topicPageSize: 20,+ workspacePreferenceLoading: false,}));vi.mock('@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode', () => ({@@ -52,16 +54,22 @@ vi.mock('@/store/global/selectors', () => ({}));vi.mock('@/store/user', () => ({- useUserStore: (selector: (state: unknown) => unknown) => selector({}),+ useUserStore: (selector: (state: unknown) => unknown) =>+ selector({+ useFetchWorkspaceUserPreference: () => ({ isLoading: mocks.workspacePreferenceLoading }),+ }),}));vi.mock('@/store/user/selectors', () => ({preferenceSelectors: { topicIncludeCompleted: () => mocks.topicIncludeCompleted },+ workspaceUserSettingsSelectors: { topicOnlyMine: () => () => mocks.topicOnlyMine },}));describe('chat topic list fetches', () => {beforeEach(() => {mocks.storeFetchTopics.mockClear();+ mocks.topicOnlyMine = false;+ mocks.workspacePreferenceLoading = false;});it('asks the same query for a named agent as the sidebar does for the active one', () => {@@ -90,6 +98,33 @@ describe('chat topic list fetches', () => {expect(panelArgs.excludeTriggers).toEqual(MAIN_SIDEBAR_EXCLUDE_TRIGGERS);});+ it('forwards the workspace only-mine filter from both the sidebar and the panel', () => {+ mocks.topicOnlyMine = true;++ renderHook(() => useFetchChatTopics());+ const [, sidebarArgs = {}] = mocks.storeFetchTopics.mock.calls.at(-1)!;++ renderHook(() => useFetchAgentChatTopics('agent-1'));+ const [, panelArgs = {}] = mocks.storeFetchTopics.mock.calls.at(-1)!;++ expect(sidebarArgs.onlyMine).toBe(true);+ expect(panelArgs.onlyMine).toBe(true);+ });++ /** @example A cold workspace load must not paint the unfiltered list before "only mine" is known. */+ it('holds both fetches until the workspace preference has loaded', () => {+ mocks.workspacePreferenceLoading = true;++ renderHook(() => useFetchChatTopics());+ const [sidebarEnabled] = mocks.storeFetchTopics.mock.calls.at(-1)!;++ renderHook(() => useFetchAgentChatTopics('agent-1'));+ const [panelEnabled] = mocks.storeFetchTopics.mock.calls.at(-1)!;++ expect(sidebarEnabled).toBe(false);+ expect(panelEnabled).toBe(false);+ });+it('stays disabled until the panel knows its agent', () => {renderHook(() => useFetchAgentChatTopics(undefined));diff --git a/src/hooks/useFetchChatTopics.ts b/src/hooks/useFetchChatTopics.tsindex 3b8ed740297..d6c433c1cb4 100644--- a/src/hooks/useFetchChatTopics.ts+++ b/src/hooks/useFetchChatTopics.ts@@ -4,6 +4,8 @@ import {type SidebarTopicListQuery,} from '@/hooks/chatTopicListQuery';import { useFetchTopics } from '@/hooks/useFetchTopics';+import { useTopicOnlyMine } from '@/hooks/useTopicOnlyMine';+import { useWorkspacePreferenceReady } from '@/hooks/useWorkspacePreferenceReady';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -23,16 +25,26 @@ import { preferenceSelectors } from '@/store/user/selectors';* pre-paint hydrate reads imperatively: same inputs means the same SWR key and* the same persisted row, so SWR dedupes and the hydrate actually applies.*/-const useChatTopicListQuery = (): SidebarTopicListQuery => {+const useChatTopicListQuery = (): { query: SidebarTopicListQuery; ready: boolean } => {const includeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);+ const onlyMine = useTopicOnlyMine();+ // The workspace "only mine" filter is part of the list identity. On a cold+ // load the workspace resolves after the route loader, so hold the fetch until+ // this member's preference is known (local copy or network, success or+ // failure) — otherwise the unfiltered list paints first.+ const ready = useWorkspacePreferenceReady();const activeGroupId = useChatStore((s) => s.activeGroupId);const { topicGroupMode } = useAgentTopicGroupMode();- return deriveSidebarTopicListQuery({- includeCompleted,- isGroupSession: !!activeGroupId,- topicGroupMode,- });+ return {+ query: deriveSidebarTopicListQuery({+ includeCompleted,+ isGroupSession: !!activeGroupId,+ onlyMine,+ topicGroupMode,+ }),+ ready,+ };};/**@@ -43,7 +55,10 @@ const useChatTopicListQuery = (): SidebarTopicListQuery => {* Extend {@link useChatTopicListQuery} when adding more preference-driven topic* params; don't spread them across individual components.*/-export const useFetchChatTopics = () => useFetchTopics(useChatTopicListQuery());+export const useFetchChatTopics = () => {+ const { query, ready } = useChatTopicListQuery();+ return useFetchTopics(query, ready);+};/*** Same canonical list, for the secondary conversation panels that carry their@@ -55,11 +70,11 @@ export const useFetchChatTopics = () => useFetchTopics(useChatTopicListQuery());* moment such a panel mounted next to it.*/export const useFetchAgentChatTopics = (agentId?: string) => {- const query = useChatTopicListQuery();+ const { query, ready } = useChatTopicListQuery();const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);const pageSize = useGlobalStore(systemStatusSelectors.topicPageSize);- return useChatStore((s) => s.useFetchTopics)(!!agentId, {+ return useChatStore((s) => s.useFetchTopics)(!!agentId && ready, {agentId,...query,isInbox: !!inboxAgentId && agentId === inboxAgentId,diff --git a/src/hooks/useFetchTopics.ts b/src/hooks/useFetchTopics.tsindex 5d6a8772d6e..6f9e937715c 100644--- a/src/hooks/useFetchTopics.ts+++ b/src/hooks/useFetchTopics.ts@@ -10,11 +10,15 @@ import { systemStatusSelectors } from '@/store/global/selectors';/*** Fetch topics for the current session (agent or group)*/-export const useFetchTopics = (options?: {- excludeStatuses?: string[];- excludeTriggers?: string[];- sortBy?: TopicQuerySortBy;-}) => {+export const useFetchTopics = (+ options?: {+ excludeStatuses?: string[];+ excludeTriggers?: string[];+ onlyMine?: boolean;+ sortBy?: TopicQuerySortBy;+ },+ enabled = true,+) => {const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);const [activeAgentId, activeGroupId, useFetchTopicsHook] = useChatStore((s) => [s.activeAgentId,@@ -28,7 +32,7 @@ export const useFetchTopics = (options?: {const hasTopicData = useChatStore((s) => !!s.topicDataMap[topicMapKey({ agentId: activeAgentId, groupId: activeGroupId })],);- const { isValidating } = useFetchTopicsHook(true, {+ const { isValidating } = useFetchTopicsHook(enabled, {agentId: activeAgentId,...(options?.excludeStatuses && options.excludeStatuses.length > 0? { excludeStatuses: options.excludeStatuses }@@ -38,6 +42,7 @@ export const useFetchTopics = (options?: {: {}),groupId: activeGroupId,isInbox: activeGroupId ? false : isInbox,+ ...(options?.onlyMine ? { onlyMine: true } : {}),pageSize: topicPageSize,...(options?.sortBy ? { sortBy: options.sortBy } : {}),});diff --git a/src/hooks/useSidebarTopicSearch.test.ts b/src/hooks/useSidebarTopicSearch.test.tsnew file mode 100644index 00000000000..09b43ad1432--- /dev/null+++ b/src/hooks/useSidebarTopicSearch.test.ts@@ -0,0 +1,44 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useSidebarTopicSearch } from './useSidebarTopicSearch';++const mocks = vi.hoisted(() => ({+ onlyMine: false,+ useSearchTopics: vi.fn(),+}));++vi.mock('@/hooks/useTopicOnlyMine', () => ({ useTopicOnlyMine: () => mocks.onlyMine }));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: unknown) => unknown) =>+ selector({ activeAgentId: 'agt_1', useSearchTopics: mocks.useSearchTopics }),+}));++describe('useSidebarTopicSearch', () => {+ beforeEach(() => {+ mocks.onlyMine = false;+ mocks.useSearchTopics.mockClear();+ });++ /** @example With "only mine" on, sidebar searches must not bring back teammates' topics. */+ it('searches the active agent with the workspace only-mine filter', () => {+ mocks.onlyMine = true;++ renderHook(() => useSidebarTopicSearch('release'));++ expect(mocks.useSearchTopics).toHaveBeenLastCalledWith('release', {+ agentId: 'agt_1',+ onlyMine: true,+ });+ });++ it('searches unfiltered when the filter is off', () => {+ renderHook(() => useSidebarTopicSearch('release'));++ expect(mocks.useSearchTopics).toHaveBeenLastCalledWith('release', {+ agentId: 'agt_1',+ onlyMine: false,+ });+ });+});diff --git a/src/hooks/useSidebarTopicSearch.ts b/src/hooks/useSidebarTopicSearch.tsnew file mode 100644index 00000000000..db082126b3b--- /dev/null+++ b/src/hooks/useSidebarTopicSearch.ts@@ -0,0 +1,18 @@+import { useTopicOnlyMine } from '@/hooks/useTopicOnlyMine';+import { useChatStore } from '@/store/chat';++/**+ * Server-side topic search for the active agent's sidebar surfaces (topic+ * drawers, mobile search). Applies the same workspace "only mine" filter as+ * the list, so a search never brings back topics the list is hiding. An empty+ * keyword disables the request.+ */+export const useSidebarTopicSearch = (keywords: string | undefined) => {+ const [activeAgentId, useSearchTopics] = useChatStore((s) => [+ s.activeAgentId,+ s.useSearchTopics,+ ]);+ const onlyMine = useTopicOnlyMine();++ return useSearchTopics(keywords, { agentId: activeAgentId, onlyMine });+};diff --git a/src/hooks/useTopicOnlyMine.ts b/src/hooks/useTopicOnlyMine.tsnew file mode 100644index 00000000000..896d1c7847c--- /dev/null+++ b/src/hooks/useTopicOnlyMine.ts@@ -0,0 +1,13 @@+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useUserStore } from '@/store/user';+import { workspaceUserSettingsSelectors } from '@/store/user/selectors';++/**+ * Whether topic lists and searches show only the caller's own topics — the+ * member's "only mine" choice for the active workspace. Always false in+ * personal mode.+ */+export const useTopicOnlyMine = (): boolean => {+ const activeWorkspaceId = useActiveWorkspaceId();+ return useUserStore(workspaceUserSettingsSelectors.topicOnlyMine(activeWorkspaceId));+};diff --git a/src/hooks/useWorkspacePreferenceReady.test.ts b/src/hooks/useWorkspacePreferenceReady.test.tsnew file mode 100644index 00000000000..a3bd1b7c0d9--- /dev/null+++ b/src/hooks/useWorkspacePreferenceReady.test.ts@@ -0,0 +1,40 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useWorkspacePreferenceReady } from './useWorkspacePreferenceReady';++const mocks = vi.hoisted(() => ({+ isLoading: false,+ useFetchWorkspaceUserPreference: vi.fn(),+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: unknown) => unknown) =>+ selector({ useFetchWorkspaceUserPreference: mocks.useFetchWorkspaceUserPreference }),+}));++describe('useWorkspacePreferenceReady', () => {+ beforeEach(() => {+ mocks.isLoading = false;+ mocks.useFetchWorkspaceUserPreference.mockReset();+ mocks.useFetchWorkspaceUserPreference.mockImplementation(() => ({+ isLoading: mocks.isLoading,+ }));+ });++ /** @example A cold project route has no other surface syncing the preference. */+ it('syncs the preference itself and is not ready while it loads', () => {+ mocks.isLoading = true;++ const { result } = renderHook(() => useWorkspacePreferenceReady());++ expect(mocks.useFetchWorkspaceUserPreference).toHaveBeenCalled();+ expect(result.current).toBe(false);+ });++ it('is ready once the preference is known', () => {+ const { result } = renderHook(() => useWorkspacePreferenceReady());++ expect(result.current).toBe(true);+ });+});diff --git a/src/hooks/useWorkspacePreferenceReady.ts b/src/hooks/useWorkspacePreferenceReady.tsnew file mode 100644index 00000000000..b3eb908865d--- /dev/null+++ b/src/hooks/useWorkspacePreferenceReady.ts@@ -0,0 +1,10 @@+import { useUserStore } from '@/store/user';++/**+ * Syncs the member's preference for the active workspace and reports whether+ * it is known yet (local copy or network, success or failure). Always true in+ * personal mode. Topic lists wait on it because the "only mine" filter lives+ * there — reading it early paints the unfiltered list first.+ */+export const useWorkspacePreferenceReady = (): boolean =>+ !useUserStore((s) => s.useFetchWorkspaceUserPreference)().isLoading;diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex bfc36d7dc90..38e7ebae466 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -128,12 +128,16 @@ export const topicKeys = {'topic:scheduledRunWatch',topicId,]),- search: def('topic:search', (keywords: string, agentId?: string, groupId?: string) => [+ search: def('topic:search',- keywords,- agentId,- groupId,- ]),+ (keywords: string, agentId?: string, groupId?: string, onlyMine?: boolean) => [+ 'topic:search',+ keywords,+ agentId,+ groupId,+ onlyMine,+ ],+ ),};// ---- acceptance comment -------------------------------------------------diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.tsindex 46d3bd43ecd..14e0ba27c0c 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts@@ -24,6 +24,8 @@ const preHydrateAgentSlugMock = vi.hoisted(() =>);const preHydrateDeviceListMock = vi.hoisted(() => vi.fn(async () => true));const preHydrateVerifyRunsMock = vi.hoisted(() => vi.fn(async (_ids: string[]) => {}));+const preHydrateWorkspacePreferenceMock = vi.hoisted(() => vi.fn(async () => true));+const chatState = vi.hoisted(() => ({ dbMessagesMap: {} as Record<string, unknown[]> }));vi.mock('@lobechat/builtin-agents', () => ({@@ -71,6 +73,12 @@ vi.mock('@/store/device', () => ({useDeviceStore: { getState: () => ({ preHydrateDeviceList: preHydrateDeviceListMock }) },}));+vi.mock('@/store/user', () => ({+ useUserStore: {+ getState: () => ({ preHydrateWorkspaceUserPreference: preHydrateWorkspacePreferenceMock }),+ },+}));+vi.mock('@/store/verify', () => ({useVerifyStore: { getState: () => ({ preHydrateVerifyRuns: preHydrateVerifyRunsMock }) },}));@@ -89,6 +97,51 @@ describe('agent chat topic list loader', () => {preHydrateDeviceListMock.mockResolvedValue(true);getSidebarTopicListParamsMock.mockReset();getSidebarTopicListParamsMock.mockReturnValue({ agentId: 'agt_1', pageSize: 20 });+ preHydrateWorkspacePreferenceMock.mockReset();+ preHydrateWorkspacePreferenceMock.mockResolvedValue(true);+ });++ /** @example "Only mine" set on another device: no local copy, so the cached page may be unfiltered. */+ it('skips the topic seed in a workspace whose preference is still unknown', async () => {+ preHydrateWorkspacePreferenceMock.mockResolvedValue(false);++ await agentChatTopicListLoader(loaderArgs('agt_1'));++ expect(preHydrateTopicListMock).not.toHaveBeenCalled();+ });++ it('seeds the topic page once the workspace preference is known', async () => {+ await agentChatTopicListLoader(loaderArgs('agt_1'));++ expect(preHydrateTopicListMock).toHaveBeenCalledWith({ agentId: 'agt_1', pageSize: 20 });+ });++ /** @example The "only mine" filter lives there; deriving params first seeds the unfiltered page. */+ it('reads the workspace preference before deriving the sidebar params', async () => {+ const order: string[] = [];+ preHydrateWorkspacePreferenceMock.mockImplementation(async () => {+ order.push('preference');+ return true;+ });+ getSidebarTopicListParamsMock.mockImplementation(() => {+ order.push('params');+ return { agentId: 'agt_1', pageSize: 20 };+ });++ await agentChatTopicListLoader(loaderArgs('agt_1'));++ expect(order).toEqual(['preference', 'params']);+ });++ it('does not let a stalled workspace preference read block the route', async () => {+ vi.useFakeTimers();+ preHydrateWorkspacePreferenceMock.mockImplementation(() => new Promise(() => {}));++ const settled = vi.fn();+ void agentChatTopicListLoader(loaderArgs('agt_1')).then(settled);++ await vi.advanceTimersByTimeAsync(PRE_PAINT_HYDRATE_TIMEOUT * 2);+ expect(settled).toHaveBeenCalled();});afterEach(() => {diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.tsindex 09ee688e36e..245173ccdc7 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts@@ -9,6 +9,7 @@ import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useDeviceStore } from '@/store/device';+import { useUserStore } from '@/store/user';import { useVerifyStore } from '@/store/verify';const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));@@ -39,6 +40,23 @@ export const preHydrateTopicListForRoute = async (routeAgentId?: string): Promisconst agentId = resolveRouteAgentId(routeAgentId);if (!agentId) return;+ // The workspace "only mine" filter is part of the list identity; read it+ // before deriving the params, or the seeded page is the unfiltered one.+ let preferenceKnown = false;+ await settleWithin(+ useUserStore+ .getState()+ .preHydrateWorkspaceUserPreference()+ .then((known) => {+ preferenceKnown = known;+ }),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );+ // Still unknown (no local copy yet, e.g. set on another device): any page+ // seeded now could be the unfiltered one, so leave the list to the mounted,+ // preference-gated fetch.+ if (!preferenceKnown) return;+const params = getSidebarTopicListParams({ agentId });if (!params) return;diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsxindex 6b8ae84108d..5f288b33acf 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx@@ -8,6 +8,7 @@ import { VList } from 'virtua';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import TopicEmpty from '@/features/TopicEmpty';+import { useSidebarTopicSearch } from '@/hooks/useSidebarTopicSearch';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';@@ -32,8 +33,6 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {isLoadingMore,isExpandingPageSize,loadMoreTopics,- activeAgentId,- useSearchTopics,] = useChatStore((s) => [s.activeTopicId,s.activeThreadId,@@ -41,8 +40,6 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {topicSelectors.isLoadingMoreTopics(s),topicSelectors.isExpandingPageSize(s),s.loadMoreTopics,- s.activeAgentId,- s.useSearchTopics,]);// Use server-side search if there's a keyword@@ -60,11 +57,7 @@ const Content = memo<ContentProps>(({ open, searchKeyword }) => {}, [isSearching]);// Only search when there's a keyword (pass undefined to disable SWR)- // Note: searchTopics uses sessionId in the service, but agentId in the hook- useSearchTopics(isSearching ? trimmedKeyword : undefined, {- agentId: activeAgentId,- groupId: undefined,- });+ useSidebarTopicSearch(isSearching ? trimmedKeyword : undefined);const searchResults = useChatStore(topicSelectors.searchTopics, isEqual);const allTopicList = useChatStore(topicSelectors.displayTopics, isEqual);diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useFilterMenu.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useFilterMenu.tsxindex 80b9e89a59f..571ff7901a4 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/useFilterMenu.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useFilterMenu.tsx@@ -4,12 +4,14 @@ import { LucideCheck } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { useOnlyMineFilterItem } from '@/features/AgentSidebar/Topic/useOnlyMineFilterItem';import { useUserStore } from '@/store/user';import { preferenceSelectors } from '@/store/user/selectors';import type { TopicGroupMode, TopicSortBy } from '@/types/topic';export const useTopicFilterDropdownMenu = (): DropdownItem[] => {const { t } = useTranslation('topic');+ const onlyMineItem = useOnlyMineFilterItem();const [topicGroupMode, topicSortBy, topicIncludeCompleted, updatePreference] = useUserStore((s) => [@@ -63,11 +65,12 @@ export const useTopicFilterDropdownMenu = (): DropdownItem[] => {updatePreference({ topicIncludeCompleted: !topicIncludeCompleted });},},+ ...(onlyMineItem ? [onlyMineItem] : []),],key: 'filter',label: t('filter.filter'),type: 'group' as const,},];- }, [topicGroupMode, topicSortBy, topicIncludeCompleted, updatePreference, t]);+ }, [topicGroupMode, topicSortBy, topicIncludeCompleted, onlyMineItem, updatePreference, t]);};diff --git a/src/routes/(mobile)/chat/features/Topic/features/TopicModal.tsx b/src/routes/(mobile)/chat/features/Topic/features/TopicModal.tsxindex 65cd34a19ce..76edb1808a4 100644--- a/src/routes/(mobile)/chat/features/Topic/features/TopicModal.tsx+++ b/src/routes/(mobile)/chat/features/Topic/features/TopicModal.tsx@@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next';import ImperativeModal from '@/components/ImperativeModal';import { OverlayContainerContext } from '@/features/NavPanel/OverlayContainer';-import { useFetchTopics } from '@/hooks/useFetchTopics';+import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';import { useWorkspaceModal } from '@/hooks/useWorkspaceModal';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -20,7 +20,9 @@ const Topics = memo(({ children }: PropsWithChildren) => {const { t } = useTranslation('topic');const [overlayContainer, setOverlayContainer] = useState<HTMLDivElement | null>(null);- useFetchTopics();+ // The same canonical query as the list inside: both write this container's+ // bucket, so a looser fetch landing last would bring back filtered-out topics.+ useFetchChatTopics();return (<OverlayContainerContext value={overlayContainer}>diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex 77d1dfec412..5493cbee44c 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -116,6 +116,7 @@ export class TopicService {groupId: params.groupId,includeTriggers: params.includeTriggers,isInbox: params.isInbox,+ onlyMine: params.onlyMine,pageSize: params.pageSize,sortBy: params.sortBy,triggers: params.triggers,@@ -168,11 +169,17 @@ export class TopicService {return result.data.hasFiles;};- searchTopics = (keywords: string, agentId?: string, groupId?: string): Promise<ChatTopic[]> => {+ searchTopics = (+ keywords: string,+ agentId?: string,+ groupId?: string,+ onlyMine?: boolean,+ ): Promise<ChatTopic[]> => {return lambdaClient.topic.searchTopics.query({agentId,groupId,keywords,+ onlyMine: onlyMine || undefined,}) as any;};diff --git a/src/services/topic/searchTopics.test.ts b/src/services/topic/searchTopics.test.tsnew file mode 100644index 00000000000..a6887beb8bb--- /dev/null+++ b/src/services/topic/searchTopics.test.ts@@ -0,0 +1,36 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';++import { TopicService } from './index';++vi.mock('@/libs/trpc/client', () => ({+ createWorkspaceLambdaClient: vi.fn(),+ lambdaClient: { topic: { searchTopics: { query: vi.fn(async () => []) } } },+}));++describe('TopicService.searchTopics', () => {+ beforeEach(() => {+ vi.mocked(lambdaClient.topic.searchTopics.query).mockClear();+ });++ /** @example A sidebar search with "only mine" on must not return teammates' topics. */+ it('forwards the workspace only-mine filter', async () => {+ await new TopicService().searchTopics('release', 'agt_1', undefined, true);++ expect(lambdaClient.topic.searchTopics.query).toHaveBeenCalledWith({+ agentId: 'agt_1',+ groupId: undefined,+ keywords: 'release',+ onlyMine: true,+ });+ });++ it('omits the filter when it is off', async () => {+ await new TopicService().searchTopics('release', 'agt_1');++ expect(lambdaClient.topic.searchTopics.query).toHaveBeenCalledWith(+ expect.objectContaining({ onlyMine: undefined }),+ );+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex afe9a359615..133c20c117e 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -97,6 +97,7 @@ import {import { isQueueBlockingOperation, snapshotQueuedFiles } from '@/store/chat/slices/operation/types';import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';+import { topicListFilterOf } from '@/store/chat/slices/topic/projection';import { resolveTopicHeteroPin } from '@/store/chat/slices/topic/selectors';import { type ChatStore } from '@/store/chat/store';import {@@ -234,29 +235,11 @@ export class ConversationLifecycleActionImpl {this.#get = get;}- /**- * Read the active topic-list filter from `topicDataMap` so it can be- * forwarded to `sendMessageInServer`. Without this, the server returns- * an unfiltered list which `internal_updateTopics` then writes back over- * the filtered sidebar — completed/cron topics reappear until the next- * SWR revalidation.- */- #getTopicFilter = (- agentId?: string,- groupId?: string,- ):- | { excludeStatuses?: string[]; excludeTriggers?: string[]; includeTriggers?: string[] }- | undefined => {- if (!agentId && !groupId) return undefined;- const data = this.#get().topicDataMap[topicMapKey({ agentId, groupId })];- if (!data) return undefined;- const { excludeStatuses, excludeTriggers } = data;- if (!excludeStatuses?.length && !excludeTriggers?.length) return undefined;- return {- ...(excludeStatuses?.length ? { excludeStatuses } : {}),- ...(excludeTriggers?.length ? { excludeTriggers } : {}),- };- };+ /** The active topic-list filter, forwarded to `sendMessageInServer` (see `topicListFilterOf`). */+ #getTopicFilter = (agentId?: string, groupId?: string) =>+ agentId || groupId+ ? topicListFilterOf(this.#get().topicDataMap[topicMapKey({ agentId, groupId })])+ : undefined;/*** Land a thread the server created for this send: record it on the operation,diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 242a8daaac4..87ba9180eba 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -30,6 +30,7 @@ import {type ReplicaPageResult,type ReplicaSyncResult,} from '@/libs/replica';+import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';import { mutate } from '@/libs/swr';import { cronKeys, topicKeys } from '@/libs/swr/keys';import { getCacheScope } from '@/libs/swr/useCacheScope';@@ -76,6 +77,7 @@ import {topicAgentViewResource,type TopicListParams,topicListResource,+ topicListViewFields,} from './projection';import { type ChatTopicDispatch } from './reducer';import { topicSelectors } from './selectors';@@ -243,13 +245,7 @@ export class ChatTopicActionImpl {stateKey: 'topicListReplica',toPersisted,view: recordLens<ChatStore, TopicData>('topicDataMap'),- viewFields: ({ excludeStatuses, excludeTriggers, isInbox, sortBy, withDetails }) => ({- excludeStatuses,- excludeTriggers,- isInbox: Boolean(isInbox),- sortBy,- withDetails,- }),+ viewFields: topicListViewFields,});this.#topicAgentView = createReplicaSlice(topicAgentViewResource, {actionPrefix: n('topicAgentView'),@@ -276,6 +272,7 @@ export class ChatTopicActionImpl {this.#topicAgentView,this.#topicDetail,]);+ subscribeCacheScope((scope) => this.#topicList.ensureScope(scope));}#resolveTopicLinkedPullRequestRefreshParams = (@@ -1387,9 +1384,8 @@ export class ChatTopicActionImpl {* projection, then revalidates; results land in `topicDataMap` — read them* through `topicSelectors`, never from this hook.*/- useFetchTopics = (enable: boolean, params: Partial<TopicListParams> = {}): ReplicaSyncResult => {- return this.#topicList.useSync(normalizeTopicListParams(params), { enabled: enable });- };+ useFetchTopics = (enable: boolean, params: Partial<TopicListParams> = {}): ReplicaSyncResult =>+ this.#topicList.useSync(normalizeTopicListParams(params), { enabled: enable });/*** Seed the sidebar's persisted page for a session before its first paint.@@ -1479,6 +1475,7 @@ export class ChatTopicActionImpl {excludeTriggers: currentData?.excludeTriggers,groupId: activeGroupId,isInbox: currentData?.isInbox,+ onlyMine: currentData?.onlyMine,pageSize: currentData?.pageSize || useGlobalStore.getState().status.topicPageSize || 20,sortBy: currentData?.sortBy,withDetails: currentData?.withDetails,@@ -1490,15 +1487,16 @@ export class ChatTopicActionImpl {{agentId,groupId,+ onlyMine,}: {agentId?: string;groupId?: string;+ onlyMine?: boolean;} = {},- ): SWRResponse<ChatTopic[]> => {- return useSWR<ChatTopic[]>(- keywords ? topicKeys.search(keywords, agentId, groupId) : null,- ([, keywords, agentId, groupId]: [string, string, string | undefined, string | undefined]) =>- topicService.searchTopics(keywords, agentId, groupId),+ ): SWRResponse<ChatTopic[]> =>+ useSWR<ChatTopic[]>(+ keywords ? topicKeys.search(keywords, agentId, groupId, onlyMine || undefined) : null,+ () => topicService.searchTopics(keywords ?? '', agentId, groupId, onlyMine),{onSuccess: (data) => {// Search rows render the same status icon as the sidebar — pin@@ -1515,7 +1513,6 @@ export class ChatTopicActionImpl {},},);- };switchTopic = async (id?: string | null, options?: SwitchTopicOptions): Promise<void> => {const opts = options ?? {};@@ -2027,6 +2024,7 @@ export class ChatTopicActionImpl {isExpandingPageSize: false,isLoadingMore: false,items: nextItems,+ onlyMine: currentData?.onlyMine,pageSize,sortBy: currentData?.sortBy,total,diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.tsindex f2cc3dc1352..457306af5bb 100644--- a/src/store/chat/slices/topic/initialState.ts+++ b/src/store/chat/slices/topic/initialState.ts@@ -20,6 +20,8 @@ export interface TopicData extends ReplicaPagedData<ChatTopic, number> {* dropping the loading-more row while `hasMore` remains true.*/loadMoreError?: unknown;+ /** Only the caller's own topics (workspace "only mine" filter; part of the query identity). */+ onlyMine?: boolean;/*** Last fetched/used page size for this topic container.* Used to detect "pageSize expansion" (user increases pageSize) without being affected by SWR revalidationdiff --git a/src/store/chat/slices/topic/projection.test.ts b/src/store/chat/slices/topic/projection.test.tsnew file mode 100644index 00000000000..c40dc7d2ba4--- /dev/null+++ b/src/store/chat/slices/topic/projection.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import type { TopicData } from './initialState';+import { normalizeTopicListParams, topicListFilterOf } from './projection';++const bucket = (data: Partial<TopicData>): TopicData => ({+ currentPage: 0,+ hasMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ ...data,+});++describe('topicListFilterOf', () => {+ it('returns nothing for an unloaded or unfiltered bucket', () => {+ expect(topicListFilterOf(undefined)).toBeUndefined();+ expect(topicListFilterOf(bucket({}))).toBeUndefined();+ });++ /** @example A send in a workspace must not echo other members' topics back into the filtered list. */+ it('forwards the only-mine filter alongside the status and trigger filters', () => {+ expect(+ topicListFilterOf(+ bucket({ excludeStatuses: ['completed'], excludeTriggers: ['cron'], onlyMine: true }),+ ),+ ).toEqual({ excludeStatuses: ['completed'], excludeTriggers: ['cron'], onlyMine: true });+ expect(topicListFilterOf(bucket({ onlyMine: true }))).toEqual({ onlyMine: true });+ });+});++describe('normalizeTopicListParams onlyMine', () => {+ it('drops a disabled only-mine filter so the request identity stays unchanged', () => {+ expect(normalizeTopicListParams({ agentId: 'a', onlyMine: false })?.onlyMine).toBeUndefined();+ expect(normalizeTopicListParams({ agentId: 'a', onlyMine: true })?.onlyMine).toBe(true);+ });+});diff --git a/src/store/chat/slices/topic/projection.ts b/src/store/chat/slices/topic/projection.tsindex 717d6e3caa3..c9dc5ce73cf 100644--- a/src/store/chat/slices/topic/projection.ts+++ b/src/store/chat/slices/topic/projection.ts@@ -1,3 +1,4 @@+import type { SendMessageServerParams } from '@lobechat/types';import isEqual from 'fast-deep-equal';import { definePagedReplica, defineReplica } from '@/libs/replica';@@ -13,6 +14,7 @@ export interface TopicListParams {excludeTriggers?: string[];groupId?: string;isInbox?: boolean;+ onlyMine?: boolean;pageSize: number;sortBy?: TopicQuerySortBy;withDetails?: boolean;@@ -44,6 +46,7 @@ export const normalizeTopicListParams = (excludeTriggers,groupId,isInbox,+ onlyMine,pageSize,sortBy,withDetails,@@ -57,6 +60,7 @@ export const normalizeTopicListParams = (excludeTriggers: excludeTriggers?.length ? excludeTriggers : undefined,groupId,isInbox,+ onlyMine: onlyMine || undefined,pageSize: pageSize || DEFAULT_TOPIC_PAGE_SIZE,sortBy,withDetails: withDetails || undefined,@@ -81,10 +85,12 @@ export const topicListResource = definePagedReplica<TopicListParams, ChatTopic,key: ({ agentId, groupId }) => topicMapKey({ agentId, groupId }),name: 'topicList',paging: topicPaging,- query: ({ excludeStatuses, excludeTriggers, isInbox, sortBy, withDetails }) => ({+ query: ({ excludeStatuses, excludeTriggers, isInbox, onlyMine, sortBy, withDetails }) => ({excludeStatuses,excludeTriggers,isInbox: Boolean(isInbox),+ // Omitted when off so pages persisted before the filter existed still match.+ onlyMine: onlyMine || undefined,sortBy,withDetails: Boolean(withDetails),}),@@ -92,6 +98,43 @@ export const topicListResource = definePagedReplica<TopicListParams, ChatTopic,version: 2,});+/** Query descriptors a fetched page stamps onto its `topicDataMap` bucket. */+export const topicListViewFields = ({+ excludeStatuses,+ excludeTriggers,+ isInbox,+ onlyMine,+ sortBy,+ withDetails,+}: TopicListParams): Partial<TopicData> => ({+ excludeStatuses,+ excludeTriggers,+ isInbox: Boolean(isInbox),+ onlyMine,+ sortBy,+ withDetails,+});++/**+ * The filter a loaded bucket was fetched with, for `sendMessageInServer` to+ * apply to the topic list it returns. Without it the server echoes an+ * unfiltered list that `internal_updateTopics` writes back over the filtered+ * sidebar — completed / cron / other members' topics reappear until the next+ * revalidation.+ */+export const topicListFilterOf = (+ data: TopicData | undefined,+): SendMessageServerParams['topicFilter'] => {+ if (!data) return undefined;+ const { excludeStatuses, excludeTriggers, onlyMine } = data;+ if (!excludeStatuses?.length && !excludeTriggers?.length && !onlyMine) return undefined;+ return {+ ...(excludeStatuses?.length ? { excludeStatuses } : {}),+ ...(excludeTriggers?.length ? { excludeTriggers } : {}),+ ...(onlyMine ? { onlyMine } : {}),+ };+};+/*** Agent Topics management page (`/agent/:aid/topics`): a different shape of* the same entity — `withDetails` columns and a larger page — so it is itsdiff --git a/src/store/chat/slices/topic/topicListCache.integration.test.ts b/src/store/chat/slices/topic/topicListCache.integration.test.tsindex 77f88071d5f..a41df4ac084 100644--- a/src/store/chat/slices/topic/topicListCache.integration.test.ts+++ b/src/store/chat/slices/topic/topicListCache.integration.test.ts@@ -20,6 +20,7 @@ import { type Cache, SWRConfig, useSWRConfig } from 'swr';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { cacheScope, createReplicaState } from '@/libs/replica';+import { broadcastCacheScope, resetCacheScopeBroadcast } from '@/libs/replica/cacheScopeEvents';import { localDataCache } from '@/libs/swr/localDataCache';import { createCacheProvider } from '@/libs/swr/localStorageProvider';import { setScopedMutate } from '@/libs/swr/mutate';@@ -367,4 +368,28 @@ describe('persisted topic list across a reload', () => {expect(useChatStore.getState().topicListReplica.scope).toBe(scopeB);sessionB.unmount();});++ /** @example A workspace switch while the "only mine" preference loads must not keep the previous workspace's topics on screen. */+ it('drops another scope’s list on a scope switch while the sync is gated off', async () => {+ resetCacheScopeBroadcast();+ const scopeA = createScope();+ vi.mocked(topicService.getTopics).mockResolvedValue({ items: [runningTopic], total: 1 } as any);+ const sessionA = renderHook(() => useChatStore().useFetchTopics(true, { agentId: AGENT_ID }), {+ wrapper: wrapper(makeProvider(scopeA)),+ });+ await waitFor(() =>+ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]?.items).toHaveLength(1),+ );+ sessionA.unmount();++ const scopeB = useScope(`${SCOPE_PREFIX}:${randomUUID()}`);+ const gated = renderHook(() => useChatStore().useFetchTopics(false, { agentId: AGENT_ID }), {+ wrapper: wrapper(makeProvider(scopeB)),+ });+ act(() => broadcastCacheScope(scopeB));++ expect(useChatStore.getState().topicDataMap[CONTAINER_KEY]).toBeUndefined();+ expect(useChatStore.getState().topicListReplica.scope).toBe(scopeB);+ gated.unmount();+ });});diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.tsindex 2f3d9147e4b..6d9bb5135e3 100644--- a/src/store/user/slices/workspaceUserSettings/action.ts+++ b/src/store/user/slices/workspaceUserSettings/action.ts@@ -193,6 +193,25 @@ export class WorkspaceUserSettingsActionImpl {};};+ /**+ * Seed the active workspace's persisted preference before a route commits, so+ * pre-paint reads that depend on it (the topic sidebar's "only mine" filter)+ * ask for the same list the mounted sidebar will. Call from a route loader,+ * bounded by a timeout. Resolves whether the active workspace's preference+ * is known afterwards — always in personal mode, which has no row.+ */+ preHydrateWorkspaceUserPreference = async (): Promise<boolean> => {+ const workspaceId = getActiveWorkspaceId();+ if (!workspaceId) return true;++ const replica = this.#replica();+ const scope = getWorkspaceUserPreferenceResource().scope.get();+ // The slot may still hold the previous identity's bucket; drop it first.+ replica.ensureScope(scope);+ await replica.hydrate({ workspaceId }, scope);+ return this.#get().workspaceUserPreferenceWorkspaceId === workspaceId;+ };+updateWorkspaceUserPreference = async (patch: Partial<WorkspaceUserPreference>,): Promise<void> => {diff --git a/src/store/user/slices/workspaceUserSettings/replica.test.ts b/src/store/user/slices/workspaceUserSettings/replica.test.tsindex 617b28198d4..4cec6e7c393 100644--- a/src/store/user/slices/workspaceUserSettings/replica.test.ts+++ b/src/store/user/slices/workspaceUserSettings/replica.test.ts@@ -138,6 +138,34 @@ describe('workspace user preference replica', () => {expect(entry('ws-1').source).toBe('server');});+ // A route loader derives the topic list identity ("only mine") from this+ // bucket before the route commits — nothing has mounted the sync yet.+ it('seeds the persisted bucket before paint without a mounted sync', async () => {+ await resource.storage!.set(+ { queryKey: storageKey, scope },+ { data: { topicOnlyMine: true }, updatedAt: 1 },+ );++ await expect(state().preHydrateWorkspaceUserPreference()).resolves.toBe(true);++ expect(state().workspaceUserPreferenceWorkspaceId).toBe('ws-1');+ expect(state().workspaceUserPreference).toEqual({ topicOnlyMine: true });+ expect(workspaceUserSettingsService.getPreference).not.toHaveBeenCalled();+ });++ it('reports the preference as unknown when no local copy exists', async () => {+ await expect(state().preHydrateWorkspaceUserPreference()).resolves.toBe(false);+ expect(workspaceUserSettingsService.getPreference).not.toHaveBeenCalled();+ });++ it('skips the pre-paint seed in personal mode', async () => {+ active.id = null;++ // Personal mode has no row: nothing to wait for.+ await expect(state().preHydrateWorkspaceUserPreference()).resolves.toBe(true);+ expect(state().workspaceUserPreferenceWorkspaceId).toBeNull();+ });+it('never hits the network in personal mode (no active workspace)', async () => {active.id = null;diff --git a/src/store/user/slices/workspaceUserSettings/selectors.test.ts b/src/store/user/slices/workspaceUserSettings/selectors.test.tsnew file mode 100644index 00000000000..322f16eec06--- /dev/null+++ b/src/store/user/slices/workspaceUserSettings/selectors.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import type { UserStore } from '@/store/user';++import { workspaceUserSettingsSelectors } from './selectors';++const state = (workspaceId: string | null, topicOnlyMine?: boolean) =>+ ({+ workspaceUserPreference: { topicOnlyMine },+ workspaceUserPreferenceWorkspaceId: workspaceId,+ }) as unknown as UserStore;++describe('workspaceUserSettingsSelectors.topicOnlyMine', () => {+ it('reads the filter for the workspace the bucket was loaded for', () => {+ expect(workspaceUserSettingsSelectors.topicOnlyMine('ws-1')(state('ws-1', true))).toBe(true);+ expect(workspaceUserSettingsSelectors.topicOnlyMine('ws-1')(state('ws-1', false))).toBe(false);+ });++ /** @example Switching from a workspace back to personal mode keeps the old bucket in the store. */+ it('ignores a bucket left over from another workspace or in personal mode', () => {+ expect(workspaceUserSettingsSelectors.topicOnlyMine(null)(state('ws-1', true))).toBe(false);+ expect(workspaceUserSettingsSelectors.topicOnlyMine('ws-2')(state('ws-1', true))).toBe(false);+ });+});diff --git a/src/store/user/slices/workspaceUserSettings/selectors.ts b/src/store/user/slices/workspaceUserSettings/selectors.tsindex 04011df9e8a..cb0a63ab2a8 100644--- a/src/store/user/slices/workspaceUserSettings/selectors.ts+++ b/src/store/user/slices/workspaceUserSettings/selectors.ts@@ -50,6 +50,20 @@ const isAgentHiddenFromSidebar =/** Per-member sidebar sections layout for the active workspace. */const sidebarLayout = (s: UserStore) => s.workspaceUserPreference.sidebar;+/**+ * Whether topic sidebars list only the caller's own topics in `workspaceId`+ * (the active one). The loaded bucket can still belong to the previous+ * workspace right after a switch — back to personal mode included — so it only+ * counts when it was loaded for this workspace. Always false in personal mode,+ * where every topic is the caller's.+ */+const topicOnlyMine =+ (workspaceId: string | null) =>+ (s: UserStore): boolean =>+ !!workspaceId &&+ s.workspaceUserPreferenceWorkspaceId === workspaceId &&+ !!s.workspaceUserPreference.topicOnlyMine;+/** The workspace whose preference row is currently loaded (null = not yet fetched). */const preferenceWorkspaceId = (s: UserStore) => s.workspaceUserPreferenceWorkspaceId;@@ -62,4 +76,5 @@ export const workspaceUserSettingsSelectors = {sidebarHiddenAgentIds,sidebarHiddenGroupIds,sidebarLayout,+ topicOnlyMine,};