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.

✨ feat: add internal entity link previews (#17015)

Arvin Xu11c014ebba21
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index e4e02b91beb..666421584b5 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -402,6 +402,10 @@
"inputQueue.edit": "Edit",
"inputQueue.sendNow": "Send now (interrupts current run)",
"intentUnderstanding.title": "Understanding your intent...",
+ "internalLink.agent.open": "Open agent",
+ "internalLink.preview.agent": "Agent",
+ "internalLink.preview.document": "Page",
+ "internalLink.preview.task": "Task",
"inviteMembers": "Invite members",
"knowledgeBase.all": "All Content",
"knowledgeBase.allFiles": "All Files",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 9ab5988a581..0890c3de0a6 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -404,6 +404,10 @@
"inputQueue.edit": "编辑",
"inputQueue.sendNow": "立即发送(中断当前运行)",
"intentUnderstanding.title": "正在理解你的意图…",
+ "internalLink.agent.open": "打开助理",
+ "internalLink.preview.agent": "Agent",
+ "internalLink.preview.document": "页面",
+ "internalLink.preview.task": "任务",
"inviteMembers": "邀请成员",
"knowledgeBase.all": "全部内容",
"knowledgeBase.allFiles": "全部文件",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index cc3ccad80f2..557c20b9236 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -36,6 +36,7 @@ export default {
'agentDocument.emptyTitle': 'No document open',
'agentDocument.linkCopied': 'Link copied',
'agentDocument.openAsPage': 'Open as full page',
+ 'internalLink.agent.open': 'Open agent',
'agentProfile.files_one': '{{count}} file',
'agentProfile.files_other': '{{count}} files',
'agentProfile.knowledgeBases_one': '{{count}} library',
@@ -1522,5 +1523,8 @@ export default {
'verifyConfig.verifierTypeDesc.agent': 'Spawn a sub-agent to investigate and judge',
'verifyConfig.verifierTypeDesc.llm': 'Let an LLM judge the result',
'verifyConfig.verifierTypeDesc.program': 'Run a deterministic script to check',
+ 'internalLink.preview.agent': 'Agent',
+ 'internalLink.preview.document': 'Page',
+ 'internalLink.preview.task': 'Task',
'you': 'You',
};
diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx
new file mode 100644
index 00000000000..585e7d0599a
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityLink.tsx
@@ -0,0 +1,164 @@
+'use client';
+
+import { Icon } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { BotIcon, CheckSquareIcon, FileTextIcon } from 'lucide-react';
+import type { MouseEvent } from 'react';
+import { memo, useCallback } from 'react';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useClientDataSWR } from '@/libs/swr';
+import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+
+import type { InternalLinkReference } from '../internalLink';
+import { InternalEntityPreview } from './InternalEntityPreview';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ link: css`
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ color: ${cssVar.colorText} !important;
+ text-decoration-color: ${cssVar.colorBorder};
+ text-decoration-line: underline;
+ text-decoration-thickness: 1px;
+ text-underline-offset: 3px;
+
+ transition:
+ color 0.15s,
+ text-decoration-color 0.15s;
+
+ &:hover {
+ color: ${cssVar.colorText} !important;
+ text-decoration-color: ${cssVar.colorTextSecondary};
+ }
+
+ &:focus-visible {
+ border-radius: 2px;
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: 2px;
+ }
+
+ > svg {
+ flex: none;
+ color: ${cssVar.colorTextSecondary};
+ }
+ `,
+}));
+
+const ENTITY_ICONS = {
+ agent: BotIcon,
+ document: FileTextIcon,
+ task: CheckSquareIcon,
+} as const;
+
+interface InternalEntityLinkProps {
+ href: string;
+ label: string;
+ reference: InternalLinkReference;
+}
+
+export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label, reference }) => {
+ const navigate = useWorkspaceAwareNavigate();
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const [openAgentDetail, openDocument, openTaskDetail] = useChatStore((s) => [
+ s.openAgentDetail,
+ s.openDocument,
+ s.openTaskDetail,
+ ]);
+ const linkedAgentId = reference.type === 'document' ? reference.agentId : undefined;
+ const shouldResolveAgentDocument = !!linkedAgentId && linkedAgentId === activeAgentId;
+ const { data: agentDocuments, mutate: resolveAgentDocuments } = useClientDataSWR(
+ shouldResolveAgentDocument ? agentDocumentSWRKeys.documentsList(linkedAgentId) : null,
+ () => agentDocumentService.listDocuments({ agentId: linkedAgentId! }),
+ );
+
+ const handleClick = useCallback(
+ async (event: MouseEvent<HTMLAnchorElement>) => {
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
+ return;
+ }
+
+ event.preventDefault();
+
+ if ('workspaceSlug' in reference && reference.workspaceSlug) {
+ navigate(reference.pathname, { escape: true });
+ return;
+ }
+
+ if (
+ reference.type === 'document' &&
+ reference.agentId &&
+ reference.agentId !== activeAgentId
+ ) {
+ navigate(reference.pathname, { escape: true });
+ return;
+ }
+
+ switch (reference.type) {
+ case 'agent': {
+ openAgentDetail(reference.agentId);
+ break;
+ }
+ case 'document': {
+ const documents = shouldResolveAgentDocument
+ ? (agentDocuments ?? (await resolveAgentDocuments().catch(() => undefined)))
+ : undefined;
+ const agentDocumentId = documents?.find(
+ (document) => document.documentId === reference.documentId,
+ )?.id;
+
+ openDocument(reference.documentId, agentDocumentId);
+ break;
+ }
+ case 'task': {
+ openTaskDetail(reference.taskId);
+ break;
+ }
+ case 'route': {
+ navigate(reference.pathname);
+ break;
+ }
+ }
+ },
+ [
+ activeAgentId,
+ agentDocuments,
+ navigate,
+ openAgentDetail,
+ openDocument,
+ openTaskDetail,
+ reference,
+ resolveAgentDocuments,
+ shouldResolveAgentDocument,
+ ],
+ );
+
+ const icon = reference.type === 'route' ? undefined : ENTITY_ICONS[reference.type];
+
+ const link = (
+ <a
+ className={styles.link}
+ href={href}
+ rel="noopener noreferrer"
+ target="_blank"
+ onClick={handleClick}
+ >
+ {icon && <Icon icon={icon} size={14} />}
+ {label}
+ </a>
+ );
+
+ if (reference.type === 'route' || reference.workspaceSlug) return link;
+
+ return (
+ <InternalEntityPreview fallbackTitle={label} reference={reference}>
+ {link}
+ </InternalEntityPreview>
+ );
+});
+
+InternalEntityLink.displayName = 'InternalEntityLink';
diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityPreview.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityPreview.tsx
new file mode 100644
index 00000000000..c5e16f8b2c4
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Link/Render/InternalEntityPreview.tsx
@@ -0,0 +1,166 @@
+'use client';
+
+import { Avatar, Flexbox, Icon, Popover, Skeleton, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { BotIcon, CheckSquareIcon, FileTextIcon } from 'lucide-react';
+import { memo, type PropsWithChildren, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { agentService } from '@/services/agent';
+import { documentService } from '@/services/document';
+import { taskService } from '@/services/task';
+
+import type { InternalLinkReference } from '../internalLink';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ content: css`
+ width: 320px;
+ padding: 16px;
+ `,
+ description: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 3;
+
+ line-height: 1.55;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ icon: css`
+ display: grid;
+ flex: none;
+ place-items: center;
+
+ width: 36px;
+ height: 36px;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ title: css`
+ overflow: hidden;
+
+ font-weight: 600;
+ line-height: 1.4;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ type: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+interface PreviewData {
+ avatar?: string | null;
+ backgroundColor?: string | null;
+ description?: string | null;
+ title?: string | null;
+}
+
+const getPreviewData = async (reference: InternalLinkReference): Promise<PreviewData | null> => {
+ switch (reference.type) {
+ case 'agent': {
+ return agentService.getAgentConfigById(reference.agentId);
+ }
+ case 'document': {
+ const document = await documentService.getDocumentById(reference.documentId);
+ return document
+ ? {
+ description: document.content,
+ title: document.title || document.filename,
+ }
+ : null;
+ }
+ case 'task': {
+ const result = await taskService.getDetail(reference.taskId);
+ const task = result.data;
+ return task
+ ? {
+ description: task.description || task.instruction,
+ title: task.name || task.identifier,
+ }
+ : null;
+ }
+ case 'route': {
+ return null;
+ }
+ }
+};
+
+interface InternalEntityPreviewProps extends PropsWithChildren {
+ fallbackTitle: string;
+ reference: Exclude<InternalLinkReference, { type: 'route' }>;
+}
+
+export const InternalEntityPreview = memo<InternalEntityPreviewProps>(
+ ({ children, fallbackTitle, reference }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+ const { data, isLoading } = useClientDataSWR(
+ open ? ['internal-entity-preview', reference.type, reference.pathname] : null,
+ () => getPreviewData(reference),
+ { revalidateOnFocus: false },
+ );
+
+ const icon =
+ reference.type === 'agent'
+ ? BotIcon
+ : reference.type === 'task'
+ ? CheckSquareIcon
+ : FileTextIcon;
+ const typeLabel = t(`internalLink.preview.${reference.type}`);
+
+ const content = isLoading ? (
+ <div className={styles.content}>
+ <Skeleton active avatar paragraph={{ rows: 2 }} />
+ </div>
+ ) : (
+ <Flexbox className={styles.content} gap={12}>
+ <Flexbox horizontal align="center" gap={12}>
+ {reference.type === 'agent' && data?.avatar ? (
+ <Avatar
+ avatar={data.avatar}
+ background={data.backgroundColor ?? undefined}
+ shape="square"
+ size={36}
+ />
+ ) : (
+ <span className={styles.icon}>
+ <Icon icon={icon} size={19} />
+ </span>
+ )}
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <span className={styles.type}>{typeLabel}</span>
+ <span className={styles.title}>{data?.title || fallbackTitle}</span>
+ </Flexbox>
+ </Flexbox>
+ {data?.description && (
+ <Text className={styles.description} fontSize={13}>
+ {data.description}
+ </Text>
+ )}
+ </Flexbox>
+ );
+
+ return (
+ <Popover
+ content={content}
+ mouseEnterDelay={0.35}
+ open={open}
+ placement="top"
+ styles={{ content: { borderRadius: 12, overflow: 'hidden', padding: 0 } }}
+ trigger="hover"
+ triggerProps={{ role: 'link' }}
+ onOpenChange={setOpen}
+ >
+ {children}
+ </Popover>
+ );
+ },
+);
+
+InternalEntityPreview.displayName = 'InternalEntityPreview';
diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
index a9765e939b3..5ccd33129b3 100644
--- a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
+++ b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
@@ -1,8 +1,8 @@
/**
* @vitest-environment happy-dom
*/
-import { render } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import Render from './index';
@@ -10,6 +10,43 @@ import Render from './index';
// selector's return value through this module-level flag so each case can flip
// the "Link Icon" setting on/off without a real store.
let mockShowIcon = true;
+const mockNavigate = vi.fn();
+const mockOpenAgentDetail = vi.fn();
+const mockOpenDocument = vi.fn();
+const mockOpenTaskDetail = vi.fn();
+
+vi.mock('@/business/client/hooks/useWorkspaces', () => ({
+ useWorkspaces: () => [{ id: 'ws-1', slug: 'lobe-team' }],
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mockNavigate,
+}));
+
+vi.mock('@/libs/swr', () => ({
+ useClientDataSWR: () => ({
+ data: [{ documentId: 'docs_doc1', id: 'agent-document-1' }],
+ mutate: vi.fn(),
+ }),
+}));
+
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentService: { listDocuments: vi.fn() },
+ agentDocumentSWRKeys: { documentsList: (agentId: string) => ['agent-documents', agentId] },
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) => selector({ activeAgentId: 'agt_1' }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: unknown) => unknown) =>
+ selector({
+ openAgentDetail: mockOpenAgentDetail,
+ openDocument: mockOpenDocument,
+ openTaskDetail: mockOpenTaskDetail,
+ }),
+}));
vi.mock('@/store/user', () => ({
useUserStore: (selector: (s: unknown) => unknown) => selector(undefined),
@@ -32,6 +69,10 @@ afterEach(() => {
mockShowIcon = true;
});
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
describe('Link Render — message link icon toggle', () => {
describe('when enableMessageLinkIcon is ON (default)', () => {
it('renders a generic link with a leading favicon icon', () => {
@@ -102,3 +143,104 @@ describe('Link Render — message link icon toggle', () => {
});
});
});
+
+describe('Link Render — internal entities', () => {
+ it('opens official document links in the conversation portal', () => {
+ const { getByRole } = renderLink({
+ linkHref: '/agent/agt_1/docs/doc1',
+ linkKind: 'generic',
+ linkLabel: 'Research notes',
+ });
+
+ fireEvent.click(getByRole('link', { name: 'Research notes' }));
+
+ expect(mockOpenDocument).toHaveBeenCalledWith('docs_doc1', 'agent-document-1');
+ expect(getByRole('link', { name: 'Research notes' })).toHaveAttribute(
+ 'href',
+ '/agent/agt_1/docs/doc1',
+ );
+ expect(mockNavigate).not.toHaveBeenCalled();
+ });
+
+ it('opens tasks and agents in their portal views', () => {
+ const task = renderLink({
+ linkHref: '/task/T-198',
+ linkKind: 'generic',
+ linkLabel: 'T-198',
+ });
+ fireEvent.click(task.getByRole('link', { name: 'T-198' }));
+ expect(mockOpenTaskDetail).toHaveBeenCalledWith('T-198');
+ task.unmount();
+
+ const agent = renderLink({
+ linkHref: '/agent/agt_1',
+ linkKind: 'generic',
+ linkLabel: 'Research agent',
+ });
+ fireEvent.click(agent.getByRole('link', { name: 'Research agent' }));
+ expect(mockOpenAgentDetail).toHaveBeenCalledWith('agt_1');
+ });
+
+ it('preserves modifier-click browser behavior', () => {
+ const { getByRole } = renderLink({
+ linkHref: '/task/T-198',
+ linkKind: 'generic',
+ linkLabel: 'T-198',
+ });
+
+ fireEvent.click(getByRole('link', { name: 'T-198' }), { metaKey: true });
+
+ expect(mockOpenTaskDetail).not.toHaveBeenCalled();
+ });
+
+ it('navigates non-entity app routes without leaving the SPA', () => {
+ const { getByRole } = renderLink({
+ linkHref: '/settings/profile',
+ linkKind: 'generic',
+ linkLabel: 'Profile settings',
+ });
+
+ fireEvent.click(getByRole('link', { name: 'Profile settings' }));
+
+ expect(mockNavigate).toHaveBeenCalledWith('/settings/profile');
+ });
+
+ it('preserves workspace prefixes for workspace-qualified SPA routes', () => {
+ const { getByRole } = renderLink({
+ linkHref: '/lobe-team/tasks',
+ linkKind: 'generic',
+ linkLabel: 'Workspace tasks',
+ });
+
+ fireEvent.click(getByRole('link', { name: 'Workspace tasks' }));
+
+ expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/tasks', { escape: true });
+ });
+
+ it('navigates workspace-qualified entities before opening a scoped portal', () => {
+ const { getByRole, queryByRole } = renderLink({
+ linkHref: '/lobe-team/task/T-198',
+ linkKind: 'generic',
+ linkLabel: 'Workspace task',
+ });
+
+ fireEvent.click(getByRole('link', { name: 'Workspace task' }));
+
+ expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/task/T-198', { escape: true });
+ expect(mockOpenTaskDetail).not.toHaveBeenCalled();
+ expect(queryByRole('dialog')).not.toBeInTheDocument();
+ });
+
+ it('preserves a different agent context for agent-scoped document links', () => {
+ const { getByRole } = renderLink({
+ linkHref: '/agent/agt_other/docs/docs_1',
+ linkKind: 'generic',
+ linkLabel: 'Another agent document',
+ });
+
+ fireEvent.click(getByRole('link', { name: 'Another agent document' }));
+
+ expect(mockNavigate).toHaveBeenCalledWith('/agent/agt_other/docs/docs_1', { escape: true });
+ expect(mockOpenDocument).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/index.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/index.tsx
index a7deeae3eab..de91228169e 100644
--- a/src/features/Conversation/Markdown/plugins/Link/Render/index.tsx
+++ b/src/features/Conversation/Markdown/plugins/Link/Render/index.tsx
@@ -4,12 +4,15 @@ import { Github } from '@lobehub/icons';
import { Mail } from 'lucide-react';
import { memo } from 'react';
+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
import { type MarkdownElementProps } from '../../type';
+import { parseInternalLink } from '../internalLink';
import { type LobeLinkKind } from '../parse';
import FaviconIcon from './FaviconIcon';
+import { InternalEntityLink } from './InternalEntityLink';
import LinearIcon from './LinearIcon';
import LinkChip from './LinkChip';
@@ -25,8 +28,18 @@ interface LobeLinkProperties {
const Render = memo<MarkdownElementProps<LobeLinkProperties>>(({ node }) => {
const { linkHref, linkKind, linkLabel, linkDomain } = node?.properties || {};
const showIcon = useUserStore(userGeneralSettingsSelectors.enableMessageLinkIcon);
+ const workspaces = useWorkspaces();
const label = linkLabel || linkHref || '';
+ const internalReference = parseInternalLink(
+ linkHref,
+ typeof window === 'undefined' ? undefined : window.location.origin,
+ workspaces.map((workspace) => workspace.slug),
+ );
+
+ if (linkHref && internalReference) {
+ return <InternalEntityLink href={linkHref} label={label} reference={internalReference} />;
+ }
if (!showIcon) {
return <LinkChip href={linkHref} label={label} />;
diff --git a/src/features/Conversation/Markdown/plugins/Link/internalLink.test.ts b/src/features/Conversation/Markdown/plugins/Link/internalLink.test.ts
new file mode 100644
index 00000000000..f183c0b9e2b
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Link/internalLink.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseInternalLink } from './internalLink';
+
+describe('parseInternalLink', () => {
+ it('parses official agent document links', () => {
+ expect(
+ parseInternalLink('https://app.lobehub.com/agent/agt_agent/docs/document?mode=preview#title'),
+ ).toEqual({
+ agentId: 'agt_agent',
+ documentId: 'docs_document',
+ pathname: '/agent/agt_agent/docs/document?mode=preview#title',
+ type: 'document',
+ });
+ });
+
+ it('parses page links as document references', () => {
+ expect(parseInternalLink('/page/page-1')).toEqual({
+ documentId: 'docs_page-1',
+ pathname: '/page/page-1',
+ type: 'document',
+ });
+ });
+
+ it('parses global and agent-scoped tasks', () => {
+ expect(parseInternalLink('https://app.lobehub.com/task/T-198')).toEqual({
+ pathname: '/task/T-198',
+ taskId: 'T-198',
+ type: 'task',
+ });
+ expect(parseInternalLink('/agent/agent-1/task/T-199')).toEqual({
+ agentId: 'agent-1',
+ pathname: '/agent/agent-1/task/T-199',
+ taskId: 'T-199',
+ type: 'task',
+ });
+ });
+
+ it('parses workspace-prefixed entity paths', () => {
+ expect(
+ parseInternalLink('/lobe-team/agent/agt_agent/docs/docs_document', undefined, ['lobe-team']),
+ ).toEqual({
+ agentId: 'agt_agent',
+ documentId: 'docs_document',
+ pathname: '/lobe-team/agent/agt_agent/docs/docs_document',
+ type: 'document',
+ workspaceSlug: 'lobe-team',
+ });
+ });
+
+ it('accepts the current self-hosted origin', () => {
+ expect(
+ parseInternalLink('https://chat.example.com/task/T-200', 'https://chat.example.com'),
+ ).toEqual({
+ pathname: '/task/T-200',
+ taskId: 'T-200',
+ type: 'task',
+ });
+ expect(
+ parseInternalLink('https://app.lobehub.com/task/T-200', 'https://chat.example.com'),
+ ).toBeNull();
+ });
+
+ it('accepts official links from the Electron renderer origin', () => {
+ expect(parseInternalLink('https://app.lobehub.com/task/T-201', 'app://renderer')).toEqual({
+ pathname: '/task/T-201',
+ taskId: 'T-201',
+ type: 'task',
+ });
+ });
+
+ it('preserves workspace context for workspace-prefixed SPA routes', () => {
+ expect(parseInternalLink('/lobe-team/tasks', undefined, ['lobe-team'])).toEqual({
+ pathname: '/lobe-team/tasks',
+ type: 'route',
+ workspaceSlug: 'lobe-team',
+ });
+ });
+
+ it('rejects external hosts even when their path resembles an app route', () => {
+ expect(
+ parseInternalLink('https://example.com/task/T-200', 'https://chat.example.com'),
+ ).toBeNull();
+ expect(parseInternalLink('//example.com/task/T-200', 'https://chat.example.com')).toBeNull();
+ });
+
+ it('parses agent roots and keeps deeper routes as SPA routes', () => {
+ expect(parseInternalLink('/agent/agent-1')).toEqual({
+ agentId: 'agent-1',
+ pathname: '/agent/agent-1',
+ type: 'agent',
+ });
+ expect(parseInternalLink('/agent/custom-agent-id-123/docs/foo')).toEqual({
+ agentId: 'custom-agent-id-123',
+ documentId: 'docs_foo',
+ pathname: '/agent/custom-agent-id-123/docs/foo',
+ type: 'document',
+ });
+ expect(parseInternalLink('/agent/agent-1/topics')).toEqual({
+ pathname: '/agent/agent-1/topics',
+ type: 'route',
+ });
+ expect(parseInternalLink('/agent/inbox')).toEqual({
+ pathname: '/agent/inbox',
+ type: 'route',
+ });
+ expect(parseInternalLink('https://app.lobehub.com/settings/profile')).toEqual({
+ pathname: '/settings/profile',
+ type: 'route',
+ });
+ });
+
+ it('leaves same-origin backend and framework links to the browser', () => {
+ expect(parseInternalLink('/api/agent/stream?operationId=op_1')).toBeNull();
+ expect(parseInternalLink('/f/generated-file-id')).toBeNull();
+ expect(parseInternalLink('https://app.lobehub.com/f/generated-file-id')).toBeNull();
+ expect(parseInternalLink('/trpc/lambda')).toBeNull();
+ expect(parseInternalLink('/webapi/chat')).toBeNull();
+ expect(parseInternalLink('/_next/static/chunks/app.js')).toBeNull();
+ expect(parseInternalLink('/favicon.ico')).toBeNull();
+ expect(parseInternalLink('/manifest.webmanifest')).toBeNull();
+ expect(parseInternalLink('/.well-known/assetlinks.json')).toBeNull();
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/Link/internalLink.ts b/src/features/Conversation/Markdown/plugins/Link/internalLink.ts
new file mode 100644
index 00000000000..6f9e5989c65
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/Link/internalLink.ts
@@ -0,0 +1,160 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { OFFICIAL_URL } from '@lobechat/const';
+
+import { getIdFromIdentifier } from '@/utils/identifier';
+
+const ROUTE_ROOTS = new Set(['agent', 'page', 'task', 'tasks']);
+const BUILTIN_AGENT_SLUG_SET = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));
+const NON_SPA_ROUTE_ROOTS = new Set(['_next', 'api', 'f', 'oidc', 'trpc', 'webapi']);
+const SPA_ROUTE_ROOTS = new Set([
+ 'agent',
+ 'community',
+ 'downloads',
+ 'eval',
+ 'fleet',
+ 'group',
+ 'image',
+ 'memory',
+ 'page',
+ 'resource',
+ 'settings',
+ 'task',
+ 'tasks',
+ 'video',
+]);
+
+export type InternalLinkReference =
+ | { agentId: string; pathname: string; type: 'agent'; workspaceSlug?: string }
+ | {
+ agentId?: string;
+ documentId: string;
+ pathname: string;
+ type: 'document';
+ workspaceSlug?: string;
+ }
+ | { pathname: string; type: 'route'; workspaceSlug?: string }
+ | {
+ agentId?: string;
+ pathname: string;
+ taskId: string;
+ type: 'task';
+ workspaceSlug?: string;
+ };
+
+const getRouteSegments = (pathname: string, workspaceSlugs: ReadonlySet<string>) => {
+ const segments = pathname.split('/').filter(Boolean);
+
+ if (ROUTE_ROOTS.has(segments[0])) return { segments, workspaceSlug: undefined };
+ if (workspaceSlugs.has(segments[0]) && ROUTE_ROOTS.has(segments[1])) {
+ return { segments: segments.slice(1), workspaceSlug: segments[0] };
+ }
+
+ return null;
+};
+
+const isInternalHost = (url: URL, currentOrigin?: string) => {
+ const officialHost = new URL(OFFICIAL_URL).host;
+ if (!currentOrigin) return url.host === officialHost;
+
+ try {
+ const originUrl = new URL(currentOrigin);
+ if (originUrl.protocol !== 'http:' && originUrl.protocol !== 'https:') {
+ return url.host === officialHost;
+ }
+
+ return url.host === originUrl.host;
+ } catch {
+ return false;
+ }
+};
+
+/** Parse a LobeHub route into a semantic entity reference. */
+export const parseInternalLink = (
+ href: string | undefined,
+ currentOrigin?: string,
+ workspaceSlugs: readonly string[] = [],
+): InternalLinkReference | null => {
+ if (!href) return null;
+
+ const isRootRelative = href.startsWith('/') && !href.startsWith('//');
+ let url: URL;
+
+ try {
+ url = new URL(href, currentOrigin || OFFICIAL_URL);
+ } catch {
+ return null;
+ }
+
+ if (!isRootRelative && !isInternalHost(url, currentOrigin)) return null;
+
+ const route = getRouteSegments(url.pathname, new Set(workspaceSlugs));
+ const pathname = `${url.pathname}${url.search}${url.hash}`;
+
+ if (!route) {
+ const rootSegment = url.pathname.split('/').find(Boolean);
+
+ if (
+ !rootSegment ||
+ NON_SPA_ROUTE_ROOTS.has(rootSegment) ||
+ (!SPA_ROUTE_ROOTS.has(rootSegment) && !workspaceSlugs.includes(rootSegment))
+ ) {
+ return null;
+ }
+
+ const workspaceSlug = workspaceSlugs.includes(rootSegment) ? rootSegment : undefined;
+
+ return { pathname, type: 'route', ...(workspaceSlug ? { workspaceSlug } : {}) };
+ }
+
+ const { segments, workspaceSlug } = route;
+
+ if (segments[0] === 'page' && segments[1]) {
+ return {
+ documentId: getIdFromIdentifier(segments[1], 'docs'),
+ pathname,
+ type: 'document',
+ ...(workspaceSlug ? { workspaceSlug } : {}),
+ };
+ }
+
+ if (segments[0] === 'task' && segments[1]) {
+ return {
+ pathname,
+ taskId: segments[1],
+ type: 'task',
+ ...(workspaceSlug ? { workspaceSlug } : {}),
+ };
+ }
+
+ if (segments[0] === 'agent' && segments[1]) {
+ if (BUILTIN_AGENT_SLUG_SET.has(segments[1])) return { pathname, type: 'route' };
+
+ const agentId = segments[1];
+
+ if (segments[2] === 'docs' && segments[3]) {
+ return {
+ agentId,
+ documentId: getIdFromIdentifier(segments[3], 'docs'),
+ pathname,
+ type: 'document',
+ ...(workspaceSlug ? { workspaceSlug } : {}),
+ };
+ }
+
+ if (segments[2] === 'task' && segments[3]) {
+ return {
+ agentId,
+ pathname,
+ taskId: segments[3],
+ type: 'task',
+ ...(workspaceSlug ? { workspaceSlug } : {}),
+ };
+ }
+
+ if (segments.length === 2) {
+ return { agentId, pathname, type: 'agent', ...(workspaceSlug ? { workspaceSlug } : {}) };
+ }
+ }
+
+ return { pathname, type: 'route', ...(workspaceSlug ? { workspaceSlug } : {}) };
+};
diff --git a/src/features/Conversation/Markdown/plugins/Link/parse.test.ts b/src/features/Conversation/Markdown/plugins/Link/parse.test.ts
index c4a6b3d2545..d72acc24730 100644
--- a/src/features/Conversation/Markdown/plugins/Link/parse.test.ts
+++ b/src/features/Conversation/Markdown/plugins/Link/parse.test.ts
@@ -32,12 +32,10 @@ describe('parseLobeLink', () => {
});
it('parses linear issue', () => {
- expect(parseLobeLink('https://linear.app/lobehub/issue/TST-10001/codex-pptx-preview')).toEqual(
- {
- canonicalLabel: 'TST-10001',
- kind: 'linear',
- },
- );
+ expect(parseLobeLink('https://linear.app/lobehub/issue/TST-10001/codex-pptx-preview')).toEqual({
+ canonicalLabel: 'TST-10001',
+ kind: 'linear',
+ });
});
it('parses github user / org pages with the github icon', () => {
@@ -87,10 +85,16 @@ describe('parseLobeLink', () => {
);
});
- it('ignores citation, footnote, relative and non-http hrefs', () => {
+ it('keeps root-relative links for the internal-link renderer', () => {
+ expect(parseLobeLink('/foo/bar')).toEqual({
+ canonicalLabel: '/foo/bar',
+ kind: 'generic',
+ });
+ });
+
+ it('ignores citation, footnote and non-http hrefs', () => {
expect(parseLobeLink('citation-1')).toBeNull();
expect(parseLobeLink('#user-content-fn-1')).toBeNull();
- expect(parseLobeLink('/foo/bar')).toBeNull();
expect(parseLobeLink(undefined)).toBeNull();
});
});
diff --git a/src/features/Conversation/Markdown/plugins/Link/parse.ts b/src/features/Conversation/Markdown/plugins/Link/parse.ts
index ed0fd953d7f..aea062bc445 100644
--- a/src/features/Conversation/Markdown/plugins/Link/parse.ts
+++ b/src/features/Conversation/Markdown/plugins/Link/parse.ts
@@ -48,6 +48,10 @@ const figmaFileName = (segments: string[]): string | undefined => {
export const parseLobeLink = (href?: string): ParsedLobeLink | null => {
if (!href) return null;
+ if (href.startsWith('/')) {
+ return { canonicalLabel: href, kind: 'generic' };
+ }
+
if (href.startsWith('mailto:')) {
const email = href.slice('mailto:'.length).split('?')[0];
return email ? { canonicalLabel: email, kind: 'email' } : null;
diff --git a/src/features/Portal/AgentDetail/Body.tsx b/src/features/Portal/AgentDetail/Body.tsx
new file mode 100644
index 00000000000..bc0caf8c3e2
--- /dev/null
+++ b/src/features/Portal/AgentDetail/Body.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { Avatar, Flexbox, Markdown, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import Loading from '@/components/Loading/BrandTextLoading';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+const Body = memo(() => {
+ const { t } = useTranslation('chat');
+ const agentId = useChatStore(chatPortalSelectors.agentDetailId) || '';
+ const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);
+ const { error, isLoading, mutate } = useFetchAgentConfig(true, agentId);
+ const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));
+ const openingMessage = useAgentStore(
+ (s) => agentSelectors.getAgentConfigById(agentId)(s)?.openingMessage,
+ );
+
+ if (!agentId) return null;
+
+ if (error) {
+ return (
+ <Flexbox flex={1} padding={24}>
+ <AsyncError error={error} variant="page" onRetry={() => void mutate()} />
+ </Flexbox>
+ );
+ }
+
+ if (isLoading) return <Loading debugId="PortalAgentDetail" />;
+
+ return (
+ <Flexbox align="center" flex={1} gap={16} padding={32} style={{ overflowY: 'auto' }}>
+ <Avatar avatar={meta.avatar} background={meta.backgroundColor} shape="square" size={80} />
+ <Text align="center" fontSize={24} weight="bold">
+ {meta.title || t('defaultSession', { ns: 'common' })}
+ </Text>
+ {meta.description && (
+ <Text align="center" type="secondary">
+ {meta.description}
+ </Text>
+ )}
+ {openingMessage && (
+ <Flexbox width="min(100%, 560px)">
+ <Markdown variant="chat">{openingMessage}</Markdown>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+export default Body;
diff --git a/src/features/Portal/AgentDetail/Header.tsx b/src/features/Portal/AgentDetail/Header.tsx
new file mode 100644
index 00000000000..16803c0ff79
--- /dev/null
+++ b/src/features/Portal/AgentDetail/Header.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
+import { ActionIcon } from '@lobehub/ui';
+import { Maximize2Icon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import PortalChromeHeader from '@/features/Portal/components/Header';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+import Title from './Title';
+
+const Header = memo(() => {
+ const { t } = useTranslation('chat');
+ const agentId = useChatStore(chatPortalSelectors.agentDetailId);
+ const navigate = useWorkspaceAwareNavigate();
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+
+ return (
+ <PortalChromeHeader
+ title={<Title />}
+ rightExtra={
+ agentId ? (
+ <ActionIcon
+ icon={Maximize2Icon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('internalLink.agent.open')}
+ onClick={() => {
+ navigate(`/agent/${agentId}`);
+ clearPortalStack();
+ }}
+ />
+ ) : undefined
+ }
+ />
+ );
+});
+
+export default Header;
diff --git a/src/features/Portal/AgentDetail/Title.tsx b/src/features/Portal/AgentDetail/Title.tsx
new file mode 100644
index 00000000000..da6084b6d4e
--- /dev/null
+++ b/src/features/Portal/AgentDetail/Title.tsx
@@ -0,0 +1,25 @@
+'use client';
+
+import { Avatar, Flexbox, Text } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+const Title = memo(() => {
+ const agentId = useChatStore(chatPortalSelectors.agentDetailId);
+ const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId || ''));
+
+ return (
+ <Flexbox horizontal align="center" gap={8} style={{ minWidth: 0 }}>
+ <Avatar avatar={meta.avatar} background={meta.backgroundColor} shape="square" size={24} />
+ <Text ellipsis weight={500}>
+ {meta.title || agentId}
+ </Text>
+ </Flexbox>
+ );
+});
+
+export default Title;
diff --git a/src/features/Portal/AgentDetail/index.ts b/src/features/Portal/AgentDetail/index.ts
new file mode 100644
index 00000000000..a2c8cd2db32
--- /dev/null
+++ b/src/features/Portal/AgentDetail/index.ts
@@ -0,0 +1,10 @@
+import type { PortalImpl } from '../type';
+import Body from './Body';
+import Header from './Header';
+import Title from './Title';
+
+export const AgentDetail: PortalImpl = {
+ Body,
+ Header,
+ Title,
+};
diff --git a/src/features/Portal/router.tsx b/src/features/Portal/router.tsx
index da1f943e8a0..ae695540c69 100644
--- a/src/features/Portal/router.tsx
+++ b/src/features/Portal/router.tsx
@@ -6,6 +6,7 @@ import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';
+import { AgentDetail } from './AgentDetail';
import { Artifacts } from './Artifacts';
import Header from './components/Header';
import { Document } from './Document';
@@ -23,6 +24,7 @@ import { VerifyResult } from './VerifyResult';
// View type to component mapping
const VIEW_COMPONENTS: Record<PortalViewType, PortalImpl> = {
+ [PortalViewType.AgentDetail]: AgentDetail,
[PortalViewType.Home]: {
Body: HomeBody,
Title: HomeTitle,
diff --git a/src/routes/(main)/agent/features/Portal/features/Portal.tsx b/src/routes/(main)/agent/features/Portal/features/Portal.tsx
index 7206b8b52c1..50cff027de8 100644
--- a/src/routes/(main)/agent/features/Portal/features/Portal.tsx
+++ b/src/routes/(main)/agent/features/Portal/features/Portal.tsx
@@ -39,13 +39,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const PortalPanel = memo(({ children }: PropsWithChildren) => {
- const [showPortal, showToolUI, showArtifactUI, showThread, showTaskDetail] = useChatStore((s) => [
- chatPortalSelectors.showPortal(s),
- chatPortalSelectors.showPluginUI(s),
- chatPortalSelectors.showArtifactUI(s),
- portalThreadSelectors.showThread(s),
- chatPortalSelectors.showTaskDetail(s),
- ]);
+ const [showPortal, showToolUI, showArtifactUI, showThread, showTaskDetail, showAgentDetail] =
+ useChatStore((s) => [
+ chatPortalSelectors.showPortal(s),
+ chatPortalSelectors.showPluginUI(s),
+ chatPortalSelectors.showArtifactUI(s),
+ portalThreadSelectors.showThread(s),
+ chatPortalSelectors.showTaskDetail(s),
+ chatPortalSelectors.showAgentDetail(s),
+ ]);
const [portalWidth, updateSystemStatus] = useGlobalStore((s) => [
systemStatusSelectors.portalWidth(s),
@@ -83,7 +85,7 @@ const PortalPanel = memo(({ children }: PropsWithChildren) => {
content: styles.content,
}}
minWidth={
- showArtifactUI || showToolUI || showThread || showTaskDetail
+ showArtifactUI || showToolUI || showThread || showTaskDetail || showAgentDetail
? CHAT_PORTAL_TOOL_UI_WIDTH
: CHAT_PORTAL_WIDTH
}
diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.ts
index a9d23b8c3d0..c7585e83266 100644
--- a/src/store/chat/slices/portal/action.test.ts
+++ b/src/store/chat/slices/portal/action.test.ts
@@ -333,6 +333,21 @@ describe('chatDockSlice', () => {
});
});
+ describe('openAgentDetail', () => {
+ it('should push AgentDetail view and open portal', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.openAgentDetail('agt_1');
+ });
+
+ expect(result.current.portalStack).toEqual([
+ { agentId: 'agt_1', type: PortalViewType.AgentDetail },
+ ]);
+ expect(result.current.showPortal).toBe(true);
+ });
+ });
+
describe('openLocalFile', () => {
it('should add entry to openLocalFiles, set active, and push LocalFile view', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.ts
index 4429bb4a954..c0c7a47b783 100644
--- a/src/store/chat/slices/portal/action.ts
+++ b/src/store/chat/slices/portal/action.ts
@@ -466,6 +466,10 @@ export class ChatPortalActionImpl {
this.#get().pushPortalView({ artifact, type: PortalViewType.Artifact });
};
+ openAgentDetail = (agentId: string): void => {
+ this.#get().pushPortalView({ agentId, type: PortalViewType.AgentDetail });
+ };
+
openDocument = (documentId: string, agentDocumentId?: string): void => {
this.#get().pushPortalView({ agentDocumentId, documentId, type: PortalViewType.Document });
};
diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.ts
index dafaa2b2814..5ab8ca87db4 100644
--- a/src/store/chat/slices/portal/initialState.ts
+++ b/src/store/chat/slices/portal/initialState.ts
@@ -8,6 +8,7 @@ export enum ArtifactDisplayMode {
// ============== Portal View Stack Types ==============
export enum PortalViewType {
+ AgentDetail = 'agentDetail',
Artifact = 'artifact',
Document = 'document',
FilePreview = 'filePreview',
@@ -41,6 +42,7 @@ export interface OpenLocalFileEntry extends OpenLocalFileParams {
export type PortalViewData =
| { type: PortalViewType.Home }
+ | { agentId: string; type: PortalViewType.AgentDetail }
| { artifact: PortalArtifact; type: PortalViewType.Artifact }
| { agentDocumentId?: string; documentId: string; type: PortalViewType.Document }
| { type: PortalViewType.Notebook }
diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.ts
index 14cc4a1b44f..f75fc0ccd90 100644
--- a/src/store/chat/slices/portal/selectors.test.ts
+++ b/src/store/chat/slices/portal/selectors.test.ts
@@ -84,6 +84,17 @@ describe('chatDockSelectors', () => {
});
});
+ describe('agent detail', () => {
+ it('should expose the active agent detail id', () => {
+ const state = createState({
+ portalStack: [{ agentId: 'agt_1', type: PortalViewType.AgentDetail }],
+ });
+
+ expect(chatPortalSelectors.showAgentDetail(state)).toBe(true);
+ expect(chatPortalSelectors.agentDetailId(state)).toBe('agt_1');
+ });
+ });
+
describe('canGoBack', () => {
it('should return false when stack has 0 or 1 views', () => {
expect(chatPortalSelectors.canGoBack(createState())).toBe(false);
diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.ts
index 484712b9b20..ed0bb175664 100644
--- a/src/store/chat/slices/portal/selectors.ts
+++ b/src/store/chat/slices/portal/selectors.ts
@@ -32,6 +32,7 @@ const showPortal = (s: ChatStoreState) => s.showPortal;
// ============== View Type Guards ==============
const showArtifactUI = (s: ChatStoreState) => currentViewType(s) === PortalViewType.Artifact;
+const showAgentDetail = (s: ChatStoreState) => currentViewType(s) === PortalViewType.AgentDetail;
const showDocument = (s: ChatStoreState) => currentViewType(s) === PortalViewType.Document;
const showNotebook = (s: ChatStoreState) => currentViewType(s) === PortalViewType.Notebook;
const showFilePreview = (s: ChatStoreState) => currentViewType(s) === PortalViewType.FilePreview;
@@ -55,6 +56,11 @@ const getViewData = <T extends PortalViewType>(
return null;
};
+const agentDetailId = (s: ChatStoreState): string | undefined => {
+ const view = getViewData(s, PortalViewType.AgentDetail);
+ return view?.agentId;
+};
+
// Artifact selectors
const currentArtifact = (s: ChatStoreState): PortalArtifact | undefined => {
const view = getViewData(s, PortalViewType.Artifact);
@@ -245,6 +251,7 @@ export const chatPortalSelectors = {
// View type guards
showArtifactUI,
+ showAgentDetail,
showDocument,
showNotebook,
showFilePreview,
@@ -253,6 +260,9 @@ export const chatPortalSelectors = {
showPluginUI,
showTaskDetail,
+ // Agent detail data
+ agentDetailId,
+
// Artifact data
currentArtifact,
artifactTitle,