π€― 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): per-agent only-mine filter, tray and file-chip polish (#21870)
Lobehub Coder123695a4c1bb
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 744f28089bf..152be7da035 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -121,8 +121,11 @@ export interface WorkspaceUserPreference {*/sidebarPinnedOverrides?: Record<string /* itemId */, boolean>;/**- * Topic sidebars list only the topics this member created, hiding the other- * members' topics under the same agent / group.+ * Topic sidebars list only the topics this member created.+ *+ * @deprecated The filter is a device-local, per-agent choice now+ * (`systemStatus.topicOnlyMineByAgent`). Existing values are ignored;+ * nothing reads or writes this key.*/topicOnlyMine?: boolean;}diff --git a/src/components/Editor/AutoSaveHint.tsx b/src/components/Editor/AutoSaveHint.tsxindex 1ba629692ed..f45764b75b2 100644--- a/src/components/Editor/AutoSaveHint.tsx+++ b/src/components/Editor/AutoSaveHint.tsx@@ -1,14 +1,48 @@'use client';-import { Icon, Spin, Tag } from '@lobehub/ui';+import { Icon, Spin } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import dayjs from 'dayjs';import { CloudIcon, TriangleAlertIcon } from 'lucide-react';import { type CSSProperties } from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { sx } from '@/styles/sx';import { type SaveStatus } from '@/types/saveState';+const styles = stylex.create({+ failed: {+ color: cssVar.colorError,+ },+ hint: {+ alignItems: 'center',+ color: cssVar.colorTextTertiary,+ display: 'inline-flex',+ flex: 'none',+ fontSize: 12,+ gap: 4,+ lineHeight: '20px',+ whiteSpace: 'nowrap',+ },+ retry: {+ backgroundColor: 'transparent',+ borderRadius: 2,+ borderStyle: 'none',+ color: 'inherit',+ cursor: 'pointer',+ fontFamily: 'inherit',+ fontSize: 'inherit',+ lineHeight: 'inherit',+ outline: { 'default': null, ':focus-visible': `2px solid ${cssVar.colorErrorBorder}` },+ outlineOffset: 1,+ padding: 0,+ textDecorationLine: 'underline',+ textUnderlineOffset: 2,+ },+});+interface AutoSaveHintProps {lastUpdatedTime?: string | Date | null;/** Called when the user clicks Retry on a failed save. */@@ -20,44 +54,45 @@ interface AutoSaveHintProps {/*** AutoSaveHint - Unified save status indicator for editors*- * Displays real-time save status for document/config changes. The `failed`- * state renders an error tag with an inline Retry so a- * silent save failure can never masquerade as "Latest version loaded".+ * A quiet inline hint, not a tag: saving is a background fact that should not+ * compete with the header's actions. Only the `failed` state takes the error+ * color, with an inline Retry, so a silent save failure can never masquerade+ * as "Latest version loaded".*/const AutoSaveHint = memo<AutoSaveHintProps>(({ style, saveStatus, lastUpdatedTime, onRetry }) => {const { t } = useTranslation('editor');if (saveStatus === 'saving')return (- <Tag icon={<Spin size="small" />} style={style}>+ <span {...sx(styles.hint, undefined, style)}>+ <Spin size="small" />{t('autoSave.saving')}- </Tag>+ </span>);if (saveStatus === 'failed')return (- <Tag- color={'error'}- icon={<Icon icon={TriangleAlertIcon} />}- style={{ cursor: onRetry ? 'pointer' : undefined, ...style }}- onClick={onRetry}- >+ <span {...sx([styles.hint, styles.failed], undefined, style)} role="alert">+ <Icon icon={TriangleAlertIcon} size={14} />{t('autoSave.failed')}- {onRetry ? ` Β· ${t('autoSave.retry')}` : ''}- </Tag>- );-- if (saveStatus === 'saved' && lastUpdatedTime)- return (- <Tag icon={<Icon icon={CloudIcon} />} style={style}>- {t('autoSave.saved')} {dayjs(lastUpdatedTime).fromNow()}- </Tag>+ {onRetry && (+ <>+ {' Β· '}+ <button {...stylex.props(styles.retry)} type="button" onClick={onRetry}>+ {t('autoSave.retry')}+ </button>+ </>+ )}+ </span>);return (- <Tag icon={<Icon icon={CloudIcon} />} style={style}>- {t('autoSave.latest')}- </Tag>+ <span {...sx(styles.hint, undefined, style)}>+ <Icon icon={CloudIcon} size={14} />+ {saveStatus === 'saved' && lastUpdatedTime+ ? `${t('autoSave.saved')} ${dayjs(lastUpdatedTime).fromNow()}`+ : t('autoSave.latest')}+ </span>);});diff --git a/src/features/AgentSidebar/Topic/List/index.test.tsx b/src/features/AgentSidebar/Topic/List/index.test.tsxindex cb7cb705f0d..fc9920dcb81 100644--- a/src/features/AgentSidebar/Topic/List/index.test.tsx+++ b/src/features/AgentSidebar/Topic/List/index.test.tsx@@ -126,9 +126,10 @@ vi.mock('@/store/user/selectors', () => ({topicSortBy: (state: { topicSortBy: string }) => state.topicSortBy,},userProfileSelectors: { userId: () => 'test-user-id' },- workspaceUserSettingsSelectors: { topicOnlyMine: () => () => false },}));+vi.mock('@/hooks/useTopicOnlyMine', () => ({ useTopicOnlyMine: () => false }));+vi.mock('../AllTopicsDrawer', () => ({default: ({ open }: { open: boolean }) => (<div data-open={String(open)} data-testid="all-topics-drawer" />diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsxindex 21e182dc05f..45b6a87283d 100644--- a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx+++ b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx@@ -16,8 +16,15 @@ const preferenceMock = vi.hoisted(() => ({const updateAgentModeMock = vi.hoisted(() => vi.fn());const workspaceMock = vi.hoisted(() => ({hasActiveWorkspace: false,+ ownerId: 'agent-1' as string | undefined,+ setTopicOnlyMine: vi.fn(),topicOnlyMine: false,- updateWorkspaceUserPreference: vi.fn(),+}));++vi.mock('@/hooks/useTopicOnlyMine', () => ({+ useSetTopicOnlyMine: () => workspaceMock.setTopicOnlyMine,+ useTopicOnlyMine: () => workspaceMock.topicOnlyMine,+ useTopicOnlyMineOwnerId: () => workspaceMock.ownerId,}));vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({@@ -49,7 +56,6 @@ vi.mock('@/store/user', () => ({useUserStore: (selector: (state: unknown) => unknown) =>selector({updatePreference: preferenceMock.updatePreference,- updateWorkspaceUserPreference: workspaceMock.updateWorkspaceUserPreference,}),}));@@ -58,9 +64,6 @@ vi.mock('@/store/user/selectors', () => ({topicSortBy: () => preferenceMock.topicSortBy,topicIncludeCompleted: () => preferenceMock.topicIncludeCompleted,},- workspaceUserSettingsSelectors: {- topicOnlyMine: () => () => workspaceMock.topicOnlyMine,- },}));const organizeLabels = (items: any[]): string[] => {@@ -130,6 +133,7 @@ describe('useTopicFilterDropdownMenu only-mine filter', () => {scopeMock.scope = null;workspaceMock.hasActiveWorkspace = false;workspaceMock.topicOnlyMine = false;+ workspaceMock.ownerId = 'agent-1';vi.clearAllMocks();});@@ -141,7 +145,8 @@ describe('useTopicFilterDropdownMenu only-mine filter', () => {expect(keys).toEqual(['showCompleted']);});- it('toggles the per-workspace only-mine preference inside a workspace', () => {+ /** @example Turning it on for one agent must not filter every other agent's list. */+ it("toggles the current agent's own local only-mine choice inside a workspace", () => {workspaceMock.hasActiveWorkspace = true;const { result } = renderHook(() => useTopicFilterDropdownMenu());@@ -151,8 +156,16 @@ describe('useTopicFilterDropdownMenu only-mine filter', () => {expect(item.label).toBe('filter.onlyMine');item.onClick();- expect(workspaceMock.updateWorkspaceUserPreference).toHaveBeenCalledWith({- topicOnlyMine: true,- });+ expect(workspaceMock.setTopicOnlyMine).toHaveBeenCalledWith('agent-1', true);+ });++ it('hides the only-mine filter until the list knows its agent', () => {+ workspaceMock.hasActiveWorkspace = true;+ workspaceMock.ownerId = undefined;++ const { result } = renderHook(() => useTopicFilterDropdownMenu());++ const keys = filterGroup(result.current()).children.map((child: any) => child.key);+ expect(keys).toEqual(['showCompleted']);});});diff --git a/src/features/AgentSidebar/Topic/useOnlyMineFilterItem.tsx b/src/features/AgentSidebar/Topic/useOnlyMineFilterItem.tsxindex 45d1993be3f..8890314bfeb 100644--- a/src/features/AgentSidebar/Topic/useOnlyMineFilterItem.tsx+++ b/src/features/AgentSidebar/Topic/useOnlyMineFilterItem.tsx@@ -5,30 +5,33 @@ 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';+import {+ useSetTopicOnlyMine,+ useTopicOnlyMine,+ useTopicOnlyMineOwnerId,+} from '@/hooks/useTopicOnlyMine';/*** "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.+ * stored on this device per agent (group / project). Returns `null` in+ * personal mode.*/export const useOnlyMineFilterItem = (): DropdownItem | null => {const { t } = useTranslation('topic');const hasActiveWorkspace = useHasActiveWorkspace();+ const ownerId = useTopicOnlyMineOwnerId();const onlyMine = useTopicOnlyMine();- const updateWorkspaceUserPreference = useUserStore((s) => s.updateWorkspaceUserPreference);+ const setOnlyMine = useSetTopicOnlyMine();return useMemo(() => {- if (!hasActiveWorkspace) return null;+ if (!hasActiveWorkspace || !ownerId) return null;return {icon: onlyMine ? <Icon icon={LucideCheck} /> : <div />,key: 'onlyMine',label: t('filter.onlyMine'),- onClick: () => {- void updateWorkspaceUserPreference({ topicOnlyMine: !onlyMine });- },+ onClick: () => setOnlyMine(ownerId, !onlyMine),};- }, [hasActiveWorkspace, onlyMine, updateWorkspaceUserPreference, t]);+ }, [hasActiveWorkspace, ownerId, onlyMine, setOnlyMine, t]);};diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts b/src/features/AgentSidebar/Topic/useScopedTopics.test.tsindex d3a73e4e9f4..ac220b59201 100644--- a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts+++ b/src/features/AgentSidebar/Topic/useScopedTopics.test.ts@@ -77,9 +77,9 @@ vi.mock('@/store/user', () => ({}));vi.mock('@/store/user/selectors', () => ({userProfileSelectors: { userId: (s: typeof userFixture) => s.userId },- workspaceUserSettingsSelectors: {- topicOnlyMine: () => (s: typeof userFixture) => s.topicOnlyMine,- },+}));+vi.mock('@/hooks/useTopicOnlyMine', () => ({+ useTopicOnlyMine: () => userFixture.topicOnlyMine,}));vi.mock('i18next', () => ({ t: (key: string) => key }));@@ -104,7 +104,7 @@ describe('Project topics use the canonical Agent sidebar rules', () => {userFixture.topicOnlyMine = false;updateSystemStatus.mockClear();});- it('lists only the caller topics with the workspace only-mine filter, keeping the open one', () => {+ it('lists only the caller topics with the project only-mine filter, keeping the open one', () => {userFixture.topicOnlyMine = true;const { result, rerender } = renderHook(() => useScopedSidebarTopics(20, 'updatedAt', 'flat', false),diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.ts b/src/features/AgentSidebar/Topic/useScopedTopics.tsindex 35cb3648cb1..0a119e1a6e6 100644--- a/src/features/AgentSidebar/Topic/useScopedTopics.ts+++ b/src/features/AgentSidebar/Topic/useScopedTopics.ts@@ -78,7 +78,7 @@ 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+ * Project topics arrive in full, so the project's "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[] => {diff --git a/src/features/Conversation/ChatInput/OpStatusTray.tsx b/src/features/Conversation/ChatInput/OpStatusTray.tsxindex 3c5b0a87b16..dab78f11042 100644--- a/src/features/Conversation/ChatInput/OpStatusTray.tsx+++ b/src/features/Conversation/ChatInput/OpStatusTray.tsx@@ -3,7 +3,8 @@import { formatElapsedClockTime } from '@lobechat/utils';import { createStaticStyles, cx, Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';import type { LucideIcon } from 'lucide-react';-import { BrainCircuitIcon, CircleDollarSignIcon, CoinsIcon } from 'lucide-react';+import { CircleDollarSignIcon, CoinsIcon, FootprintsIcon } from 'lucide-react';+import type { ReactNode } from 'react';import { Fragment, memo, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -15,6 +16,7 @@ import { calculateOperationUsageMetrics } from '@/utils/operationUsageMetrics';import { contextSelectors, dataSelectors, useConversationStore } from '../store';import { type ActivityKey, resolveOperationActivity } from '../utils/operationActivity';+import AnimatedCount from './OpStatusTray/AnimatedCount';import { parseStatusPhrases, pickRotatingStatusPhrase } from './OpStatusTray/logic';// Cycle the generating phrase like a carousel so a long-running task doesn't@@ -237,7 +239,7 @@ interface MetricItem {key: 'cost' | 'llmCalls' | 'tokens';label: string;title: string;- value: string;+ value: ReactNode;}const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {@@ -347,10 +349,10 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {// Zero-valued metrics render nothing. LLM calls are the user-facing "step"// metric: tool-only iterations never increment it.- const metrics = [+ const metricCandidates: (MetricItem | undefined)[] = [operationState.llmCalls > 0? {- icon: BrainCircuitIcon,+ icon: FootprintsIcon,key: 'llmCalls',label: llmCallsLabel,title: `${operationState.llmCalls} ${llmCallsLabel}`,@@ -363,7 +365,7 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {key: 'tokens',label: tokenLabel,title: `${formatTokens(totalTokens)} ${tokenLabel}`,- value: formatTokens(totalTokens),+ value: <AnimatedCount format={formatTokens} value={totalTokens} />,}: undefined,totalCost > 0@@ -375,7 +377,8 @@ const OpStatusTray = memo<OpStatusTrayProps>(({ seamless, topAttached }) => {value: formatCost(totalCost),}: undefined,- ].filter((item): item is MetricItem => !!item);+ ];+ const metrics = metricCandidates.filter((item): item is MetricItem => !!item);const tokenMetric = metrics.find((metric) => metric.key === 'tokens');const renderMetric = ({ icon, title, value }: MetricItem) => (diff --git a/src/features/Conversation/ChatInput/OpStatusTray/AnimatedCount.tsx b/src/features/Conversation/ChatInput/OpStatusTray/AnimatedCount.tsxnew file mode 100644index 00000000000..f3af6246157--- /dev/null+++ b/src/features/Conversation/ChatInput/OpStatusTray/AnimatedCount.tsx@@ -0,0 +1,16 @@+import { memo } from 'react';++import { useAnimatedCount } from './useAnimatedCount';++interface AnimatedCountProps {+ format: (value: number) => string;+ value: number;+}++const AnimatedCount = memo<AnimatedCountProps>(({ format, value }) => (+ <>{useAnimatedCount(value, format)}</>+));++AnimatedCount.displayName = 'AnimatedCount';++export default AnimatedCount;diff --git a/src/features/Conversation/ChatInput/OpStatusTray/useAnimatedCount.test.ts b/src/features/Conversation/ChatInput/OpStatusTray/useAnimatedCount.test.tsnew file mode 100644index 00000000000..8bb085d6803--- /dev/null+++ b/src/features/Conversation/ChatInput/OpStatusTray/useAnimatedCount.test.ts@@ -0,0 +1,69 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useAnimatedCount } from './useAnimatedCount';++const mocks = vi.hoisted(() => ({+ animate: vi.fn(),+ reduceMotion: false,+ stop: vi.fn(),+}));++vi.mock('motion/react', () => ({+ animate: mocks.animate,+ useReducedMotion: () => mocks.reduceMotion,+}));++const format = (n: number) => `${n}t`;+const render = (value: number) =>+ renderHook(({ value }) => useAnimatedCount(value, format), { initialProps: { value } });++describe('useAnimatedCount', () => {+ beforeEach(() => {+ mocks.animate.mockReset().mockReturnValue({ stop: mocks.stop });+ mocks.reduceMotion = false;+ mocks.stop.mockClear();+ });++ it('starts at its value without animating', () => {+ const { result } = render(100);++ expect(result.current).toBe('100t');+ expect(mocks.animate).not.toHaveBeenCalled();+ });++ /** @example The token total jumped from 120.0k to 194.0k with no growth in between. */+ it('counts up from the shown number instead of jumping to a new value', () => {+ const { result, rerender } = render(100);+ rerender({ value: 200 });++ expect(result.current).toBe('100t');+ expect(mocks.animate).toHaveBeenCalledWith(100, 200, expect.anything());++ const { onUpdate } = mocks.animate.mock.calls[0][2];+ act(() => onUpdate(149.6));+ expect(result.current).toBe('150t');+ act(() => onUpdate(200));+ expect(result.current).toBe('200t');+ });++ it('continues from the interrupted number when the value moves again', () => {+ const { rerender } = render(100);+ rerender({ value: 200 });+ act(() => mocks.animate.mock.calls[0][2].onUpdate(150));++ rerender({ value: 300 });++ expect(mocks.stop).toHaveBeenCalled();+ expect(mocks.animate).toHaveBeenLastCalledWith(150, 300, expect.anything());+ });++ it('jumps straight to the value for reduced-motion users', () => {+ mocks.reduceMotion = true;+ const { result, rerender } = render(100);+ rerender({ value: 200 });++ expect(result.current).toBe('200t');+ expect(mocks.animate).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Conversation/ChatInput/OpStatusTray/useAnimatedCount.ts b/src/features/Conversation/ChatInput/OpStatusTray/useAnimatedCount.tsnew file mode 100644index 00000000000..6b35e065cb0--- /dev/null+++ b/src/features/Conversation/ChatInput/OpStatusTray/useAnimatedCount.ts@@ -0,0 +1,37 @@+import { animate, useReducedMotion } from 'motion/react';+import { useEffect, useRef, useState } from 'react';++const COUNT_DURATION_S = 0.8;++/**+ * Formatted text that counts from the previously shown number to `value`+ * instead of jumping, so a growing total (tokens arrive in per-step chunks)+ * reads as growth. Starts at `value` on mount; reduced-motion users get the+ * plain jump. `format` must be stable.+ */+export const useAnimatedCount = (value: number, format: (value: number) => string): string => {+ const reduceMotion = useReducedMotion();+ const shownRef = useRef(value);+ const [display, setDisplay] = useState(() => format(value));++ useEffect(() => {+ const from = shownRef.current;+ if (from === value || reduceMotion) {+ shownRef.current = value;+ setDisplay(format(value));+ return;+ }++ const controls = animate(from, value, {+ duration: COUNT_DURATION_S,+ ease: 'easeOut',+ onUpdate: (latest) => {+ shownRef.current = latest;+ setDisplay(format(Math.round(latest)));+ },+ });+ return () => controls.stop();+ }, [format, reduceMotion, value]);++ return display;+};diff --git a/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx b/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsxindex 65f629d9802..523337e71f6 100644--- a/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx+++ b/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx@@ -4,6 +4,7 @@ import React, { memo } from 'react';import { LocalFile } from '@/features/LocalFile';import { useStartTopicConversation } from '../../../../hooks/useStartTopicConversation';+import { useOpenEditedFile } from '../../../../Messages/EditedFilesCard/useOpenEditedFile';import { useConversationStore } from '../../../../store';import { type MarkdownElementProps } from '../../type';@@ -24,6 +25,9 @@ const Render = memo<MarkdownElementProps<LocalFileProps>>(({ node }) => {(s) => !!s.context.topicShareId || !!s.context.agentShareId,);const conversation = useStartTopicConversation();+ // Same reachability rules as the edited-files card: on web the file opens in+ // the portal only when the agent's bound device can serve the read.+ const resolveOpenFile = useOpenEditedFile();if (!name || !path) {// If required properties are missing, render an error or null@@ -33,12 +37,16 @@ const Render = memo<MarkdownElementProps<LocalFileProps>>(({ node }) => {// isDirectory may be true (from plugin) or undefined; ensure it is a booleanconst isDir = isDirectory === true;+ const openInPortal = isDir+ ? undefined+ : resolveOpenFile({ kind: 'modified', path, sandboxBacked: false });return (<LocalFileconversation={conversation}isDirectory={isDir}name={name}+ openInPortal={openInPortal}path={path}readonly={isSharePage}/>diff --git a/src/features/LocalFile/LocalFile.tsx b/src/features/LocalFile/LocalFile.tsxindex 77580303b96..969684e981c 100644--- a/src/features/LocalFile/LocalFile.tsx+++ b/src/features/LocalFile/LocalFile.tsx@@ -1,4 +1,4 @@-import { createStaticStyles, cssVar, Flexbox, Popover } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx, Flexbox, Popover } from '@lobehub/ui';import { ExternalLink, EyeIcon, FolderOpen, MessageSquarePlus } from 'lucide-react';import React from 'react';import { useTranslation } from 'react-i18next';@@ -11,13 +11,13 @@ import { useStartTopicInDirectory } from './useStartTopicInDirectory';const styles = createStaticStyles(({ css }) => ({container: css`- cursor: pointer;-padding-block: 2px;padding-inline: 4px 8px;border-radius: 4px;-color: ${cssVar.colorText};+ `,+ interactive: css`+ cursor: pointer;:hover {color: ${cssVar.colorText};@@ -104,6 +104,12 @@ interface LocalFileProps {conversation?: StartTopicConversation;isDirectory?: boolean;name: string;+ /**+ * Web only: opens the file in the right-side portal through the agent's+ * bound device. Without it the web chip is a static reference β the web app+ * has no Open / Show in Folder.+ */+ openInPortal?: () => void;path?: string;/*** When true, disable interactive actions (Open / Show in Folder).@@ -117,11 +123,18 @@ export const LocalFile = ({name,path,isDirectory = false,+ openInPortal,readonly = false,}: LocalFileProps) => {const { t } = useTranslation('components');- const { canPreview, handleClick, handleOpenFile, handleOpenFolder, handlePreview } =- useLocalFileActions({ isDirectory, path, readonly });+ const {+ canOpenNatively,+ canPreview,+ handleClick,+ handleOpenFile,+ handleOpenFolder,+ handlePreview,+ } = useLocalFileActions({ isDirectory, openInPortal, path, readonly });const { canStartTopic, startTopic } = useStartTopicInDirectory({conversation,isDirectory,@@ -133,7 +146,7 @@ export const LocalFile = ({<Flexboxhorizontalalign={'center'}- className={styles.container}+ className={cx(styles.container, (handleClick || canOpenNatively) && styles.interactive)}gap={4}// Inline chip, not a <button> (block layout inside markdown prose) β so// give the clickable state complete button semantics by hand.@@ -158,8 +171,9 @@ export const LocalFile = ({</Flexbox>);- // Readonly mode (e.g. share page): no popover or local actions.- if (readonly) {+ // Readonly mode (e.g. share page) and the web app have no system actions;+ // there the chip only previews on click, so a hover menu would add nothing.+ if (!canOpenNatively) {return fileContent;}diff --git a/src/features/LocalFile/useLocalFileActions.test.ts b/src/features/LocalFile/useLocalFileActions.test.tsindex 8cb0128676a..fa3134a520d 100644--- a/src/features/LocalFile/useLocalFileActions.test.ts+++ b/src/features/LocalFile/useLocalFileActions.test.ts@@ -9,9 +9,13 @@ import { createLocalFileTabId } from '@/store/chat/slices/portal/helpers';import { useLocalFileActions } from './useLocalFileActions';+const env = vi.hoisted(() => ({ isDesktop: true }));+vi.mock('@lobechat/const', async (importOriginal) => ({...((await importOriginal()) as Record<string, unknown>),- isDesktop: true,+ get isDesktop() {+ return env.isDesktop;+ },}));const openLocalFileOrFolder = vi.hoisted(() => vi.fn());@@ -38,6 +42,7 @@ const setWorkingDirectory = (workingDirectory: string) => {describe('useLocalFileActions', () => {afterEach(() => {+ env.isDesktop = true;useChatStore.setState(useChatStore.getInitialState());vi.clearAllMocks();});@@ -108,4 +113,49 @@ describe('useLocalFileActions', () => {expect(result.current.canPreview).toBe(false);expect(result.current.handleClick).toBeUndefined();});++ describe('on the web app', () => {+ /** @example Web chips offered Open / Show in Folder, which are Electron IPC and did nothing. */+ it('previews the file in the portal through the bound device and offers no system actions', () => {+ env.isDesktop = false;+ const openInPortal = vi.fn();++ const { result } = renderHook(() =>+ useLocalFileActions({ openInPortal, path: '/Users/me/project/deck.md' }),+ );++ expect(result.current.canOpenNatively).toBe(false);+ expect(result.current.canPreview).toBe(true);+ result.current.handleClick!();++ expect(openInPortal).toHaveBeenCalledTimes(1);+ expect(openLocalFileOrFolder).not.toHaveBeenCalled();+ });++ it('leaves the chip inert when no device can serve the file', () => {+ env.isDesktop = false;++ const { result } = renderHook(() =>+ useLocalFileActions({ path: '/Users/me/project/deck.md' }),+ );++ expect(result.current.canPreview).toBe(false);+ expect(result.current.handleClick).toBeUndefined();+ });++ it('does not try to open directories in a system file manager', () => {+ env.isDesktop = false;++ const { result } = renderHook(() =>+ useLocalFileActions({+ isDirectory: true,+ openInPortal: vi.fn(),+ path: '/Users/me/project/docs',+ }),+ );++ expect(result.current.canPreview).toBe(false);+ expect(result.current.handleClick).toBeUndefined();+ });+ });});diff --git a/src/features/LocalFile/useLocalFileActions.ts b/src/features/LocalFile/useLocalFileActions.tsindex b9f472c28f0..2502f4ff265 100644--- a/src/features/LocalFile/useLocalFileActions.ts+++ b/src/features/LocalFile/useLocalFileActions.ts@@ -7,12 +7,18 @@ import { topicSelectors } from '@/store/chat/selectors';interface UseLocalFileActionsParams {isDirectory?: boolean;+ /**+ * Web only: opens the file in the right-side portal through the agent's+ * bound device. Absent when no device can serve the read.+ */+ openInPortal?: () => void;path?: string;readonly?: boolean;}export const useLocalFileActions = ({isDirectory = false,+ openInPortal,path,readonly = false,}: UseLocalFileActionsParams) => {@@ -24,7 +30,13 @@ export const useLocalFileActions = ({const allowExternalFilePreview =!!parsed && (!workingDirectory || parsed.workingDirectory !== workingDirectory);+ // The web app cannot reach the user's filesystem: Open / Show in Folder are+ // Electron IPC and do nothing there, so a file can only be previewed in the+ // portal β and only when a bound device serves the read.+ const webPreview = !isDesktop && !readonly && !isDirectory ? openInPortal : undefined;+const handlePreview = () => {+ if (webPreview) return webPreview();if (!parsed) return;openLocalFile({allowExternalFilePreview,@@ -43,15 +55,21 @@ export const useLocalFileActions = ({localFileService.openFileFolder(path);};+ // Directories open in the system file manager (desktop only); files preview+ // in the portal. Nothing to do leaves the chip inert.const handleClick = readonly? undefined- : () => {- if (isDirectory) return handleOpenFile();- if (parsed) return handlePreview();- };+ : isDirectory+ ? isDesktop+ ? handleOpenFile+ : undefined+ : parsed || webPreview+ ? handlePreview+ : undefined;return {- canPreview: !!parsed,+ canOpenNatively: isDesktop && !readonly,+ canPreview: !!parsed || !!webPreview,handleClick,handleOpenFile,handleOpenFolder,diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsxindex 35e22c2af8d..eea5ed483af 100644--- a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx@@ -32,7 +32,6 @@ import {} from '@/features/AgentSidebar/Topic/TopicListScope';import { useOnlyMineTopics, useScopedTopics } from '@/features/AgentSidebar/Topic/useScopedTopics';import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import { useWorkspacePreferenceReady } from '@/hooks/useWorkspacePreferenceReady';import {useProjectDirectories,useProjectDirectoryStore,@@ -96,10 +95,6 @@ function ProjectTopicList({ projectId, coordinatorAgentId, itemKey }: ProjectDirfilterTopics(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();const startTopic = useStartProjectTopic(projectId);const fixedDeviceId = useAgentFixedDeviceId(coordinatorAgentId);return (@@ -147,7 +142,7 @@ function ProjectTopicList({ projectId, coordinatorAgentId, itemKey }: ProjectDironRetry={() => Promise.all([request.revalidate(), directoriesRequest.revalidate()])}/>) : null}- {!request.hasData || isPreferenceLoading ? (+ {!request.hasData ? (<SkeletonList />) : !topics.length && !request.error && topicGroupMode !== 'byAgent' ? (// By agent, the main agent's empty group offers the first topic instead.@@ -162,7 +157,7 @@ function ProjectTopicList({ projectId, coordinatorAgentId, itemKey }: ProjectDir</Button></Flexbox>) : null}- {isPreferenceLoading ? null : topicGroupMode === 'flat' ? (+ {topicGroupMode === 'flat' ? (<FlatMode />) : topicGroupMode === 'byStatus' ? (<ByStatusMode />diff --git a/src/hooks/chatTopicListQuery.test.ts b/src/hooks/chatTopicListQuery.test.tsindex b0282004a40..98050cd23d3 100644--- a/src/hooks/chatTopicListQuery.test.ts+++ b/src/hooks/chatTopicListQuery.test.ts@@ -9,11 +9,18 @@ const agentStateMock = vi.hoisted(() => ({agentMap: {} as Record<string, any>,builtinAgentIdMap: { inbox: 'agt_inbox' } as Record<string, string>,}));-const globalStateMock = vi.hoisted(() => ({ topicPageSize: 20 }));+const globalStateMock = vi.hoisted(() => ({+ topicOnlyMineByAgent: {} as Record<string, boolean>,+ topicPageSize: 20,+}));const userStateMock = vi.hoisted(() => ({topicGroupMode: 'byTime' as string,topicIncludeCompleted: false,- topicOnlyMine: false,+}));+const workspaceMock = vi.hoisted(() => ({ activeWorkspaceId: 'ws-1' as string | null }));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => workspaceMock.activeWorkspaceId,}));vi.mock('@/store/agent', () => ({ useAgentStore: { getState: () => agentStateMock } }));@@ -31,7 +38,11 @@ vi.mock('@/store/agent/selectors', () => ({vi.mock('@/store/global', () => ({ useGlobalStore: { getState: () => globalStateMock } }));vi.mock('@/store/global/selectors', () => ({- systemStatusSelectors: { topicPageSize: (s: typeof globalStateMock) => s.topicPageSize },+ systemStatusSelectors: {+ topicOnlyMine: (ownerId?: string) => (s: typeof globalStateMock) =>+ !!ownerId && !!s.topicOnlyMineByAgent[ownerId],+ topicPageSize: (s: typeof globalStateMock) => s.topicPageSize,+ },}));vi.mock('@/store/user', () => ({ useUserStore: { getState: () => userStateMock } }));@@ -41,9 +52,6 @@ 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', () => {@@ -118,10 +126,11 @@ describe('getSidebarTopicListParams', () => {beforeEach(() => {agentStateMock.activeAgentId = 'agent-1';agentStateMock.agentMap = {};+ globalStateMock.topicOnlyMineByAgent = {};globalStateMock.topicPageSize = 20;userStateMock.topicGroupMode = 'byTime';userStateMock.topicIncludeCompleted = false;- userStateMock.topicOnlyMine = false;+ workspaceMock.activeWorkspaceId = 'ws-1';});it('returns nothing without a session', () => {@@ -154,10 +163,25 @@ 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;+ it("carries the route agent's own only-mine choice into the pre-paint request", () => {+ globalStateMock.topicOnlyMineByAgent = { 'agent-7': true };expect(getSidebarTopicListParams({ agentId: 'agent-7' })?.onlyMine).toBe(true);+ expect(getSidebarTopicListParams({ agentId: 'agent-8' })?.onlyMine).toBeUndefined();+ });++ it('keys a group session by its group id', () => {+ globalStateMock.topicOnlyMineByAgent = { grp_1: true };++ expect(getSidebarTopicListParams({ groupId: 'grp_1' })?.onlyMine).toBe(true);+ });++ /** @example Personal mode has nobody else's topics to hide, whatever the device remembers. */+ it('ignores a remembered choice outside a workspace', () => {+ globalStateMock.topicOnlyMineByAgent = { 'agent-7': true };+ workspaceMock.activeWorkspaceId = null;++ expect(getSidebarTopicListParams({ agentId: 'agent-7' })?.onlyMine).toBeUndefined();});it('never flags a group session as inbox and keeps its default ordering', () => {diff --git a/src/hooks/chatTopicListQuery.ts b/src/hooks/chatTopicListQuery.tsindex 0e7a69c55aa..65faaf9908b 100644--- a/src/hooks/chatTopicListQuery.ts+++ b/src/hooks/chatTopicListQuery.ts@@ -12,7 +12,7 @@ import {import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useUserStore } from '@/store/user';-import { preferenceSelectors, workspaceUserSettingsSelectors } from '@/store/user/selectors';+import { preferenceSelectors } from '@/store/user/selectors';import type { TopicGroupMode } from '@/types/topic';const EXCLUDE_STATUSES_COMPLETED = ['completed'];@@ -90,17 +90,20 @@ export const getSidebarTopicListParams = (session: {const agentState = useAgentStore.getState();const inboxAgentId = builtinAgentSelectors.inboxAgentId(agentState);const userState = useUserStore.getState();+ const globalState = useGlobalStore.getState();return normalizeTopicListParams({...deriveSidebarTopicListQuery({includeCompleted: preferenceSelectors.topicIncludeCompleted(userState),isGroupSession: !!groupId,- onlyMine: workspaceUserSettingsSelectors.topicOnlyMine(getActiveWorkspaceId())(userState),+ onlyMine:+ !!getActiveWorkspaceId() &&+ systemStatusSelectors.topicOnlyMine(groupId ?? agentId)(globalState),topicGroupMode: getTopicGroupModeForAgent(agentId),}),agentId,groupId,isInbox: !groupId && !!inboxAgentId && inboxAgentId === agentId,- pageSize: systemStatusSelectors.topicPageSize(useGlobalStore.getState()),+ pageSize: systemStatusSelectors.topicPageSize(globalState),});};diff --git a/src/hooks/useFetchChatTopics.test.ts b/src/hooks/useFetchChatTopics.test.tsindex df0569fb6a5..c529f186031 100644--- a/src/hooks/useFetchChatTopics.test.ts+++ b/src/hooks/useFetchChatTopics.test.ts@@ -16,8 +16,15 @@ const mocks = vi.hoisted(() => ({topicGroupMode: 'byStatus' as string,topicIncludeCompleted: false,topicOnlyMine: false,+ topicOnlyMineOwners: [] as (string | undefined)[],topicPageSize: 20,- workspacePreferenceLoading: false,+}));++vi.mock('@/hooks/useTopicOnlyMine', () => ({+ useTopicOnlyMine: (ownerId?: string) => {+ mocks.topicOnlyMineOwners.push(ownerId);+ return mocks.topicOnlyMine;+ },}));vi.mock('@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode', () => ({@@ -54,22 +61,18 @@ vi.mock('@/store/global/selectors', () => ({}));vi.mock('@/store/user', () => ({- useUserStore: (selector: (state: unknown) => unknown) =>- selector({- useFetchWorkspaceUserPreference: () => ({ isLoading: mocks.workspacePreferenceLoading }),- }),+ useUserStore: (selector: (state: unknown) => unknown) => selector({}),}));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;+ mocks.topicOnlyMineOwners = [];});it('asks the same query for a named agent as the sidebar does for the active one', () => {@@ -98,7 +101,7 @@ 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', () => {+ it('forwards the per-agent only-mine filter from both the sidebar and the panel', () => {mocks.topicOnlyMine = true;renderHook(() => useFetchChatTopics());@@ -111,18 +114,11 @@ describe('chat topic list fetches', () => {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)!;+ /** @example A goal-chat panel reads the choice of the agent it names, not the active session's. */+ it('reads the panel agent its own only-mine choice', () => {+ renderHook(() => useFetchAgentChatTopics('agent-2'));- expect(sidebarEnabled).toBe(false);- expect(panelEnabled).toBe(false);+ expect(mocks.topicOnlyMineOwners.at(-1)).toBe('agent-2');});it('stays disabled until the panel knows its agent', () => {diff --git a/src/hooks/useFetchChatTopics.ts b/src/hooks/useFetchChatTopics.tsindex d6c433c1cb4..564a69f6aa3 100644--- a/src/hooks/useFetchChatTopics.ts+++ b/src/hooks/useFetchChatTopics.ts@@ -5,7 +5,6 @@ import {} 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';@@ -25,26 +24,18 @@ 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 = (): { query: SidebarTopicListQuery; ready: boolean } => {+const useChatTopicListQuery = (ownerId?: string): SidebarTopicListQuery => {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 onlyMine = useTopicOnlyMine(ownerId);const activeGroupId = useChatStore((s) => s.activeGroupId);const { topicGroupMode } = useAgentTopicGroupMode();- return {- query: deriveSidebarTopicListQuery({- includeCompleted,- isGroupSession: !!activeGroupId,- onlyMine,- topicGroupMode,- }),- ready,- };+ return deriveSidebarTopicListQuery({+ includeCompleted,+ isGroupSession: !!activeGroupId,+ onlyMine,+ topicGroupMode,+ });};/**@@ -56,8 +47,7 @@ const useChatTopicListQuery = (): { query: SidebarTopicListQuery; ready: boolean* params; don't spread them across individual components.*/export const useFetchChatTopics = () => {- const { query, ready } = useChatTopicListQuery();- return useFetchTopics(query, ready);+ return useFetchTopics(useChatTopicListQuery());};/**@@ -70,11 +60,11 @@ export const useFetchChatTopics = () => {* moment such a panel mounted next to it.*/export const useFetchAgentChatTopics = (agentId?: string) => {- const { query, ready } = useChatTopicListQuery();+ const query = useChatTopicListQuery(agentId);const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);const pageSize = useGlobalStore(systemStatusSelectors.topicPageSize);- return useChatStore((s) => s.useFetchTopics)(!!agentId && ready, {+ return useChatStore((s) => s.useFetchTopics)(!!agentId, {agentId,...query,isInbox: !!inboxAgentId && agentId === inboxAgentId,diff --git a/src/hooks/useSidebarTopicSearch.ts b/src/hooks/useSidebarTopicSearch.tsindex db082126b3b..779d8c0df33 100644--- a/src/hooks/useSidebarTopicSearch.ts+++ b/src/hooks/useSidebarTopicSearch.ts@@ -3,7 +3,7 @@ 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+ * drawers, mobile search). Applies the same per-agent "only mine" filter as* the list, so a search never brings back topics the list is hiding. An empty* keyword disables the request.*/diff --git a/src/hooks/useTopicOnlyMine.test.ts b/src/hooks/useTopicOnlyMine.test.tsnew file mode 100644index 00000000000..fbadd94eecf--- /dev/null+++ b/src/hooks/useTopicOnlyMine.test.ts@@ -0,0 +1,79 @@+import { renderHook } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { TopicListScopeContext } from '@/features/AgentSidebar/Topic/TopicListScope';++import { useSetTopicOnlyMine, useTopicOnlyMine, useTopicOnlyMineOwnerId } from './useTopicOnlyMine';++const mocks = vi.hoisted(() => ({+ chat: { activeAgentId: 'agent-1', activeGroupId: undefined as string | undefined },+ global: {+ status: { topicOnlyMineByAgent: {} as Record<string, boolean> },+ updateSystemStatus: vi.fn(),+ },+ hasActiveWorkspace: true,+}));++vi.mock('@/business/client/hooks/useHasActiveWorkspace', () => ({+ useHasActiveWorkspace: () => mocks.hasActiveWorkspace,+}));+vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: typeof mocks.chat) => unknown) => selector(mocks.chat),+}));+vi.mock('@/store/global', () => ({+ useGlobalStore: (selector: (s: typeof mocks.global) => unknown) => selector(mocks.global),+}));++const projectScope = ({ children }: PropsWithChildren) =>+ createElement(TopicListScopeContext, { value: { projectId: 'project-a' } }, children);++describe('useTopicOnlyMine', () => {+ beforeEach(() => {+ mocks.chat.activeAgentId = 'agent-1';+ mocks.chat.activeGroupId = undefined;+ mocks.global.status.topicOnlyMineByAgent = {};+ mocks.global.updateSystemStatus.mockClear();+ mocks.hasActiveWorkspace = true;+ });++ /** @example Turning it on for one agent used to filter every agent in the workspace. */+ it("reads only the active agent's own choice", () => {+ mocks.global.status.topicOnlyMineByAgent = { 'agent-2': true };++ expect(renderHook(() => useTopicOnlyMine()).result.current).toBe(false);++ mocks.chat.activeAgentId = 'agent-2';+ expect(renderHook(() => useTopicOnlyMine()).result.current).toBe(true);+ });++ it('prefers an explicitly named agent over the active one', () => {+ mocks.global.status.topicOnlyMineByAgent = { 'agent-2': true };++ expect(renderHook(() => useTopicOnlyMine('agent-2')).result.current).toBe(true);+ });++ it('is always off in personal mode', () => {+ mocks.global.status.topicOnlyMineByAgent = { 'agent-1': true };+ mocks.hasActiveWorkspace = false;++ expect(renderHook(() => useTopicOnlyMine()).result.current).toBe(false);+ });++ it('keys a project sidebar by project and a group by group', () => {+ mocks.chat.activeGroupId = 'grp-1';+ expect(renderHook(() => useTopicOnlyMineOwnerId()).result.current).toBe('grp-1');+ expect(+ renderHook(() => useTopicOnlyMineOwnerId(), { wrapper: projectScope }).result.current,+ ).toBe('project-a');+ });++ it('stores the choice locally under its owner', () => {+ const { result } = renderHook(() => useSetTopicOnlyMine());+ result.current('agent-1', true);++ expect(mocks.global.updateSystemStatus).toHaveBeenCalledWith({+ topicOnlyMineByAgent: { 'agent-1': true },+ });+ });+});diff --git a/src/hooks/useTopicOnlyMine.ts b/src/hooks/useTopicOnlyMine.tsindex 896d1c7847c..0a53619bd81 100644--- a/src/hooks/useTopicOnlyMine.ts+++ b/src/hooks/useTopicOnlyMine.ts@@ -1,13 +1,41 @@-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { useUserStore } from '@/store/user';-import { workspaceUserSettingsSelectors } from '@/store/user/selectors';+import { useCallback } from 'react';++import { useHasActiveWorkspace } from '@/business/client/hooks/useHasActiveWorkspace';+import { useTopicListScope } from '@/features/AgentSidebar/Topic/TopicListScope';+import { useChatStore } from '@/store/chat';+import { useGlobalStore } from '@/store/global';+import { systemStatusSelectors } from '@/store/global/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.+ * Owner of the topic list on screen, which the "only mine" choice is keyed by:+ * the project of a project sidebar, else the active group, else the active+ * agent.*/-export const useTopicOnlyMine = (): boolean => {- const activeWorkspaceId = useActiveWorkspaceId();- return useUserStore(workspaceUserSettingsSelectors.topicOnlyMine(activeWorkspaceId));+export const useTopicOnlyMineOwnerId = (): string | undefined => {+ const scope = useTopicListScope();+ const [activeAgentId, activeGroupId] = useChatStore((s) => [s.activeAgentId, s.activeGroupId]);+ return scope?.projectId || activeGroupId || activeAgentId || undefined;+};++/**+ * Whether topic lists and searches show only the caller's own topics β a+ * device-local choice each agent (group / project) keeps for itself. Always+ * false in personal mode. Pass `ownerId` when the list names its agent+ * explicitly instead of following the active session.+ */+export const useTopicOnlyMine = (ownerId?: string): boolean => {+ const hasActiveWorkspace = useHasActiveWorkspace();+ const activeOwnerId = useTopicOnlyMineOwnerId();+ const onlyMine = useGlobalStore(systemStatusSelectors.topicOnlyMine(ownerId ?? activeOwnerId));+ return hasActiveWorkspace && onlyMine;+};++/** Writes the "only mine" choice of one topic-list owner. */+export const useSetTopicOnlyMine = () => {+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);+ return useCallback(+ (ownerId: string, onlyMine: boolean) =>+ updateSystemStatus({ topicOnlyMineByAgent: { [ownerId]: onlyMine } }),+ [updateSystemStatus],+ );};diff --git a/src/hooks/useWorkspacePreferenceReady.test.ts b/src/hooks/useWorkspacePreferenceReady.test.tsdeleted file mode 100644index a3bd1b7c0d9..00000000000--- a/src/hooks/useWorkspacePreferenceReady.test.ts+++ /dev/null@@ -1,40 +0,0 @@-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.tsdeleted file mode 100644index b3eb908865d..00000000000--- a/src/hooks/useWorkspacePreferenceReady.ts+++ /dev/null@@ -1,10 +0,0 @@-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/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.tsindex 14e0ba27c0c..05a123e8a04 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts@@ -24,7 +24,6 @@ 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[]> }));@@ -73,12 +72,6 @@ vi.mock('@/store/device', () => ({useDeviceStore: { getState: () => ({ preHydrateDeviceList: preHydrateDeviceListMock }) },}));-vi.mock('@/store/user', () => ({- useUserStore: {- getState: () => ({ preHydrateWorkspaceUserPreference: preHydrateWorkspacePreferenceMock }),- },-}));-vi.mock('@/store/verify', () => ({useVerifyStore: { getState: () => ({ preHydrateVerifyRuns: preHydrateVerifyRunsMock }) },}));@@ -97,59 +90,16 @@ 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 () => {+ /** @example The per-agent "only mine" filter is restored synchronously, so nothing gates the seed. */+ it('seeds the topic page from the derived sidebar params', async () => {await agentChatTopicListLoader(loaderArgs('agt_1'));+ expect(getSidebarTopicListParamsMock).toHaveBeenCalledWith({ agentId: '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(() => {- vi.useRealTimers();- });-- // Without it the input bar's device chip read "Unknown device" until the- // mount-time hydrate (or the network) answered.it('seeds the persisted device list before the route commits', async () => {await agentChatTopicListLoader(loaderArgs('agt_1'));diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.tsindex 245173ccdc7..9249991f832 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts@@ -9,7 +9,6 @@ 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));@@ -40,23 +39,9 @@ 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;-+ // The per-agent "only mine" filter is part of the list identity. It is read+ // from the system status, which restores it synchronously at store creation+ // (`createInitialSystemStatus`), so the params below already carry it.const params = getSidebarTopicListParams({ agentId });if (!params) return;diff --git a/src/store/global/initialState.test.ts b/src/store/global/initialState.test.tsindex 82ce624be20..d424fd9fa97 100644--- a/src/store/global/initialState.test.ts+++ b/src/store/global/initialState.test.ts@@ -40,6 +40,21 @@ describe('createInitialSystemStatus', () => {expect(status.workingSidebarWidth).toBe(480);});+ /** @example A cold reload seeded the unfiltered topic page before the async status restore. */+ it('restores the per-agent only-mine topic filter before the route loader reads it', () => {+ seed({ topicOnlyMineByAgent: { agt_a: true, agt_b: false } });++ expect(createInitialSystemStatus().topicOnlyMineByAgent).toEqual({ agt_a: true, agt_b: false });+ });++ it('drops a malformed persisted only-mine filter', () => {+ seed({ topicOnlyMineByAgent: { agt_a: 'yes', agt_b: true } });+ expect(createInitialSystemStatus().topicOnlyMineByAgent).toEqual({ agt_b: true });++ seed({ topicOnlyMineByAgent: ['agt_a'] });+ expect(createInitialSystemStatus().topicOnlyMineByAgent).toBeUndefined();+ });+it('opens Home in one column for a browser without a stored rail choice', () => {expect(createInitialSystemStatus().showHomeRail).toBe(false);});diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex a4e4426648c..ca558444d61 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -488,6 +488,12 @@ export interface SystemStatus {* Whether to display tokens in short format*/tokenDisplayFormatShort?: boolean;+ /**+ * Workspace "only my topics" filter, keyed by the topic list's owner: the+ * agentId of an agent sidebar, the groupId of a group, the projectId of a+ * project sidebar. Device-local, so each agent keeps its own choice.+ */+ topicOnlyMineByAgent?: Record<string, boolean>;/*** number of topics to display per page*/@@ -678,6 +684,16 @@ export const INITIAL_STATUS = {const statusStorage = new AsyncLocalStorage<SystemStatus>('LOBE_SYSTEM_STATUS');+/** Keeps only `ownerId β boolean` entries of a persisted value of unknown shape. */+const restoreTopicOnlyMineByAgent = (value: unknown): Record<string, boolean> | undefined => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;+ return Object.fromEntries(+ Object.entries(value).filter(+ (entry): entry is [string, boolean] => typeof entry[1] === 'boolean',+ ),+ );+};+/*** Restore the shell-defining preferences before React's first render. The* remaining system status still follows the existing async initialization path,@@ -685,6 +701,10 @@ const statusStorage = new AsyncLocalStorage<SystemStatus>('LOBE_SYSTEM_STATUS');* the boot shell reads them synchronously to draw a shell that lines up with* the real layout, and `NavPanelDraggable` would otherwise size its* pre-hydration placeholder to the default width.+ *+ * The per-agent "only mine" topic filter is restored here too: it is part of+ * the topic list identity, and the route loader seeds that list before the+ * async initialization runs β an unrestored filter seeds the unfiltered page.*/export const createInitialSystemStatus = (): SystemStatus => {const persistedStatus = statusStorage.getFromLocalStorageSync();@@ -714,6 +734,7 @@ export const createInitialSystemStatus = (): SystemStatus => {typeof persistedStatus.showRightPanel === 'boolean'? persistedStatus.showRightPanel: INITIAL_STATUS.showRightPanel,+ topicOnlyMineByAgent: restoreTopicOnlyMineByAgent(persistedStatus.topicOnlyMineByAgent),showWorkingOverview:typeof persistedStatus.showWorkingOverview === 'boolean'? persistedStatus.showWorkingOverviewdiff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.tsindex bf040e25c47..7c3ab976003 100644--- a/src/store/global/selectors/systemStatus.ts+++ b/src/store/global/selectors/systemStatus.ts@@ -120,6 +120,12 @@ const projectSidebarSections =(s: GlobalState): Record<string, boolean> | undefined =>projectId ? s.status.expandProjectSidebarSectionsByProject?.[projectId] : undefined;+/** Whether the topic list owned by `ownerId` (agent / group / project) shows only my topics. */+const topicOnlyMine =+ (ownerId: string | undefined) =>+ (s: GlobalState): boolean =>+ !!ownerId && !!s.status.topicOnlyMineByAgent?.[ownerId];+/** Upper bound of `topic.getTopics`'s `pageSize` input on the server. */export const MAX_TOPIC_PAGE_SIZE = 100;@@ -595,6 +601,7 @@ export const systemStatusSelectors = {tokenDisplayFormatShort,collapsedTopicGroupKeys,projectTopicSubGroupMode,+ topicOnlyMine,topicPageSize,videoPanelWidth,videoTopicViewMode,diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.tsindex 25d47eb1def..1eb938e6be1 100644--- a/src/store/user/slices/workspaceUserSettings/action.ts+++ b/src/store/user/slices/workspaceUserSettings/action.ts@@ -194,25 +194,6 @@ 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 307581b5128..2f1cf73b525 100644--- a/src/store/user/slices/workspaceUserSettings/replica.test.ts+++ b/src/store/user/slices/workspaceUserSettings/replica.test.ts@@ -141,34 +141,6 @@ 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.tsdeleted file mode 100644index 322f16eec06..00000000000--- a/src/store/user/slices/workspaceUserSettings/selectors.test.ts+++ /dev/null@@ -1,24 +0,0 @@-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 cb0a63ab2a8..04011df9e8a 100644--- a/src/store/user/slices/workspaceUserSettings/selectors.ts+++ b/src/store/user/slices/workspaceUserSettings/selectors.ts@@ -50,20 +50,6 @@ 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;@@ -76,5 +62,4 @@ export const workspaceUserSettingsSelectors = {sidebarHiddenAgentIds,sidebarHiddenGroupIds,sidebarLayout,- topicOnlyMine,};diff --git a/src/styles/sx.ts b/src/styles/sx.tsindex 16efbfd1a02..b29aeb558f7 100644--- a/src/styles/sx.ts+++ b/src/styles/sx.ts@@ -1,8 +1,7 @@import * as stylex from '@stylexjs/stylex';+import { type StyleXStyles } from '@stylexjs/stylex';import { type CSSProperties } from 'react';-type StyleArgs = Parameters<typeof stylex.props>;-/*** stylex.props for elements that also forward a caller's className / style, which* spreading stylex.props cannot do (@stylexjs/no-conflicting-props).@@ -12,8 +11,12 @@ type StyleArgs = Parameters<typeof stylex.props>;* The caller's className is appended, not merged: StyleX rules carry raised* specificity, so a plain class cannot override them. Components that let callers* restyle them take an `xstyle?: StyleXStyles` prop and pass it in `styles`.+ *+ * `styles` is typed as `StyleXStyles`, not `Parameters<typeof stylex.props>`:+ * `props` declares a `this` parameter, and the type-check resolves that derived+ * type to `never`, rejecting every call.*/-export const sx = (styles: StyleArgs[number], className?: string, style?: CSSProperties) => {+export const sx = (styles: StyleXStyles, className?: string, style?: CSSProperties) => {const props = stylex.props(styles);const mergedClassName = [props.className, className].filter(Boolean).join(' ');return {