Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: open generated files for agent share visitors (#20981)

YuTengjingb97c5f232249
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx
index badb41d9af6..6079e3aba14 100644
--- a/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx
+++ b/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx
@@ -9,7 +9,9 @@ import { memo, useCallback } from 'react';
import FileIcon from '@/components/FileIcon';
import { useChatStore } from '@/store/chat';
+import { useConversationStore } from '../../../store';
import type { MarkdownElementProps } from '../type';
+import { getFileLinkOpenAction } from './parse';
interface FileLinkProperties {
fileId?: string;
@@ -66,6 +68,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const Render = memo<MarkdownElementProps<FileLinkProperties>>(({ node }) => {
const { fileId, linkHref, linkLabel } = node?.properties || {};
const openFilePreview = useChatStore((s) => s.openFilePreview);
+ const isAgentShareVisitor = useConversationStore((s) => !!s.context.agentShareId);
const label = linkLabel || linkHref || '';
const handleClick = useCallback(
@@ -77,9 +80,14 @@ const Render = memo<MarkdownElementProps<FileLinkProperties>>(({ node }) => {
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
- openFilePreview({ fileId });
+ const action = getFileLinkOpenAction({ fileId, isAgentShareVisitor, label, linkHref });
+ if (action.kind === 'newTab') {
+ window.open(action.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ openFilePreview(action.params);
},
- [fileId, openFilePreview],
+ [fileId, isAgentShareVisitor, label, linkHref, openFilePreview],
);
return (
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts b/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts
index 142a3e47ec5..1bf830432f3 100644
--- a/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts
+++ b/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { parseFileLinkHref } from './parse';
+import { getFileLinkOpenAction, parseFileLinkHref } from './parse';
const ORIGIN = 'https://app.lobehub.com';
@@ -48,3 +48,29 @@ describe('parseFileLinkHref', () => {
expect(parseFileLinkHref('', ORIGIN)).toBeNull();
});
});
+
+describe('getFileLinkOpenAction', () => {
+ const link = { fileId: 'file_1', label: 'report.md', linkHref: `${ORIGIN}/f/file_1` };
+
+ it('opens the owner-scoped preview by id for the file owner', () => {
+ expect(getFileLinkOpenAction({ ...link, isAgentShareVisitor: false })).toEqual({
+ kind: 'preview',
+ params: { fileId: 'file_1' },
+ });
+ });
+
+ // Regression (LOBE-14768): the visitor does not own the creator's file, so the
+ // id-only preview fetched nothing and showed "file unavailable".
+ it('previews from the public /f/:id link on the agent-share visitor page', () => {
+ expect(getFileLinkOpenAction({ ...link, isAgentShareVisitor: true })).toEqual({
+ kind: 'preview',
+ params: { fileId: 'file_1', source: { name: 'report.md', url: `${ORIGIN}/f/file_1` } },
+ });
+ });
+
+ it('opens the public link in a new tab when the visitor label names no file type', () => {
+ expect(
+ getFileLinkOpenAction({ ...link, isAgentShareVisitor: true, label: 'Download the deck' }),
+ ).toEqual({ kind: 'newTab', url: `${ORIGIN}/f/file_1` });
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/parse.ts b/src/features/Conversation/Markdown/plugins/FileLink/parse.ts
index 132a9bfe758..bf52afd65d8 100644
--- a/src/features/Conversation/Markdown/plugins/FileLink/parse.ts
+++ b/src/features/Conversation/Markdown/plugins/FileLink/parse.ts
@@ -49,3 +49,39 @@ export const parseFileLinkHref = (
return null;
}
};
+
+// A link label that names a file, e.g. `report.md` or `action-items.csv`.
+const FILE_NAME_WITH_EXTENSION_REGEX = /\.[\da-z]{1,10}$/i;
+
+export type FileLinkOpenAction =
+ | { kind: 'preview'; params: { fileId: string; source?: { name: string; url: string } } }
+ | { kind: 'newTab'; url: string };
+
+/**
+ * What a file link click opens.
+ *
+ * The agent-share visitor does not own the creator's files, so the portal's
+ * owner-scoped fetch by id finds nothing and shows "file unavailable"; the
+ * `/f/:id` link itself is public by id, so the visitor previews straight from
+ * it. That preview only knows the file through the link label (the FileViewer
+ * picks its renderer from the name's extension), so a label such as
+ * "Download the deck" opens the public link in a new tab instead of a preview
+ * that would render the file with the wrong viewer.
+ */
+export const getFileLinkOpenAction = ({
+ fileId,
+ isAgentShareVisitor,
+ label,
+ linkHref,
+}: {
+ fileId: string;
+ isAgentShareVisitor: boolean;
+ label: string;
+ linkHref?: string;
+}): FileLinkOpenAction => {
+ if (!isAgentShareVisitor || !linkHref) return { kind: 'preview', params: { fileId } };
+
+ if (!FILE_NAME_WITH_EXTENSION_REGEX.test(label.trim())) return { kind: 'newTab', url: linkHref };
+
+ return { kind: 'preview', params: { fileId, source: { name: label.trim(), url: linkHref } } };
+};
diff --git a/src/features/Conversation/Messages/EditedFilesCard/index.test.ts b/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
index aaf2d88c1dc..27fe4889357 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
@@ -1,7 +1,9 @@
import { getFilePathDisplayInfo } from '@lobechat/shared-tool-ui/components';
import { fireEvent, render, screen } from '@testing-library/react';
import { createElement } from 'react';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
import EditedFilesCard, {
AGGREGATE_EDITED_FILE_ICON_SIZE,
@@ -17,6 +19,17 @@ vi.mock('react-i18next', () => ({
}),
}));
+const conversationState = { context: { agentShareId: undefined as string | undefined } };
+
+vi.mock('../../store', () => ({
+ useConversationStore: (selector: (s: unknown) => unknown) => selector(conversationState),
+}));
+
+afterEach(() => {
+ conversationState.context.agentShareId = undefined;
+ useChatStore.setState({ activeTopicId: undefined });
+});
+
const singleEntry = {
diffTexts: [
'diff --git a/Acceptance/index.tsx b/Acceptance/index.tsx\n--- a/Acceptance/index.tsx\n+++ b/Acceptance/index.tsx\n@@ -1 +1 @@\n-old\n+new',
@@ -94,3 +107,30 @@ describe('SingleEditedFileCard', () => {
expect(screen.getByRole('button', { name: 'editedFiles.hideChanges' })).toBeInTheDocument();
});
});
+
+describe('EditedFilesCard open action', () => {
+ const sandboxEntry = {
+ ...singleEntry,
+ path: '/home/user/price_history.html',
+ sandboxBacked: true,
+ };
+ const singleTitle = 'editedFiles.singleTitle:user/price_history.html';
+
+ it('opens a sandbox file preview from the header for the topic owner', () => {
+ useChatStore.setState({ activeTopicId: 'tpc_1' });
+ render(createElement(EditedFilesCard, { entries: [sandboxEntry] }));
+
+ expect(screen.getByText(singleTitle).closest('[role="button"]')).not.toBeNull();
+ });
+
+ // Regression (LOBE-14768): the share visitor page's portal hosts no LocalFile
+ // view, so the header click used to push an invisible view and do nothing.
+ it('keeps the header inert on the agent-share visitor page, leaving the diff action', () => {
+ conversationState.context.agentShareId = 'share_1';
+ useChatStore.setState({ activeTopicId: 'tpc_1' });
+ render(createElement(EditedFilesCard, { entries: [sandboxEntry] }));
+
+ expect(screen.getByText(singleTitle).closest('[role="button"]')).toBeNull();
+ expect(screen.getByRole('button', { name: 'editedFiles.viewChanges' })).toBeInTheDocument();
+ });
+});
diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts
index 3ec5b71d0cb..a1bbd4fad09 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts
@@ -9,6 +9,7 @@ import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
+import { useConversationStore } from '../../store';
import type { OperationEditedFile } from './deriveEditedFiles';
// Home-relative paths are already anchored: the file tools expand exactly `~`,
@@ -151,9 +152,14 @@ export const planFilesystemOpen = ({
* Context is resolved from the CURRENT agent config, not the round that ran:
* best effort, matching how the files sidebar targets "where the agent works
* now".
+ *
+ * The agent-share visitor page never gets an open action: its portal hosts no
+ * LocalFile view (see AgentShareVisitor/ArtifactPanel) and the creator's
+ * sandbox/filesystem reads are owner-scoped, so a click would do nothing.
*/
export const useOpenEditedFile = () => {
const [openLocalFile, activeTopicId] = useChatStore((s) => [s.openLocalFile, s.activeTopicId]);
+ const isAgentShareVisitor = useConversationStore((s) => !!s.context.agentShareId);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const workingDirectory = useEffectiveWorkingDirectory(activeAgentId);
@@ -174,7 +180,7 @@ export const useOpenEditedFile = () => {
(
entry: Pick<OperationEditedFile, 'kind' | 'path' | 'sandboxBacked'>,
): (() => void) | undefined => {
- if (!canPreviewEditedFile(entry)) return undefined;
+ if (isAgentShareVisitor || !canPreviewEditedFile(entry)) return undefined;
if (entry.sandboxBacked) {
if (!activeTopicId) return undefined;
return () =>
@@ -205,6 +211,13 @@ export const useOpenEditedFile = () => {
workingDirectory,
});
},
- [activeTopicId, filesystemAvailable, openLocalFile, remoteDeviceId, workingDirectory],
+ [
+ activeTopicId,
+ filesystemAvailable,
+ isAgentShareVisitor,
+ openLocalFile,
+ remoteDeviceId,
+ workingDirectory,
+ ],
);
};
diff --git a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts
index 55def30aae6..1be0118230b 100644
--- a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts
+++ b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts
@@ -19,7 +19,9 @@ vi.mock('@/features/Work/ShareVisitorDocumentModal', () => ({
createShareVisitorDocumentModal: vi.fn(),
}));
-const fileWork = (fileUrl: string) =>
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://app.lobehub.com' }));
+
+const fileWork = (fileUrl?: string) =>
({
event: { metadata: { fileId: 'file_1', filePath: '/hello_world.pptx', fileUrl } },
id: 'wk_1',
@@ -48,11 +50,27 @@ describe('useVisitorWorkOpen', () => {
windowOpen.mockRestore();
});
- it('does not open a preview for a non-http(s) file URL', () => {
+ it('previews from the /f/:id proxy instead of a non-http(s) file URL', () => {
const { result } = renderHook(() => useVisitorWorkOpen());
result.current(fileWork('javascript:alert(1)'));
- expect(openFilePreview).not.toHaveBeenCalled();
+ expect(openFilePreview).toHaveBeenCalledWith({
+ fileId: 'file_1',
+ source: { name: 'hello_world.pptx', url: 'https://app.lobehub.com/f/file_1' },
+ });
+ });
+
+ // Regression (LOBE-14768): a file Work carrying only `fileId` (no persisted
+ // URL) used to return early, so clicking its card did nothing.
+ it('previews a file Work without a persisted URL from the /f/:id proxy', () => {
+ const { result } = renderHook(() => useVisitorWorkOpen());
+
+ result.current(fileWork());
+
+ expect(openFilePreview).toHaveBeenCalledWith({
+ fileId: 'file_1',
+ source: { name: 'hello_world.pptx', url: 'https://app.lobehub.com/f/file_1' },
+ });
});
});
diff --git a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts
index b5c7f1c021c..55548b4d1c8 100644
--- a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts
+++ b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts
@@ -3,6 +3,7 @@ import { useCallback } from 'react';
import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
import { createShareVisitorDocumentModal } from '@/features/Work/ShareVisitorDocumentModal';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
import { useChatStore } from '@/store/chat';
import { useConversationStore } from '../../store';
@@ -12,12 +13,15 @@ import { useConversationStore } from '../../store';
* default open targets (Portal document viewer, owner file fetch, task detail)
* are all owner-scoped, so opens route through share-authorized paths instead.
* `/f/:id` is public by id, so a file previews in the visitor page's portal
- * straight from its URL.
+ * straight from its URL. A file Work without a persisted URL (e.g. an edited
+ * file whose version metadata only carries `fileId`) previews from the
+ * `/f/:id` proxy built from that id.
*/
export const useVisitorWorkOpen = () => {
const agentShareId = useConversationStore((s) => s.context.agentShareId);
const topicId = useConversationStore((s) => s.context.topicId);
const openFilePreview = useChatStore((s) => s.openFilePreview);
+ const appOrigin = useAppOrigin();
return useCallback(
(item: WorkSummaryItem) => {
@@ -37,10 +41,12 @@ export const useVisitorWorkOpen = () => {
return;
}
case 'filePreview': {
- if (!isSafeExternalUrl(target.url)) return;
+ const url = isSafeExternalUrl(target.url)
+ ? target.url
+ : `${appOrigin}/f/${encodeURIComponent(target.fileId)}`;
openFilePreview({
fileId: target.fileId,
- source: { name: descriptor.getTitle(item) || target.fileId, url: target.url },
+ source: { name: descriptor.getTitle(item) || target.fileId, url },
});
return;
}
@@ -54,6 +60,6 @@ export const useVisitorWorkOpen = () => {
}
}
},
- [agentShareId, openFilePreview, topicId],
+ [agentShareId, appOrigin, openFilePreview, topicId],
);
};