🤯 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: start topics from folder references (#19677)
Arvin Xu17a57f2e7e02
diff --git a/locales/en-US/components.json b/locales/en-US/components.jsonindex 55f550dc33c..838b18f475f 100644--- a/locales/en-US/components.json+++ b/locales/en-US/components.json@@ -129,6 +129,8 @@"LocalFile.action.open": "Open","LocalFile.action.preview": "Preview","LocalFile.action.showInFolder": "Show in Folder",+ "LocalFile.action.startTopic": "Start new topic here",+ "LocalFile.action.startTopicFailed": "Failed to start a new topic in this folder.","MaxTokenSlider.unlimited": "Unlimited","ModelSelect.featureTag.audio": "This model supports audio input recognition.","ModelSelect.featureTag.custom": "Custom model, by default, supports both tool calls and visual recognition. Please verify the availability of the above capabilities based on actual situations.",diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.jsonindex 96026f85b9f..01aefaaee88 100644--- a/locales/zh-CN/components.json+++ b/locales/zh-CN/components.json@@ -129,6 +129,8 @@"LocalFile.action.open": "打开","LocalFile.action.preview": "预览","LocalFile.action.showInFolder": "在文件夹中显示",+ "LocalFile.action.startTopic": "在此目录开启新话题",+ "LocalFile.action.startTopicFailed": "无法在此目录开启新话题。","MaxTokenSlider.unlimited": "无限制","ModelSelect.featureTag.audio": "该模型支持音频输入识别","ModelSelect.featureTag.custom": "自定义模型,默认支持函数调用和视觉识别。请根据实际情况确认上述功能是否可用。",diff --git a/packages/locales/src/default/components.ts b/packages/locales/src/default/components.tsindex d2367180974..bc717b12065 100644--- a/packages/locales/src/default/components.ts+++ b/packages/locales/src/default/components.ts@@ -149,6 +149,8 @@ export default {'LocalFile.action.open': 'Open','LocalFile.action.preview': 'Preview','LocalFile.action.showInFolder': 'Show in Folder',+ 'LocalFile.action.startTopic': 'Start new topic here',+ 'LocalFile.action.startTopicFailed': 'Failed to start a new topic in this folder.','MaxTokenSlider.unlimited': 'Unlimited','ModelSelect.featureTag.audio': 'This model supports audio input recognition.','ModelSelect.featureTag.custom':diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsxindex 9aa20843082..d16d295c0eb 100644--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx@@ -19,6 +19,7 @@ const testState = vi.hoisted(() => ({currentDeviceId: 'this-machine' as string | undefined,effective: {agencyConfig: undefined as Record<string, unknown> | undefined,+ isPreferenceLoading: false,workspaceScoped: false,},}));@@ -69,7 +70,11 @@ describe('useCommitWorkingDirectory — localTarget', () => {testState.chat.topic = undefined;testState.chat.updateTopicMetadata = vi.fn();testState.currentDeviceId = 'this-machine';- testState.effective = { agencyConfig: undefined, workspaceScoped: false };+ testState.effective = {+ agencyConfig: undefined,+ isPreferenceLoading: false,+ workspaceScoped: false,+ };});it('files a workspace member’s first sandbox pick against their own machine', async () => {@@ -81,6 +86,7 @@ describe('useCommitWorkingDirectory — localTarget', () => {testState.agent.agentMap = { 'agent-id': { visibility: 'public', workspaceId: 'ws-1' } };testState.effective = {agencyConfig: { boundDeviceId: 'shared-device', executionTarget: 'device' },+ isPreferenceLoading: false,workspaceScoped: true,};@@ -113,6 +119,7 @@ describe('useCommitWorkingDirectory — localTarget', () => {// the new option cannot change how the directory picker behaves.testState.effective = {agencyConfig: { boundDeviceId: 'other-device', executionTarget: 'device' },+ isPreferenceLoading: false,workspaceScoped: false,};testState.agent.agencyConfig = { boundDeviceId: 'other-device', executionTarget: 'device' };@@ -145,6 +152,7 @@ describe('useCommitWorkingDirectory — topic device provenance', () => {testState.currentDeviceId = 'this-machine';testState.effective = {agencyConfig: { boundDeviceId: 'device-b', executionTarget: 'device' },+ isPreferenceLoading: false,workspaceScoped: false,};});@@ -179,3 +187,51 @@ describe('useCommitWorkingDirectory — topic device provenance', () => {expect(patch.boundDeviceId).toBeUndefined();});});++describe('useCommitWorkingDirectory — commitAgentDefault', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ testState.agent.agencyConfig = undefined;+ testState.agent.agentMap = {};+ testState.agent.localAgentWorkingDirectoryMap = {};+ testState.agent.updateAgentConfigById = vi.fn();+ testState.agent.updateAgentRuntimeEnvConfigById = vi.fn();+ testState.chat.activeTopicId = undefined;+ testState.chat.topic = undefined;+ testState.currentDeviceId = 'this-machine';+ testState.effective = {+ agencyConfig: undefined,+ isPreferenceLoading: false,+ workspaceScoped: false,+ };+ });++ it('forwards save options so callers can observe a failed shared-config write', async () => {+ // The store swallows save failures unless asked to rethrow; a caller that+ // switches topics right after must see the rejection.+ testState.agent.updateAgentConfigById = vi.fn(+ async (_id: string, _patch: unknown, options?: { rethrow?: boolean }) => {+ if (options?.rethrow) throw new Error('save failed');+ },+ );++ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));++ await expect(+ result.current.commitAgentDefault('/work', { rethrow: true, showErrorMessage: false }),+ ).rejects.toThrow('save failed');+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ { agencyConfig: { workingDirByDevice: { 'this-machine': '/work' } } },+ { rethrow: true, showErrorMessage: false },+ );+ });++ it('exposes the workspace preference loading state for writers to wait on', () => {+ testState.effective = { ...testState.effective, isPreferenceLoading: true };++ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));++ expect(result.current.isPreferenceLoading).toBe(true);+ });+});diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex 00efe02120a..5d27def9011 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -31,6 +31,18 @@ export interface CommitWorkingDirectoryOptions {localTarget?: boolean;}+export interface CommitAgentDefaultOptions {+ /**+ * Reject when persisting the shared agent config fails. The store otherwise+ * swallows the error (and rolls the optimistic value back), so a caller that+ * acts on the saved directory right after — e.g. switching to a fresh topic —+ * must opt in to learn the write never landed.+ */+ rethrow?: boolean;+ /** Keep the store's generic save-failure toast. @default true */+ showErrorMessage?: boolean;+}+const normalizeWorkingDirEntry = (entry: WorkingDirEntry): WorkingDirEntry | undefined => {const path = entry.path.trim();if (!path) return undefined;@@ -91,10 +103,11 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string// The EFFECTIVE config (override merged) — only for resolving// which device the cwd write should target, keeping it on the same machine// the picker/GitStatus/`useEffectiveWorkingDirectory` operate on.- const { agencyConfig: effectiveAgencyConfig, workspaceScoped } = useEffectiveAgencyConfig(- agentId,- { topicId: routeTopicId },- );+ const {+ agencyConfig: effectiveAgencyConfig,+ isPreferenceLoading,+ workspaceScoped,+ } = useEffectiveAgencyConfig(agentId, { topicId: routeTopicId });// Heterogeneous CLI agents (Claude Code, Codex, …) store sessions per-cwd, so// their session cwd anchors to the SOURCE repo — a worktree switch (same repo,// different activeWorktree) must NOT change the session cwd or reset the@@ -330,17 +343,21 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string* bakes this value into its own `metadata.workingDirectory` on first send.*/const commitAgentDefault = useCallback(- async (newPath: string) => {+ async (newPath: string, options?: CommitAgentDefaultOptions) => {const path = newPath.trim();if (!path) return;if (targetDeviceId && !isPersonalDeviceTarget) {const prev = agencyConfig?.workingDirByDevice ?? {};- await updateAgentConfigById(agentId, {- agencyConfig: {- ...agencyConfig,- workingDirByDevice: { ...prev, [targetDeviceId]: path },+ await updateAgentConfigById(+ agentId,+ {+ agencyConfig: {+ ...agencyConfig,+ workingDirByDevice: { ...prev, [targetDeviceId]: path },+ },},- });+ options,+ );} else {// No resolvable device (e.g. gateway id unavailable), or a workspace// agent targeting this member's own machine (`isPersonalDeviceTarget`,@@ -378,5 +395,15 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: stringawait run();}, [activeTopic, t, clearCwd]);- return { clear, commit, commitAgentDefault };+ return {+ clear,+ commit,+ commitAgentDefault,+ /**+ * A workspace agent's device routing (shared row vs. this member's personal+ * slot) is still resolving. Writers should wait: acting now can file a local+ * path under the shared device instead of the member's own slot.+ */+ isPreferenceLoading,+ };};diff --git a/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx b/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsxindex 63bd19aae1c..65f629d9802 100644--- a/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx+++ b/src/features/Conversation/Markdown/plugins/LocalFile/Render/index.tsx@@ -3,6 +3,7 @@ import React, { memo } from 'react';import { LocalFile } from '@/features/LocalFile';+import { useStartTopicConversation } from '../../../../hooks/useStartTopicConversation';import { useConversationStore } from '../../../../store';import { type MarkdownElementProps } from '../../type';@@ -22,6 +23,7 @@ const Render = memo<MarkdownElementProps<LocalFileProps>>(({ node }) => {const isSharePage = useConversationStore((s) => !!s.context.topicShareId || !!s.context.agentShareId,);+ const conversation = useStartTopicConversation();if (!name || !path) {// If required properties are missing, render an error or null@@ -32,7 +34,15 @@ const Render = memo<MarkdownElementProps<LocalFileProps>>(({ node }) => {// isDirectory may be true (from plugin) or undefined; ensure it is a booleanconst isDir = isDirectory === true;- return <LocalFile isDirectory={isDir} name={name} path={path} readonly={isSharePage} />;+ return (+ <LocalFile+ conversation={conversation}+ isDirectory={isDir}+ name={name}+ path={path}+ readonly={isSharePage}+ />+ );}, isEqual);export default Render;diff --git a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx b/src/features/Conversation/Messages/User/components/MessageContent.test.tsxindex e33d1409e76..456e8315258 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.test.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.test.tsx@@ -7,6 +7,10 @@ vi.mock('@/features/Conversation/Markdown', () => ({default: ({ children }: any) => <div data-testid="markdown-message">{children}</div>,}));+vi.mock('../../../hooks/useStartTopicConversation', () => ({+ useStartTopicConversation: () => undefined,+}));+vi.mock('../useMarkdown', () => ({useMarkdown: () => ({}),}));diff --git a/src/features/Conversation/Messages/User/components/MessageContent.tsx b/src/features/Conversation/Messages/User/components/MessageContent.tsxindex 86090e30309..c288e37b224 100644--- a/src/features/Conversation/Messages/User/components/MessageContent.tsx+++ b/src/features/Conversation/Messages/User/components/MessageContent.tsx@@ -3,10 +3,12 @@ import { memo, useMemo } from 'react';import CollapsibleContent from '@/components/CollapsibleContent';import MarkdownMessage from '@/features/Conversation/Markdown';+import { StartTopicConversationContext } from '@/features/LocalFile';import { cleanSpeakerTag } from '@/store/chat/utils/cleanSpeakerTag';import { splitReferencedMessage } from '@/store/chat/utils/parseReferencedMessage';import { type UIChatMessage } from '@/types/index';+import { useStartTopicConversation } from '../../../hooks/useStartTopicConversation';import { useMarkdown } from '../useMarkdown';import AudioFileListViewer from './AudioFileListViewer';import FileListViewer from './FileListViewer';@@ -19,6 +21,7 @@ import VideoFileListViewer from './VideoFileListViewer';const UserMessageContent = memo<UIChatMessage>(({ id, content, editorData, imageList, videoList, audioList, fileList, metadata }) => {const markdownProps = useMarkdown(id);+ const startTopicConversation = useStartTopicConversation();const selections = metadata?.contextSelections?.length? metadata.contextSelections: metadata?.pageSelections;@@ -35,7 +38,11 @@ const UserMessageContent = memo<UIChatMessage>(editorData && typeof editorData === 'object' && Object.keys(editorData).length > 0;const textBody = hasEditorData ? (- <RichTextMessage editorState={editorData} />+ // Rich-text folder chips render headlessly, so they receive the+ // conversation through context rather than props.+ <StartTopicConversationContext value={startTopicConversation}>+ <RichTextMessage editorState={editorData} />+ </StartTopicConversationContext>) : (displayContent && <MarkdownMessage {...markdownProps}>{displayContent}</MarkdownMessage>);diff --git a/src/features/Conversation/hooks/useStartTopicConversation.test.ts b/src/features/Conversation/hooks/useStartTopicConversation.test.tsnew file mode 100644index 00000000000..a2ef17ae8b6--- /dev/null+++ b/src/features/Conversation/hooks/useStartTopicConversation.test.ts@@ -0,0 +1,58 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useStartTopicConversation } from './useStartTopicConversation';++const state = vi.hoisted(() => ({ context: {} as Record<string, unknown> }));++vi.mock('../store', () => ({+ useConversationStore: (selector: (s: typeof state) => unknown) => selector(state),+}));++describe('useStartTopicConversation', () => {+ afterEach(() => {+ state.context = {};+ });++ it('returns the agent and topic of a main conversation', () => {+ state.context = { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' };++ const { result } = renderHook(() => useStartTopicConversation());++ expect(result.current).toEqual({ agentId: 'agent-1', topicId: 'topic-1' });+ });++ it('treats a new main topic as the null topic', () => {+ state.context = { agentId: 'agent-1' };++ const { result } = renderHook(() => useStartTopicConversation());++ expect(result.current).toEqual({ agentId: 'agent-1', topicId: null });+ });++ it.each(['page', 'task', 'thread', 'group', 'agent_builder'])(+ 'is unavailable in a %s conversation',+ (scope) => {+ // These conversations own their scope/bucket; the global switchTopic(null)+ // would clear the main chat underneath instead.+ state.context = { agentId: 'agent-1', scope, topicId: 'topic-1' };++ const { result } = renderHook(() => useStartTopicConversation());++ expect(result.current).toBeUndefined();+ },+ );++ it('is unavailable in a group conversation or a share view', () => {+ for (const extra of [{ groupId: 'group-1' }, { topicShareId: 's' }, { agentShareId: 's' }]) {+ state.context = { agentId: 'agent-1', scope: 'main', ...extra };++ const { result } = renderHook(() => useStartTopicConversation());++ expect(result.current).toBeUndefined();+ }+ });+});diff --git a/src/features/Conversation/hooks/useStartTopicConversation.ts b/src/features/Conversation/hooks/useStartTopicConversation.tsnew file mode 100644index 00000000000..e480759a134--- /dev/null+++ b/src/features/Conversation/hooks/useStartTopicConversation.ts@@ -0,0 +1,25 @@+import { useMemo } from 'react';++import type { StartTopicConversation } from '@/features/LocalFile';++import { useConversationStore } from '../store';++/**+ * The conversation a folder reference can start a fresh topic from, or+ * `undefined` when it cannot. Only a single-agent `main` conversation+ * qualifies: starting a topic writes that agent's default directory and then+ * clears the global active topic, which group, page, task, thread or portal+ * conversations (own scope / message bucket) would not follow. Share views+ * are read-only.+ */+export const useStartTopicConversation = (): StartTopicConversation | undefined => {+ const agentId = useConversationStore((s) => {+ const { context } = s;+ const isMain = (context.scope ?? 'main') === 'main';+ if (!isMain || context.groupId || context.topicShareId || context.agentShareId) return;+ return context.agentId || undefined;+ });+ const topicId = useConversationStore((s) => s.context.topicId ?? null);++ return useMemo(() => (agentId ? { agentId, topicId } : undefined), [agentId, topicId]);+};diff --git a/src/features/LocalFile/LocalFile.tsx b/src/features/LocalFile/LocalFile.tsxindex 01b0324a7b0..be66f0d0f3f 100644--- a/src/features/LocalFile/LocalFile.tsx+++ b/src/features/LocalFile/LocalFile.tsx@@ -1,12 +1,15 @@-import { Flexbox, Popover } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';+import { Popover } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';-import { ExternalLink, EyeIcon, FolderOpen } from 'lucide-react';+import { ExternalLink, EyeIcon, FolderOpen, MessageSquarePlus } from 'lucide-react';import React from 'react';import { useTranslation } from 'react-i18next';import FileIcon from '@/components/FileIcon';+import { type StartTopicConversation } from './StartTopicConversation';import { useLocalFileActions } from './useLocalFileActions';+import { useStartTopicInDirectory } from './useStartTopicInDirectory';const styles = createStaticStyles(({ css }) => ({container: css`@@ -95,6 +98,12 @@ const styles = createStaticStyles(({ css }) => ({}));interface LocalFileProps {+ /**+ * The conversation rendering this reference, enabling "start a topic in this+ * folder" for it. Falls back to `StartTopicConversationContext`; absent+ * outside an eligible conversation.+ */+ conversation?: StartTopicConversation;isDirectory?: boolean;name: string;path?: string;@@ -106,6 +115,7 @@ interface LocalFileProps {}export const LocalFile = ({+ conversation,name,path,isDirectory = false,@@ -114,6 +124,12 @@ export const LocalFile = ({const { t } = useTranslation('components');const { canPreview, handleClick, handleOpenFile, handleOpenFolder, handlePreview } =useLocalFileActions({ isDirectory, path, readonly });+ const { canStartTopic, startTopic } = useStartTopicInDirectory({+ conversation,+ isDirectory,+ path,+ readonly,+ });const fileContent = (<Flexbox@@ -144,12 +160,14 @@ export const LocalFile = ({</Flexbox>);- // Directory or readonly mode (e.g. share page): no popover, just display- if (isDirectory || readonly) {+ // Readonly mode (e.g. share page): no popover or local actions.+ if (readonly) {return fileContent;}- // File: show popover with actions+ // Files and directories share the same hover action surface. Directory chips+ // keep their direct click-to-open behavior while exposing the contextual+ // "start topic here" action without adding persistent markdown clutter.const popoverContent = (<div className={styles.segmented}>{canPreview && (@@ -162,10 +180,19 @@ export const LocalFile = ({<ExternalLink size={15} />{t('LocalFile.action.open')}</button>- <button className={styles.segment} type={'button'} onClick={handleOpenFolder}>- <FolderOpen size={15} />- {t('LocalFile.action.showInFolder')}- </button>+ {isDirectory ? (+ canStartTopic && (+ <button className={styles.segment} type={'button'} onClick={() => void startTopic()}>+ <MessageSquarePlus size={15} />+ {t('LocalFile.action.startTopic')}+ </button>+ )+ ) : (+ <button className={styles.segment} type={'button'} onClick={handleOpenFolder}>+ <FolderOpen size={15} />+ {t('LocalFile.action.showInFolder')}+ </button>+ )}</div>);diff --git a/src/features/LocalFile/StartTopicConversation.ts b/src/features/LocalFile/StartTopicConversation.tsnew file mode 100644index 00000000000..143aea4d181--- /dev/null+++ b/src/features/LocalFile/StartTopicConversation.ts@@ -0,0 +1,20 @@+import { createContext } from 'react';++/**+ * The conversation a folder reference was rendered in. "Start a topic in this+ * folder" acts on that conversation only — never on whatever the global+ * active agent/topic happens to be.+ */+export interface StartTopicConversation {+ agentId: string;+ topicId: string | null;+}++/**+ * Supplies the conversation to folder chips that cannot receive it as a prop+ * (e.g. rich-text user messages, whose nodes render headlessly). Absent outside+ * an eligible conversation, which keeps the action hidden.+ */+export const StartTopicConversationContext = createContext<StartTopicConversation | undefined>(+ undefined,+);diff --git a/src/features/LocalFile/index.tsx b/src/features/LocalFile/index.tsxindex b25fb3521ba..ba1d6bb356d 100644--- a/src/features/LocalFile/index.tsx+++ b/src/features/LocalFile/index.tsx@@ -1,2 +1,6 @@export { LocalFile } from './LocalFile';export { LocalFolder } from './LocalFolder';+export {+ type StartTopicConversation,+ StartTopicConversationContext,+} from './StartTopicConversation';diff --git a/src/features/LocalFile/useStartTopicInDirectory.test.ts b/src/features/LocalFile/useStartTopicInDirectory.test.tsnew file mode 100644index 00000000000..84789a39c62--- /dev/null+++ b/src/features/LocalFile/useStartTopicInDirectory.test.ts@@ -0,0 +1,192 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { createElement } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { StartTopicConversationContext } from './StartTopicConversation';+import { useStartTopicInDirectory } from './useStartTopicInDirectory';++const mocks = vi.hoisted(() => ({+ activeAgentId: 'agent-1',+ activeTopicId: 'topic-1' as string | null,+ commitAgentDefault: vi.fn(),+ isPreferenceLoading: false,+ useCommitWorkingDirectory: vi.fn(),+ switchTopic: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...((await importOriginal()) as Record<string, unknown>),+ isDesktop: true,+}));++vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast: { error: mocks.toastError },+}));++vi.mock('@/features/ChatInput/ControlBar/useCommitWorkingDirectory', () => ({+ useCommitWorkingDirectory: (...args: unknown[]) => {+ mocks.useCommitWorkingDirectory(...args);+ return {+ commitAgentDefault: mocks.commitAgentDefault,+ isPreferenceLoading: mocks.isPreferenceLoading,+ };+ },+}));++vi.mock('@/store/agent', () => {+ const getState = () => ({ activeAgentId: mocks.activeAgentId });+ const useAgentStore = (selector: (state: { activeAgentId: string }) => unknown) =>+ selector(getState());+ useAgentStore.getState = getState;+ return { useAgentStore };+});++vi.mock('@/store/chat', () => {+ const getState = () => ({ activeTopicId: mocks.activeTopicId, switchTopic: mocks.switchTopic });+ const useChatStore = (selector: (state: ReturnType<typeof getState>) => unknown) =>+ selector(getState());+ useChatStore.getState = getState;+ return { useChatStore };+});++const renderStartTopic = (params: Partial<Parameters<typeof useStartTopicInDirectory>[0]> = {}) =>+ renderHook(() =>+ useStartTopicInDirectory({+ conversation: { agentId: 'agent-1', topicId: 'topic-1' },+ isDirectory: true,+ path: '/Users/me/Compositor',+ readonly: false,+ ...params,+ }),+ );++describe('useStartTopicInDirectory', () => {+ afterEach(() => {+ vi.clearAllMocks();+ mocks.activeAgentId = 'agent-1';+ mocks.activeTopicId = 'topic-1';+ mocks.isPreferenceLoading = false;+ });++ it('starts a fresh topic after saving the directory as the agent default', async () => {+ mocks.commitAgentDefault.mockResolvedValue(undefined);+ mocks.switchTopic.mockResolvedValue(undefined);+ const { result } = renderStartTopic();++ expect(result.current.canStartTopic).toBe(true);+ await result.current.startTopic();++ // `rethrow` makes a failed save reject instead of being swallowed by the+ // store, so the topic switch below never runs on an unsaved directory.+ expect(mocks.commitAgentDefault).toHaveBeenCalledWith('/Users/me/Compositor', {+ rethrow: true,+ showErrorMessage: false,+ });+ expect(mocks.switchTopic).toHaveBeenCalledWith(null, { skipRefreshMessage: true });+ expect(mocks.commitAgentDefault.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.switchTopic.mock.invocationCallOrder[0]!,+ );+ });++ it('does not leave the current topic when setting the directory fails', async () => {+ mocks.commitAgentDefault.mockRejectedValue(new Error('write failed'));+ const { result } = renderStartTopic();++ await result.current.startTopic();++ expect(mocks.toastError).toHaveBeenCalledWith('LocalFile.action.startTopicFailed');+ expect(mocks.switchTopic).not.toHaveBeenCalled();+ });++ it('stays disabled until workspace preferences resolve the target device', async () => {+ mocks.isPreferenceLoading = true;+ const { result } = renderStartTopic();++ expect(result.current.canStartTopic).toBe(false);+ await result.current.startTopic();++ expect(mocks.commitAgentDefault).not.toHaveBeenCalled();+ expect(mocks.switchTopic).not.toHaveBeenCalled();+ });++ it('is unavailable when the rendering conversation is not the active agent', async () => {+ // e.g. a group chat opened from a task: the global active agent is still the+ // task agent, which must not receive this directory as its default.+ mocks.activeAgentId = 'task-agent';+ const { result } = renderStartTopic({+ conversation: { agentId: 'supervisor-agent', topicId: 'topic-1' },+ });++ expect(result.current.canStartTopic).toBe(false);+ await result.current.startTopic();++ expect(mocks.commitAgentDefault).not.toHaveBeenCalled();+ });++ it('picks the conversation up from context for chips rendered without props', () => {+ // Rich-text user messages render folder chips headlessly — no props.+ const conversation = { agentId: 'agent-1', topicId: 'topic-1' };+ const { result } = renderHook(+ () =>+ useStartTopicInDirectory({+ isDirectory: true,+ path: '/Users/me/Compositor',+ readonly: false,+ }),+ {+ wrapper: ({ children }) =>+ createElement(StartTopicConversationContext, { value: conversation }, children),+ },+ );++ expect(result.current.canStartTopic).toBe(true);+ });++ it('is unavailable outside a conversation', () => {+ const { result } = renderStartTopic({ conversation: undefined });++ expect(result.current.canStartTopic).toBe(false);+ });++ it('is unavailable from a conversation that is not the active topic', () => {+ // e.g. a portal or floating panel showing another topic of the same agent:+ // clearing the global active topic would act on the route, not on it.+ const { result } = renderStartTopic({+ conversation: { agentId: 'agent-1', topicId: 'topic-other' },+ });++ expect(result.current.canStartTopic).toBe(false);+ });++ it('writes the directory for the device a fresh topic will use', () => {+ // A `null` topic keeps the current topic's pinned device from redirecting+ // the write away from the agent's default target.+ renderStartTopic();++ expect(mocks.useCommitWorkingDirectory).toHaveBeenCalledWith('agent-1', null);+ });++ it('keeps a topic the user navigated to while the directory was saving', async () => {+ mocks.commitAgentDefault.mockImplementation(async () => {+ mocks.activeTopicId = 'topic-2';+ });+ const { result } = renderStartTopic();++ await result.current.startTopic();++ expect(mocks.commitAgentDefault).toHaveBeenCalled();+ expect(mocks.switchTopic).not.toHaveBeenCalled();+ expect(mocks.toastError).not.toHaveBeenCalled();+ });++ it('disables the action for shared directory references', () => {+ const { result } = renderStartTopic({ readonly: true });++ expect(result.current.canStartTopic).toBe(false);+ });+});diff --git a/src/features/LocalFile/useStartTopicInDirectory.ts b/src/features/LocalFile/useStartTopicInDirectory.tsnew file mode 100644index 00000000000..082c2895aed--- /dev/null+++ b/src/features/LocalFile/useStartTopicInDirectory.ts@@ -0,0 +1,86 @@+import { isDesktop } from '@lobechat/const';+import { toast } from '@lobehub/ui/base-ui';+import { use } from 'react';+import { useTranslation } from 'react-i18next';++import { useCommitWorkingDirectory } from '@/features/ChatInput/ControlBar/useCommitWorkingDirectory';+import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';++import {+ type StartTopicConversation,+ StartTopicConversationContext,+} from './StartTopicConversation';++interface UseStartTopicInDirectoryParams {+ /**+ * The conversation that rendered the reference (falls back to+ * `StartTopicConversationContext`). The action is only offered+ * while it is the active main conversation (same agent and topic): the global+ * `activeAgentId` can point at another agent (e.g. a task agent while a group+ * chat is shown), and `switchTopic` acts on the active conversation only.+ */+ conversation?: StartTopicConversation;+ isDirectory: boolean;+ path?: string;+ readonly: boolean;+}++export const useStartTopicInDirectory = ({+ conversation: conversationProp,+ isDirectory,+ path,+ readonly,+}: UseStartTopicInDirectoryParams) => {+ const { t } = useTranslation('components');+ // Rich-text folder chips render headlessly and cannot receive props, so they+ // pick the conversation up from context instead.+ const conversationFromContext = use(StartTopicConversationContext);+ const conversation = conversationProp ?? conversationFromContext;+ const activeAgentId = useAgentStore((s) => s.activeAgentId);+ const activeTopicId = useChatStore((s) => s.activeTopicId ?? null);+ const isActiveConversation =+ !!conversation &&+ conversation.agentId === activeAgentId &&+ conversation.topicId === activeTopicId;+ // `null` topic: resolve the device the FRESH topic will run on (the agent's+ // default target), not the current topic's pinned machine — otherwise the+ // directory lands under a device the new topic never reads.+ const { commitAgentDefault, isPreferenceLoading } = useCommitWorkingDirectory(+ conversation?.agentId ?? '',+ null,+ );+ const switchTopic = useChatStore((s) => s.switchTopic);+ // Wait for a workspace agent's preference fetch: until it settles the write+ // may route to the workspace-shared device instead of this member's own slot.+ const canStartTopic =+ isDesktop && isDirectory && !readonly && !!path && isActiveConversation && !isPreferenceLoading;++ const startTopic = async () => {+ if (!canStartTopic || !path) return;++ // Capture where the click came from: the save can be slow, and the user may+ // move to another agent/topic meanwhile — clearing that selection would+ // discard what they navigated to.+ const originAgentId = useAgentStore.getState().activeAgentId;+ const originTopicId = useChatStore.getState().activeTopicId;++ try {+ // Rethrow so a failed save keeps the user on the current topic instead of+ // opening a fresh one without the chosen directory; the toast below+ // replaces the store's generic save-failure message.+ await commitAgentDefault(path, { rethrow: true, showErrorMessage: false });++ const stillOnOrigin =+ useAgentStore.getState().activeAgentId === originAgentId &&+ useChatStore.getState().activeTopicId === originTopicId;+ if (!stillOnOrigin) return;++ await switchTopic(null, { skipRefreshMessage: true });+ } catch {+ toast.error(t('LocalFile.action.startTopicFailed'));+ }+ };++ return { canStartTopic, startTopic };+};