π€― 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
π fix(task): show file previews inside the run drawer and add open-in-browser (#23360)
Rdmclin211331ee77cce
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsxindex bc2617ab799..c62517014ff 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx@@ -15,14 +15,22 @@ const mocks = vi.hoisted(() => ({agentMap: {},useHydrateAgentConfig: vi.fn(),},+ appOrigin: 'https://app.example.com',chatState: {closeArtifact: vi.fn(),+ closeFilePreview: vi.fn(),clearPortalStack: vi.fn(),dbMessagesMap: {'topic-chat-key': [{ id: 'message-1' }],} as Record<string, { id: string }[]>,messagesMap: {} as Record<string, { id: string }[]>,- portalStack: [] as { artifact?: { id: string }; taskId?: string; type: string }[],+ portalStack: [] as {+ artifact?: { id: string };+ file?: { fileId: string };+ sourceTopicId?: string;+ taskId?: string;+ type: string;+ }[],replaceMessages: vi.fn(),showPortal: false,topicDataMap: {},@@ -33,6 +41,8 @@ const mocks = vi.hoisted(() => ({reason: 'requires member',},navigate: vi.fn(),+ openTrustedExternalUrl: vi.fn(),+ workspaceSlug: undefined as string | undefined,serverConfigState: {serverConfig: {enableBusinessFeatures: false,@@ -207,6 +217,18 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({useWorkspaceAwareNavigate: () => mocks.navigate,}));+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ useActiveWorkspaceSlug: () => mocks.workspaceSlug,+}));++vi.mock('@/hooks/useAppOrigin', () => ({+ useAppOrigin: () => mocks.appOrigin,+}));++vi.mock('@/utils/openTrustedExternalUrl', () => ({+ openTrustedExternalUrl: mocks.openTrustedExternalUrl,+}));+vi.mock('@/hooks/useGatewayReconnect', () => ({useGatewayReconnect: vi.fn(),}));@@ -277,12 +299,19 @@ describe('TopicChatDrawer', () => {mocks.chatState.closeArtifact.mockImplementation(() => {mocks.chatState.portalStack = mocks.chatState.portalStack.slice(0, -1);});+ mocks.chatState.closeFilePreview.mockClear();+ mocks.chatState.closeFilePreview.mockImplementation(() => {+ mocks.chatState.portalStack = mocks.chatState.portalStack.slice(0, -1);+ });mocks.chatState.clearPortalStack.mockClear();mocks.chatState.clearPortalStack.mockImplementation(() => {mocks.chatState.portalStack = [];mocks.chatState.showPortal = false;});mocks.navigate.mockClear();+ mocks.openTrustedExternalUrl.mockClear();+ mocks.appOrigin = 'https://app.example.com';+ mocks.workspaceSlug = undefined;mocks.taskState.closeTopicDrawer.mockClear();mocks.taskState.activeTopicDrawerFocusRequest = undefined;mocks.taskState.activeTopicDrawerTopicId = 'topic-1';@@ -573,6 +602,72 @@ describe('TopicChatDrawer', () => {expect(mocks.taskState.closeTopicDrawer).not.toHaveBeenCalled();});+ it('shows a file preview opened from its run inside the drawer instead of behind it', () => {+ mocks.chatState.portalStack = [+ { file: { fileId: 'file_1' }, sourceTopicId: 'topic-1', type: 'filePreview' },+ ];+ mocks.chatState.showPortal = true;++ const view = render(<TopicChatDrawer />);++ expect(view.getByTestId('artifact-portal')).toBeInTheDocument();+ expect(view.queryByTestId('chat-list')).not.toBeInTheDocument();++ fireEvent.click(view.getByTestId('artifact-portal'));+ expect(mocks.chatState.closeFilePreview).toHaveBeenCalledOnce();+ expect(mocks.chatState.closeArtifact).not.toHaveBeenCalled();+ expect(mocks.taskState.closeTopicDrawer).not.toHaveBeenCalled();+ });++ it('closes its file preview together with the drawer', () => {+ mocks.chatState.portalStack = [+ { file: { fileId: 'file_1' }, sourceTopicId: 'topic-1', type: 'filePreview' },+ ];+ mocks.chatState.showPortal = true;++ const view = render(<TopicChatDrawer />);+ fireEvent.click(view.getByTestId('panel-close-icon'));++ expect(mocks.chatState.closeFilePreview).toHaveBeenCalledOnce();+ expect(mocks.taskState.closeTopicDrawer).toHaveBeenCalledOnce();+ });++ it.each([+ ['another topic', 'topic-2'],+ ['no conversation', undefined],+ ])('leaves a file preview opened from %s to the page portal', (_, sourceTopicId) => {+ mocks.chatState.portalStack = [+ { file: { fileId: 'file_1' }, sourceTopicId, type: 'filePreview' },+ ];+ mocks.chatState.showPortal = true;++ const view = render(<TopicChatDrawer />);++ expect(view.getByTestId('chat-list')).toBeInTheDocument();+ expect(view.queryByTestId('artifact-portal')).not.toBeInTheDocument();++ fireEvent.click(view.getByTestId('panel-close-icon'));+ expect(mocks.chatState.closeFilePreview).not.toHaveBeenCalled();+ });++ it('opens the run conversation in the browser', () => {+ mocks.workspaceSlug = 'acme';+ const view = render(<TopicChatDrawer />);++ fireEvent.click(view.getByTitle('report.actions.openInBrowser'));++ expect(mocks.openTrustedExternalUrl).toHaveBeenCalledWith(+ 'https://app.example.com/acme/agent/agt_assignee/topic-1',+ );+ });++ it('disables open in browser without an app origin', () => {+ mocks.appOrigin = '';+ const view = render(<TopicChatDrawer />);++ expect(view.getByTitle('report.actions.openInBrowser')).toBeDisabled();+ });+it('uses a resizable bottom-right floating panel', () => {const { getByTestId } = render(<TopicChatDrawer />);diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsxindex 1da382eff4e..c254445e683 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.tsx@@ -28,6 +28,7 @@ import {import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import ChatList from '@/features/Conversation/ChatList';import { ConversationProvider } from '@/features/Conversation/ConversationProvider';import { TaskCardScopeProvider } from '@/features/Conversation/Markdown/plugins/Task';@@ -36,11 +37,14 @@ import { PortalContent } from '@/features/Portal/router';import { useShareModal } from '@/features/ShareModal';import { LazySharePopover as SharePopover } from '@/features/SharePopover/lazy';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';+import { useAppOrigin } from '@/hooks/useAppOrigin';import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';import { useOperationState } from '@/hooks/useOperationState';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';import { useServerConfigStore } from '@/store/serverConfig';import { serverConfigSelectors } from '@/store/serverConfig/selectors';import { useTaskStore } from '@/store/task';@@ -49,6 +53,7 @@ import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';import { electronStylish } from '@/styles/electron';import { isForbiddenError } from '@/utils/forbiddenError';+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';import AssigneeAvatar from '../../features/AssigneeAvatar';import { useTopicDrawerArtifactPortal } from '../../hooks/useTopicDrawerArtifactPortal';@@ -170,7 +175,7 @@ export interface TopicChatDrawerProps {}const TopicChatDrawer = memo<TopicChatDrawerProps>(({ defaultExpanded = false }) => {- const { t } = useTranslation(['chat', 'common']);+ const { t } = useTranslation(['chat', 'common', 'verify']);const navigate = useWorkspaceAwareNavigate();const [expanded, setExpanded] = useState(defaultExpanded);const topicId = useTaskStore(taskDetailSelectors.activeTopicDrawerTopicId);@@ -185,14 +190,18 @@ const TopicChatDrawer = memo<TopicChatDrawerProps>(({ defaultExpanded = false })const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);const showArtifactPortal = useTopicDrawerArtifactPortal();const closeArtifact = useChatStore((s) => s.closeArtifact);-- // The portal state is global: an artifact left open when this drawer closes- // would make the next opening of the same topic land on the artifact instead- // of the conversation, so the drawer takes its artifact down with it.+ const closeFilePreview = useChatStore((s) => s.closeFilePreview);+ const isFilePreview = useChatStore(chatPortalSelectors.showFilePreview);+ // The drawer hosts either an artifact or a file preview opened from its run.+ const closeHostedPortal = isFilePreview ? closeFilePreview : closeArtifact;++ // The portal state is global: an artifact or preview left open when this+ // drawer closes would make the next opening of the same topic land on it+ // instead of the conversation, so the drawer takes it down with it.const handleClose = useCallback(() => {- if (showArtifactPortal) closeArtifact();+ if (showArtifactPortal) closeHostedPortal();closeTopicDrawer();- }, [closeArtifact, closeTopicDrawer, showArtifactPortal]);+ }, [closeHostedPortal, closeTopicDrawer, showArtifactPortal]);// A request to write ("Continue chat") needs the conversation and its// composer. Each request is handled once, so an artifact the user opens@@ -201,11 +210,13 @@ const TopicChatDrawer = memo<TopicChatDrawerProps>(({ defaultExpanded = false })useEffect(() => {if (!inputFocusRequest || inputFocusRequest === handledFocusRequestRef.current) return;handledFocusRequestRef.current = inputFocusRequest;- if (showArtifactPortal) closeArtifact();- }, [closeArtifact, inputFocusRequest, showArtifactPortal]);+ if (showArtifactPortal) closeHostedPortal();+ }, [closeHostedPortal, inputFocusRequest, showArtifactPortal]);const enableTopicLinkShare = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);const { allowed: canShare, reason } = usePermission('edit_own_content');const { allowed: canEditTask } = usePermission('create_content');+ const appOrigin = useAppOrigin();+ const activeWorkspaceSlug = useActiveWorkspaceSlug();// Hydrate task detail when the drawer is opened outside of TaskDetailPage// (e.g. from a brief on home) so the header has agentId / status / seq.@@ -227,6 +238,13 @@ const TopicChatDrawer = memo<TopicChatDrawerProps>(({ defaultExpanded = false }));const { openShareModal } = useShareModal({ context: shareContext });+ // Without an origin the URL is relative β the system browser has nothing to+ // resolve it against.+ const topicPageUrl =+ appOrigin && agentId && topicId+ ? `${appOrigin}${buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(agentId, topicId), activeWorkspaceSlug)}`+ : undefined;+const handleCopyTopicId = useCallback(() => {if (topicId) void copyToClipboard(topicId);}, [topicId]);@@ -387,6 +405,16 @@ const TopicChatDrawer = memo<TopicChatDrawerProps>(({ defaultExpanded = false })) : (shareIcon)}+ <ActionIcon+ disabled={!topicPageUrl}+ icon={ExternalLink}+ size={SHARE_ICON_SIZE}+ title={t('report.actions.openInBrowser', { ns: 'verify' })}+ onClick={() => {+ if (!topicPageUrl) return;+ openTrustedExternalUrl(topicPageUrl);+ }}+ /></Flexbox>);@@ -430,7 +458,7 @@ const TopicChatDrawer = memo<TopicChatDrawerProps>(({ defaultExpanded = false }){open &&(showArtifactPortal ? (<Flexbox height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}>- <PortalContent onClose={closeArtifact} />+ <PortalContent onClose={closeHostedPortal} /></Flexbox>) : (<TopicChatDrawerBodydiff --git a/src/features/AgentTasks/hooks/useTopicDrawerArtifactPortal.test.ts b/src/features/AgentTasks/hooks/useTopicDrawerArtifactPortal.test.tsindex 6eb7dd72644..2e95723fce3 100644--- a/src/features/AgentTasks/hooks/useTopicDrawerArtifactPortal.test.ts+++ b/src/features/AgentTasks/hooks/useTopicDrawerArtifactPortal.test.ts@@ -37,4 +37,24 @@ describe('resolveTopicDrawerPortalHostViewType', () => {}),).toBe(PortalViewType.Artifact);});++ it('keeps the parent task portal mounted while its drawer owns a file preview', () => {+ expect(+ resolveTopicDrawerPortalHostViewType({+ currentViewType: PortalViewType.FilePreview,+ parentViewType: PortalViewType.TaskDetail,+ showArtifactPortal: true,+ }),+ ).toBe(PortalViewType.TaskDetail);+ });++ it('does not reroute views the drawer never hosts', () => {+ expect(+ resolveTopicDrawerPortalHostViewType({+ currentViewType: PortalViewType.Document,+ parentViewType: PortalViewType.TaskDetail,+ showArtifactPortal: true,+ }),+ ).toBe(PortalViewType.Document);+ });});diff --git a/src/features/AgentTasks/hooks/useTopicDrawerArtifactPortal.ts b/src/features/AgentTasks/hooks/useTopicDrawerArtifactPortal.tsindex a3ab6cfb6b3..37a93668a02 100644--- a/src/features/AgentTasks/hooks/useTopicDrawerArtifactPortal.ts+++ b/src/features/AgentTasks/hooks/useTopicDrawerArtifactPortal.ts@@ -7,6 +7,12 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useTaskStore } from '@/store/task';import { taskDetailSelectors } from '@/store/task/selectors';+/** Portal views the run drawer can host in place of its conversation. */+const DRAWER_HOSTED_VIEW_TYPES = new Set<PortalViewType>([+ PortalViewType.Artifact,+ PortalViewType.FilePreview,+]);+interface ResolveTopicDrawerPortalHostViewTypeOptions {currentViewType: PortalViewType | null;parentViewType: PortalViewType | null;@@ -20,7 +26,8 @@ export const resolveTopicDrawerPortalHostViewType = ({}: ResolveTopicDrawerPortalHostViewTypeOptions): PortalViewType | null => {if (showArtifactPortal &&- currentViewType === PortalViewType.Artifact &&+ currentViewType &&+ DRAWER_HOSTED_VIEW_TYPES.has(currentViewType) &&(parentViewType === PortalViewType.TaskDetail || parentViewType === PortalViewType.TaskResult)) {return parentViewType;@@ -30,7 +37,10 @@ export const resolveTopicDrawerPortalHostViewType = ({};/**- * Whether the visible artifact belongs to the conversation hosted by the open run drawer.+ * Whether the visible portal view was opened from the conversation hosted by+ * the open run drawer: an artifact from one of its messages, or a file preview+ * opened from it. The drawer floats over the page's portal host, so these+ * render inside the drawer instead of behind it.*/export const useTopicDrawerArtifactPortal = () => {const [topicId, agentId] = useTaskStore((s) => [@@ -45,13 +55,12 @@ export const useTopicDrawerArtifactPortal = () => {}, [agentId, topicId]);return useChatStore((s) => {- if (- !chatKey ||- !chatPortalSelectors.showStandalonePortal(s) ||- !chatPortalSelectors.showArtifactUI(s)- ) {- return false;- }+ if (!chatKey || !chatPortalSelectors.showStandalonePortal(s)) return false;++ if (chatPortalSelectors.showFilePreview(s))+ return chatPortalSelectors.previewFileSourceTopicId(s) === topicId;++ if (!chatPortalSelectors.showArtifactUI(s)) return false;const artifactMessageId = chatPortalSelectors.artifactMessageId(s);if (!artifactMessageId) return false;diff --git a/src/features/Conversation/Markdown/plugins/FileLink/Render.test.tsx b/src/features/Conversation/Markdown/plugins/FileLink/Render.test.tsxnew file mode 100644index 00000000000..49a12e9cde1--- /dev/null+++ b/src/features/Conversation/Markdown/plugins/FileLink/Render.test.tsx@@ -0,0 +1,79 @@+import { fireEvent, render } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import Render from './Render';++const mocks = vi.hoisted(() => ({+ copyToClipboard: vi.fn(async () => {}),+ openFilePreview: vi.fn(),+ openTrustedExternalUrl: vi.fn(),+}));++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ copyToClipboard: mocks.copyToClipboard,+ toast: { success: vi.fn() },+}));++vi.mock('@/utils/openTrustedExternalUrl', () => ({+ openTrustedExternalUrl: mocks.openTrustedExternalUrl,+}));++vi.mock('../../../hooks/useOpenConversationFilePreview', () => ({+ useOpenConversationFilePreview: () => mocks.openFilePreview,+}));++vi.mock('../../../store', () => ({+ useConversationStore: (selector: (s: unknown) => unknown) =>+ selector({ context: { agentId: 'agt_1', topicId: 'tpc_1' } }),+}));++vi.mock('@/store/file', () => ({+ useFileStore: (selector: (s: unknown) => unknown) =>+ selector({ useFetchKnowledgeItem: () => ({ data: { name: 'after-compact.png' } }) }),+}));++const renderLink = () =>+ render(+ <Render+ node={{+ properties: {+ fileId: 'file_1',+ linkHref: '/resource/file/file_1',+ linkLabel: 'after-compact.png',+ linkScope: 'active',+ },+ }}+ />,+ );++describe('FileLink Render', () => {+ beforeEach(() => {+ mocks.copyToClipboard.mockClear();+ mocks.openFilePreview.mockClear();+ mocks.openTrustedExternalUrl.mockClear();+ });++ it('opens the file address in the browser from the action beside the link', () => {+ const view = renderLink();++ fireEvent.click(view.getByTitle('report.actions.openInBrowser'));++ expect(mocks.openTrustedExternalUrl).toHaveBeenCalledWith(+ `${window.location.origin}/resource/file/file_1`,+ );+ expect(mocks.openFilePreview).not.toHaveBeenCalled();+ });++ it('keeps the copy action copying the same address', async () => {+ const view = renderLink();++ fireEvent.click(view.getByTitle('copy'));++ await vi.waitFor(() =>+ expect(mocks.copyToClipboard).toHaveBeenCalledWith(+ `${window.location.origin}/resource/file/file_1`,+ ),+ );+ });+});diff --git a/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/FileLink/Render.tsxindex d2e8df3e292..ef92d7e4853 100644--- a/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx+++ b/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx@@ -5,18 +5,19 @@ import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';import { A, copyToClipboard, Icon, toast } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { CopyIcon } from 'lucide-react';+import { CopyIcon, ExternalLinkIcon } from 'lucide-react';import type { MouseEvent } from 'react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import FileIcon from '@/components/FileIcon';import { EntityLinkRender, parseLobeLink } from '@/features/EntityLink';-import { useChatStore } from '@/store/chat';import { useElectronStore } from '@/store/electron';import { electronSyncSelectors } from '@/store/electron/selectors';import { useFileStore } from '@/store/file';+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';+import { useOpenConversationFilePreview } from '../../../hooks/useOpenConversationFilePreview';import { useConversationStore } from '../../../store';import type { MarkdownElementProps } from '../type';import { fileLinkMarker } from './markers.stylex';@@ -54,7 +55,7 @@ const stylesAtomic = stylex.create({outlineColor: { 'default': null, ':focus-visible': cssVar.colorPrimaryBorder },outlineOffset: { 'default': null, ':focus-visible': '2px' },},- copy: {+ action: {cursor: 'pointer',display: 'inline-flex',alignItems: 'center',@@ -123,25 +124,32 @@ OwnedFileLabel.displayName = 'FileLinkOwnedFileLabel';const Render = memo<MarkdownElementProps<FileLinkProperties>>(({ node }) => {const { fileId, linkHref, linkLabel, linkScope, proxyHref } = node?.properties || {};- const openFilePreview = useChatStore((s) => s.openFilePreview);+ const openFilePreview = useOpenConversationFilePreview();// A share reader previews and copies the public proxy, not the owner's page.const isShareVisitor = useConversationStore((s) => isShareVisitorContext(s.context));const { t } = useTranslation('common');+ const { t: tVerify } = useTranslation('verify');const label = linkLabel || linkHref || '';const isBareLink = !linkLabel || linkLabel === linkHref || linkLabel === fileId;const targetHref = getFileLinkTargetHref({ isShareVisitor, linkHref, proxyHref });+ // The absolute address both the copy and the open-in-browser actions use.+ const getAbsoluteHref = useCallback(+ () => getFileLinkCopyHref({ isShareVisitor, linkHref, origin: getAppOrigin(), proxyHref }),+ [isShareVisitor, linkHref, proxyHref],+ );+const handleCopy = useCallback(async () => {- const href = getFileLinkCopyHref({- isShareVisitor,- linkHref,- origin: getAppOrigin(),- proxyHref,- });+ const href = getAbsoluteHref();if (!href) return;await copyToClipboard(href);toast.success(t('copySuccess'));- }, [isShareVisitor, linkHref, proxyHref, t]);+ }, [getAbsoluteHref, t]);++ const handleOpenInBrowser = useCallback(() => {+ const href = getAbsoluteHref();+ if (href) openTrustedExternalUrl(href);+ }, [getAbsoluteHref]);const handleClick = useCallback((event: MouseEvent<HTMLAnchorElement>) => {@@ -195,15 +203,28 @@ const Render = memo<MarkdownElementProps<FileLinkProperties>>(({ node }) => {)}</A>{targetHref && (- <button- aria-label={t('copy')}- {...stylex.props(stylesAtomic['copy'])}- title={t('copy')}- type={'button'}- onClick={handleCopy}- >- <Icon icon={CopyIcon} size={12} />- </button>+ <>+ <button+ aria-label={t('copy')}+ {...stylex.props(stylesAtomic['action'])}+ title={t('copy')}+ type={'button'}+ onClick={handleCopy}+ >+ <Icon icon={CopyIcon} size={12} />+ </button>+ {/* Outside the anchor: the desktop preload claims clicks via+ `closest('a')`, so a nested button would never fire. */}+ <button+ aria-label={tVerify('report.actions.openInBrowser')}+ {...stylex.props(stylesAtomic['action'])}+ title={tVerify('report.actions.openInBrowser')}+ type={'button'}+ onClick={handleOpenInBrowser}+ >+ <Icon icon={ExternalLinkIcon} size={12} />+ </button>+ </>)}</>);diff --git a/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx b/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsxindex 7813dbe25a9..b38f2ec9928 100644--- a/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx+++ b/src/features/Conversation/Messages/components/FileChunks/ChunkItem.tsx@@ -5,8 +5,8 @@ import { memo } from 'react';import FileIcon from '@/components/FileIcon';import { useIsDark } from '@/hooks/useIsDark';-import { useChatStore } from '@/store/chat';+import { useOpenConversationFilePreview } from '../../../hooks/useOpenConversationFilePreview';import { styles } from './style';export interface ChunkItemProps extends ChatFileChunk {@@ -15,8 +15,7 @@ export interface ChunkItemProps extends ChatFileChunk {const ChunkItem = memo<ChunkItemProps>(({ id, fileId, similarity, text, filename, fileType }) => {const isDarkMode = useIsDark();- // Note: openFilePreview is a portal action, kept in ChatStore as it's a global UI state- const openFilePreview = useChatStore((s) => s.openFilePreview);+ const openFilePreview = useOpenConversationFilePreview();return (<Flexboxdiff --git a/src/features/Conversation/hooks/useOpenConversationFilePreview.test.ts b/src/features/Conversation/hooks/useOpenConversationFilePreview.test.tsnew file mode 100644index 00000000000..982fcfa0ba6--- /dev/null+++ b/src/features/Conversation/hooks/useOpenConversationFilePreview.test.ts@@ -0,0 +1,52 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useOpenConversationFilePreview } from './useOpenConversationFilePreview';++const mocks = vi.hoisted(() => ({+ context: { isolatedTopic: false, topicId: 'topic-1' } as {+ isolatedTopic?: boolean;+ topicId?: string | null;+ },+ openFilePreview: vi.fn(),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: { openFilePreview: typeof mocks.openFilePreview }) => unknown) =>+ selector({ openFilePreview: mocks.openFilePreview }),+}));++vi.mock('../store', () => ({+ useConversationStore: (selector: (s: { context: typeof mocks.context }) => unknown) =>+ selector({ context: mocks.context }),+}));++describe('useOpenConversationFilePreview', () => {+ beforeEach(() => {+ mocks.openFilePreview.mockClear();+ });++ it('tags a preview opened from an isolated topic with that topic', () => {+ mocks.context = { isolatedTopic: true, topicId: 'topic-1' };+ const { result } = renderHook(() => useOpenConversationFilePreview());++ result.current({ fileId: 'file_1' });++ expect(mocks.openFilePreview).toHaveBeenCalledWith(+ { fileId: 'file_1' },+ { sourceTopicId: 'topic-1' },+ );+ });++ it('leaves previews from the main conversation untagged', () => {+ mocks.context = { isolatedTopic: false, topicId: 'topic-1' };+ const { result } = renderHook(() => useOpenConversationFilePreview());++ result.current({ fileId: 'file_1' });++ expect(mocks.openFilePreview).toHaveBeenCalledWith(+ { fileId: 'file_1' },+ { sourceTopicId: undefined },+ );+ });+});diff --git a/src/features/Conversation/hooks/useOpenConversationFilePreview.ts b/src/features/Conversation/hooks/useOpenConversationFilePreview.tsnew file mode 100644index 00000000000..9984c6822b5--- /dev/null+++ b/src/features/Conversation/hooks/useOpenConversationFilePreview.ts@@ -0,0 +1,32 @@+import { useCallback } from 'react';++import { useChatStore } from '@/store/chat';+import { type PortalFile } from '@/store/chat/slices/portal/initialState';++import { useConversationStore } from '../store';++/**+ * Opens a file preview tagged with the isolated conversation it came from.+ *+ * Use when:+ * - A message inside a conversation opens a file in the portal.+ *+ * Expects:+ * - To render inside a `ConversationProvider`.+ *+ * Returns:+ * - A preview opener. Inside an isolated Topic (the Task run drawer) the+ * preview carries that Topic, so the drawer shows it in place instead of in+ * a page portal the floating drawer would cover.+ */+export const useOpenConversationFilePreview = () => {+ const openFilePreview = useChatStore((s) => s.openFilePreview);+ const sourceTopicId = useConversationStore((s) =>+ s.context.isolatedTopic ? (s.context.topicId ?? undefined) : undefined,+ );++ return useCallback(+ (file: PortalFile) => openFilePreview(file, { sourceTopicId }),+ [openFilePreview, sourceTopicId],+ );+};diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex c61a82bb683..297314dea5c 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -519,8 +519,12 @@ export class ChatPortalActionImpl {this.#get().pushPortalView({ ...params, type: PortalViewType.MemoryDetail });};- openFilePreview = (file: PortalFile): void => {- this.#get().pushPortalView({ file, type: PortalViewType.FilePreview });+ openFilePreview = (file: PortalFile, options?: { sourceTopicId?: string }): void => {+ this.#get().pushPortalView({+ file,+ ...(options?.sourceTopicId ? { sourceTopicId: options.sourceTopicId } : {}),+ type: PortalViewType.FilePreview,+ });};openLocalFile = ({diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex 35438641478..d9139b41fb6 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -123,7 +123,16 @@ export type PortalViewData =| { runId?: string; type: PortalViewType.DashboardWidget; widgetId: string }| { agentDocumentId?: string; documentId: string; type: PortalViewType.Document }| { type: PortalViewType.Notebook }- | { file: PortalFile; type: PortalViewType.FilePreview }+ | {+ file: PortalFile;+ /**+ * The isolated conversation Topic whose message opened this preview. A+ * floating host (the Task run drawer) shows its own previews in place+ * instead of in a page portal it would cover.+ */+ sourceTopicId?: string;+ type: PortalViewType.FilePreview;+ }| { type: PortalViewType.LocalFile }/** `id` is the layer-specific row id (e.g. a preference id), not the base memory id. */| { id: string; layer: LayersEnum; type: PortalViewType.MemoryDetail }diff --git a/src/store/chat/slices/portal/openFilePreview.test.ts b/src/store/chat/slices/portal/openFilePreview.test.tsnew file mode 100644index 00000000000..5e0b083c636--- /dev/null+++ b/src/store/chat/slices/portal/openFilePreview.test.ts@@ -0,0 +1,36 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++import { PortalViewType } from './initialState';++describe('openFilePreview', () => {+ it('tags the preview with the conversation topic that opened it', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.clearPortalStack();+ result.current.openFilePreview({ fileId: 'file_1' }, { sourceTopicId: 'topic-1' });+ });++ expect(chatPortalSelectors.previewFileId(result.current)).toBe('file_1');+ expect(chatPortalSelectors.previewFileSourceTopicId(result.current)).toBe('topic-1');+ });++ it('leaves the source topic unset when opened outside a conversation', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.clearPortalStack();+ result.current.openFilePreview({ fileId: 'file_2' });+ });++ expect(result.current.portalStack.at(-1)).toEqual({+ file: { fileId: 'file_2' },+ type: PortalViewType.FilePreview,+ });+ expect(chatPortalSelectors.previewFileSourceTopicId(result.current)).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex 18e82781288..10101b01178 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -163,6 +163,8 @@ const currentFile = (s: ChatStoreState): PortalFile | undefined => {const previewFileId = (s: ChatStoreState) => currentFile(s)?.fileId;const chunkText = (s: ChatStoreState) => currentFile(s)?.chunkText;const previewFileSource = (s: ChatStoreState) => currentFile(s)?.source;+const previewFileSourceTopicId = (s: ChatStoreState) =>+ getViewData(s, PortalViewType.FilePreview)?.sourceTopicId;// Local File selectorsconst currentLocalFileScopeWorkingDirectory = (s: ChatStoreState): string | undefined =>@@ -364,6 +366,7 @@ export const chatPortalSelectors = {currentFile,previewFileId,previewFileSource,+ previewFileSourceTopicId,chunkText,// Goal drill-down data