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(portal): share one title-anchored more menu across all portals (#20038)

Arvin Xu962adaccf90d
diff --git a/locales/en-US/portal.json b/locales/en-US/portal.json
index abba5af8369..8f840b439c1 100644
--- a/locales/en-US/portal.json
+++ b/locales/en-US/portal.json
@@ -37,6 +37,17 @@
"emptyKnowledgeList": "This list is empty.",
"files": "Files",
"messageDetail": "Message Details",
+ "moreMenu.copyId": "Copy ID",
+ "moreMenu.copyIdSuccess": "ID copied",
+ "moreMenu.copyLink": "Copy link",
+ "moreMenu.copyLinkSuccess": "Link copied",
+ "moreMenu.copyPath": "Copy path",
+ "moreMenu.copyPathSuccess": "Path copied",
+ "moreMenu.delete": "Delete",
+ "moreMenu.openInPage": "Open in page",
+ "moreMenu.refresh": "Refresh",
+ "moreMenu.rename": "Rename",
+ "moreMenu.trigger": "More actions",
"notebook.confirmDelete": "Delete this Page?",
"notebook.delete": "Delete",
"notebook.empty": "No pages yet. Pages linked to this Topic will show up here.",
diff --git a/locales/en-US/thread.json b/locales/en-US/thread.json
index 87c7be4eb95..774bf009d62 100644
--- a/locales/en-US/thread.json
+++ b/locales/en-US/thread.json
@@ -1,5 +1,6 @@
{
"actions.confirmRemoveThread": "You are about to delete this subtopic. Once deleted, it cannot be recovered. Please proceed with caution.",
"newPortalThread.includeContext": "Include topic context",
- "newPortalThread.title": "Start a new subtopic"
+ "newPortalThread.title": "Start a new subtopic",
+ "portal.openInMain": "Open in main conversation"
}
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 07bf4f6b4f5..99be7362029 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -8,8 +8,6 @@
"acceptance.actions.confirmAccept": "Confirm acceptance",
"acceptance.actions.confirmReject": "Reject and start the next round",
"acceptance.actions.confirmRejectCopy": "Reject & copy prompt",
- "acceptance.actions.more": "More actions",
- "acceptance.actions.refresh": "Refresh",
"acceptance.actions.reject": "Reject delivery",
"acceptance.banner.accepted": "Accepted by you · {{time}}",
"acceptance.banner.acceptedHint": "{{count}} verification round(s) archived as the acceptance record",
diff --git a/locales/zh-CN/portal.json b/locales/zh-CN/portal.json
index d5a469868f0..b6345156f59 100644
--- a/locales/zh-CN/portal.json
+++ b/locales/zh-CN/portal.json
@@ -37,6 +37,17 @@
"emptyKnowledgeList": "当前知识列表为空",
"files": "文件",
"messageDetail": "消息详情",
+ "moreMenu.copyId": "复制 ID",
+ "moreMenu.copyIdSuccess": "ID 已复制",
+ "moreMenu.copyLink": "复制链接",
+ "moreMenu.copyLinkSuccess": "链接已复制",
+ "moreMenu.copyPath": "复制路径",
+ "moreMenu.copyPathSuccess": "路径已复制",
+ "moreMenu.delete": "删除",
+ "moreMenu.openInPage": "在页面中打开",
+ "moreMenu.refresh": "刷新",
+ "moreMenu.rename": "重命名",
+ "moreMenu.trigger": "更多操作",
"notebook.confirmDelete": "确定要删除这个文档吗?",
"notebook.delete": "删除",
"notebook.empty": "暂无文档,当前话题关联的文档将会显示在这里",
diff --git a/locales/zh-CN/thread.json b/locales/zh-CN/thread.json
index fa6a6baea9b..52766e5db2b 100644
--- a/locales/zh-CN/thread.json
+++ b/locales/zh-CN/thread.json
@@ -1,5 +1,6 @@
{
"actions.confirmRemoveThread": "将删除该子话题,删除后不可恢复。建议先复制需要保留的内容,再确认继续",
"newPortalThread.includeContext": "包含话题上下文",
- "newPortalThread.title": "开启新的子话题"
+ "newPortalThread.title": "开启新的子话题",
+ "portal.openInMain": "在主对话中打开"
}
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index ae6feff6bbd..e36afb97570 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -8,8 +8,6 @@
"acceptance.actions.confirmAccept": "确认接受交付",
"acceptance.actions.confirmReject": "打回并发起下一轮",
"acceptance.actions.confirmRejectCopy": "打回并复制 prompt",
- "acceptance.actions.more": "更多操作",
- "acceptance.actions.refresh": "刷新",
"acceptance.actions.reject": "打回交付",
"acceptance.banner.accepted": "已验收 · {{time}} 由你确认接受交付",
"acceptance.banner.acceptedHint": "{{count}} 轮验证记录已归档为验收依据",
diff --git a/packages/locales/src/default/portal.ts b/packages/locales/src/default/portal.ts
index f8e017db1a2..3e790ae0c57 100644
--- a/packages/locales/src/default/portal.ts
+++ b/packages/locales/src/default/portal.ts
@@ -45,6 +45,17 @@ export default {
'emptyKnowledgeList': 'This list is empty.',
'files': 'Files',
'messageDetail': 'Message Details',
+ 'moreMenu.copyId': 'Copy ID',
+ 'moreMenu.copyIdSuccess': 'ID copied',
+ 'moreMenu.copyLink': 'Copy link',
+ 'moreMenu.copyLinkSuccess': 'Link copied',
+ 'moreMenu.copyPath': 'Copy path',
+ 'moreMenu.copyPathSuccess': 'Path copied',
+ 'moreMenu.delete': 'Delete',
+ 'moreMenu.openInPage': 'Open in page',
+ 'moreMenu.refresh': 'Refresh',
+ 'moreMenu.rename': 'Rename',
+ 'moreMenu.trigger': 'More actions',
'notebook.confirmDelete': 'Delete this Page?',
'notebook.delete': 'Delete',
'notebook.empty': 'No pages yet. Pages linked to this Topic will show up here.',
diff --git a/packages/locales/src/default/thread.ts b/packages/locales/src/default/thread.ts
index c16ec41ad04..c46d9c668c4 100644
--- a/packages/locales/src/default/thread.ts
+++ b/packages/locales/src/default/thread.ts
@@ -3,4 +3,5 @@ export default {
'You are about to delete this subtopic. Once deleted, it cannot be recovered. Please proceed with caution.',
'newPortalThread.includeContext': 'Include topic context',
'newPortalThread.title': 'Start a new subtopic',
+ 'portal.openInMain': 'Open in main conversation',
};
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index e5989e2edb2..292d1b12a3d 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -120,8 +120,6 @@ export default {
'acceptance.actions.accept': 'Accept delivery',
'acceptance.actions.cancel': 'Cancel',
'acceptance.actions.confirmAccept': 'Confirm acceptance',
- 'acceptance.actions.more': 'More actions',
- 'acceptance.actions.refresh': 'Refresh',
'acceptance.actions.confirmRejectCopy': 'Reject & copy prompt',
'acceptance.actions.confirmReject': 'Reject and start the next round',
'acceptance.actions.reject': 'Reject delivery',
diff --git a/src/features/AgentGoals/GoalDetailActions.tsx b/src/features/AgentGoals/GoalDetailActions.tsx
index a7d18f84c94..f0f77168210 100644
--- a/src/features/AgentGoals/GoalDetailActions.tsx
+++ b/src/features/AgentGoals/GoalDetailActions.tsx
@@ -1,108 +1,67 @@
import { copyToClipboard, Icon } from '@lobehub/ui';
-import {
- ActionIcon,
- confirmModal,
- type DropdownItem,
- DropdownMenu,
- toast,
-} from '@lobehub/ui/base-ui';
+import { ActionIcon, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui/base-ui';
import { CopyIcon, LinkIcon, MoreHorizontalIcon, TrashIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { useAppOrigin } from '@/hooks/useAppOrigin';
import { usePermission } from '@/hooks/usePermission';
-import { useGoalStore } from '@/store/goal';
+
+import { useConfirmDeleteGoal, useGoalShareUrl } from './useGoalActions';
interface GoalDetailActionsProps {
/** Absent for a goal with no responsible agent — e.g. one created from a project. */
agentId?: string;
goalId: string;
- /** Replaces the default redirect to the goal list, for hosts that are not the goal page. */
- onDeleted?: () => void;
projectId?: string | null;
}
-const GoalDetailActions = memo<GoalDetailActionsProps>(
- ({ agentId, goalId, onDeleted, projectId }) => {
- const { t } = useTranslation(['chat', 'common']);
- const navigate = useWorkspaceAwareNavigate();
- const { allowed: canEditTask } = usePermission('create_content');
- const deleteGoal = useGoalStore((s) => s.deleteGoal);
- // Not `window.location.href`: on desktop that is the `app://renderer` shell
- // origin (and the shell location does not track the active tab) — build the
- // shareable web URL from the app origin and the goal route explicitly.
- const appOrigin = useAppOrigin();
- const shareUrl = appOrigin
- ? `${appOrigin}${agentId ? `/agent/${agentId}/goal/${goalId}` : `/goal/${goalId}`}`
- : undefined;
+const GoalDetailActions = memo<GoalDetailActionsProps>(({ agentId, goalId, projectId }) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const { allowed: canEditTask } = usePermission('create_content');
+ const shareUrl = useGoalShareUrl({ agentId, goalId });
+ const confirmDelete = useConfirmDeleteGoal({ agentId, goalId, projectId });
- const items = useMemo<DropdownItem[]>(
- () => [
- {
- icon: <Icon icon={CopyIcon} />,
- key: 'copyId',
- label: t('taskList.contextMenu.copyId'),
- onClick: async () => {
- await copyToClipboard(goalId);
- toast.success(t('taskList.contextMenu.copyIdSuccess'));
- },
- },
- {
- disabled: !shareUrl,
- icon: <Icon icon={LinkIcon} />,
- key: 'copyLink',
- label: t('taskList.contextMenu.copyLink'),
- onClick: async () => {
- if (!shareUrl) return;
- await copyToClipboard(shareUrl);
- toast.success(t('taskList.contextMenu.copyLinkSuccess'));
- },
+ const items = useMemo<DropdownItem[]>(
+ () => [
+ {
+ icon: <Icon icon={CopyIcon} />,
+ key: 'copyId',
+ label: t('taskList.contextMenu.copyId'),
+ onClick: async () => {
+ await copyToClipboard(goalId);
+ toast.success(t('taskList.contextMenu.copyIdSuccess'));
},
- { type: 'divider' },
- {
- danger: true,
- disabled: !canEditTask,
- icon: <Icon icon={TrashIcon} />,
- key: 'delete',
- label: t('delete', { ns: 'common' }),
- onClick: () => {
- confirmModal({
- content: t('goalDetail.deleteConfirm.content'),
- okButtonProps: { danger: true },
- okText: t('goalDetail.deleteConfirm.ok'),
- onOk: async () => {
- // Mirrors the list scope the goal was rendered under, so the page
- // the user lands on is the one whose cache was just refreshed.
- await deleteGoal(agentId, goalId, projectId ? `project:${projectId}` : undefined);
- if (onDeleted) {
- onDeleted();
- return;
- }
- navigate(
- agentId
- ? `/agent/${agentId}/goals`
- : projectId
- ? `/project/${projectId}/goals`
- : '/',
- );
- },
- title: t('goalDetail.deleteConfirm.title'),
- });
- },
+ },
+ {
+ disabled: !shareUrl,
+ icon: <Icon icon={LinkIcon} />,
+ key: 'copyLink',
+ label: t('taskList.contextMenu.copyLink'),
+ onClick: async () => {
+ if (!shareUrl) return;
+ await copyToClipboard(shareUrl);
+ toast.success(t('taskList.contextMenu.copyLinkSuccess'));
},
- ],
- [agentId, canEditTask, deleteGoal, goalId, navigate, onDeleted, projectId, shareUrl, t],
- );
+ },
+ { type: 'divider' },
+ {
+ danger: true,
+ disabled: !canEditTask,
+ icon: <Icon icon={TrashIcon} />,
+ key: 'delete',
+ label: t('delete', { ns: 'common' }),
+ onClick: confirmDelete,
+ },
+ ],
+ [canEditTask, confirmDelete, goalId, shareUrl, t],
+ );
- return (
- <DropdownMenu items={items} placement={'bottomRight'}>
- <ActionIcon icon={MoreHorizontalIcon} size={'small'} title={t('goalDetail.moreActions')} />
- </DropdownMenu>
- );
- },
-);
+ return (
+ <DropdownMenu items={items} placement={'bottomRight'}>
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} title={t('goalDetail.moreActions')} />
+ </DropdownMenu>
+ );
+});
GoalDetailActions.displayName = 'GoalDetailActions';
diff --git a/src/features/AgentGoals/useGoalActions.test.ts b/src/features/AgentGoals/useGoalActions.test.ts
new file mode 100644
index 00000000000..08b1b4bbe30
--- /dev/null
+++ b/src/features/AgentGoals/useGoalActions.test.ts
@@ -0,0 +1,53 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useGoalShareUrl } from './useGoalActions';
+
+const mocks = vi.hoisted(() => ({
+ origin: 'https://app.lobehub.com' as string | undefined,
+ slug: null as string | null,
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => mocks.origin }));
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => mocks.slug,
+}));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+vi.mock('@/store/goal', () => ({ useGoalStore: vi.fn() }));
+
+describe('useGoalShareUrl', () => {
+ beforeEach(() => {
+ mocks.origin = 'https://app.lobehub.com';
+ mocks.slug = null;
+ });
+
+ it('links an agent goal under its agent and a project goal at the top level', () => {
+ expect(
+ renderHook(() => useGoalShareUrl({ agentId: 'agt_1', goalId: 'goal_1' })).result.current,
+ ).toBe('https://app.lobehub.com/agent/agt_1/goal/goal_1');
+ expect(renderHook(() => useGoalShareUrl({ goalId: 'goal_1' })).result.current).toBe(
+ 'https://app.lobehub.com/goal/goal_1',
+ );
+ });
+
+ // Regression: the link used to be hand-built without the workspace prefix,
+ // so a copied workspace goal link opened in the personal scope.
+ it('carries the active workspace prefix', () => {
+ mocks.slug = 'acme';
+
+ expect(
+ renderHook(() => useGoalShareUrl({ agentId: 'agt_1', goalId: 'goal_1' })).result.current,
+ ).toBe('https://app.lobehub.com/acme/agent/agt_1/goal/goal_1');
+ expect(renderHook(() => useGoalShareUrl({ goalId: 'goal_1' })).result.current).toBe(
+ 'https://app.lobehub.com/acme/goal/goal_1',
+ );
+ });
+
+ it('has no link without an app origin', () => {
+ mocks.origin = undefined;
+
+ expect(renderHook(() => useGoalShareUrl({ goalId: 'goal_1' })).result.current).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentGoals/useGoalActions.ts b/src/features/AgentGoals/useGoalActions.ts
new file mode 100644
index 00000000000..82b938392ef
--- /dev/null
+++ b/src/features/AgentGoals/useGoalActions.ts
@@ -0,0 +1,68 @@
+import { confirmModal } from '@lobehub/ui/base-ui';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { useGoalStore } from '@/store/goal';
+
+interface GoalRef {
+ /** Absent for a goal with no responsible agent — e.g. one created from a project. */
+ agentId?: string;
+ goalId: string;
+}
+
+/**
+ * Shareable web URL of a goal. Not `window.location.href`: on desktop that is
+ * the `app://renderer` shell origin (and the shell location does not track the
+ * active tab) — the URL is built from the app origin and the goal route.
+ */
+export const useGoalShareUrl = ({ agentId, goalId }: GoalRef): string | undefined => {
+ const appOrigin = useAppOrigin();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ if (!appOrigin) return;
+
+ const path = agentId ? `/agent/${agentId}/goal/${goalId}` : `/goal/${goalId}`;
+ return `${appOrigin}${buildWorkspaceAwarePath(path, activeWorkspaceSlug)}`;
+};
+
+interface ConfirmDeleteGoalOptions extends GoalRef {
+ /** Replaces the default redirect to the goal list, for hosts that are not the goal page. */
+ onDeleted?: () => void;
+ projectId?: string | null;
+}
+
+/** Opens the delete confirmation for a goal and deletes it on confirm. */
+export const useConfirmDeleteGoal = ({
+ agentId,
+ goalId,
+ onDeleted,
+ projectId,
+}: ConfirmDeleteGoalOptions) => {
+ const { t } = useTranslation('chat');
+ const navigate = useWorkspaceAwareNavigate();
+ const deleteGoal = useGoalStore((s) => s.deleteGoal);
+
+ return useCallback(() => {
+ confirmModal({
+ content: t('goalDetail.deleteConfirm.content'),
+ okButtonProps: { danger: true },
+ okText: t('goalDetail.deleteConfirm.ok'),
+ onOk: async () => {
+ // Mirrors the list scope the goal was rendered under, so the page
+ // the user lands on is the one whose cache was just refreshed.
+ await deleteGoal(agentId, goalId, projectId ? `project:${projectId}` : undefined);
+ if (onDeleted) {
+ onDeleted();
+ return;
+ }
+ navigate(
+ agentId ? `/agent/${agentId}/goals` : projectId ? `/project/${projectId}/goals` : '/',
+ );
+ },
+ title: t('goalDetail.deleteConfirm.title'),
+ });
+ }, [agentId, deleteGoal, goalId, navigate, onDeleted, projectId, t]);
+};
diff --git a/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.ts b/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.ts
index 698833a149b..77e4ac9a3c5 100644
--- a/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.ts
+++ b/src/features/AgentTasks/AgentTaskDetail/useTaskCopyActions.ts
@@ -1,6 +1,6 @@
import { copyToClipboard } from '@lobehub/ui';
import { toast } from '@lobehub/ui/base-ui';
-import { useCallback } from 'react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
@@ -31,18 +31,24 @@ export const useTaskCopyActions = () => {
toast.success(t('taskList.contextMenu.copyIdSuccess'));
}, [taskId, t]);
- const copyLink = useCallback(async () => {
- if (!taskId) return;
+ // Carry the title into the link so a pasted URL says what the task is.
+ const link = useMemo(
+ () =>
+ taskId
+ ? `${appOrigin}${buildWorkspaceAwarePath(
+ taskDetailPath(taskId, taskAgentId ?? undefined, taskTitle),
+ activeWorkspaceSlug,
+ )}`
+ : undefined,
+ [taskId, taskAgentId, taskTitle, appOrigin, activeWorkspaceSlug],
+ );
- // Carry the title into the copied link so a pasted URL says what the task is.
- const taskUrl = `${appOrigin}${buildWorkspaceAwarePath(
- taskDetailPath(taskId, taskAgentId ?? undefined, taskTitle),
- activeWorkspaceSlug,
- )}`;
+ const copyLink = useCallback(async () => {
+ if (!link) return;
- await copyToClipboard(taskUrl);
+ await copyToClipboard(link);
toast.success(t('taskList.contextMenu.copyLinkSuccess'));
- }, [taskId, taskAgentId, taskTitle, appOrigin, activeWorkspaceSlug, t]);
+ }, [link, t]);
- return { copyId, copyLink, taskId };
+ return { copyId, copyLink, link, taskId };
};
diff --git a/src/features/Portal/Acceptance/Header.tsx b/src/features/Portal/Acceptance/Header.tsx
index 7eb8ab54691..a6589ebe351 100644
--- a/src/features/Portal/Acceptance/Header.tsx
+++ b/src/features/Portal/Acceptance/Header.tsx
@@ -1,63 +1,23 @@
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
-import { copyToClipboard, Flexbox, Icon } from '@lobehub/ui';
-import { ActionIcon, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui/base-ui';
-import { Copy, ExternalLink, MoreHorizontal, RefreshCw } from 'lucide-react';
+import { ActionIcon } from '@lobehub/ui/base-ui';
+import { ExternalLink } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
-import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
-import { useAppOrigin } from '@/hooks/useAppOrigin';
-import { mutate as globalMutate } from '@/libs/swr';
-import { verifyKeys } from '@/libs/swr/keys';
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import Header from '../components/Header';
import Title from './Title';
+import { useAcceptancePageUrl } from './usePageUrl';
-const AcceptanceHeader = memo(() => {
+const AcceptanceHeader = memo<{ onClose?: () => void }>(({ onClose }) => {
const { t } = useTranslation('verify');
- const appOrigin = useAppOrigin();
- const activeWorkspaceSlug = useActiveWorkspaceSlug();
- const acceptanceId = useChatStore(chatPortalSelectors.acceptancePortalId);
- const pagePath = acceptanceId
- ? buildWorkspaceAwarePath(`/acceptance/${acceptanceId}`, activeWorkspaceSlug)
- : undefined;
- const pageUrl = pagePath ? `${appOrigin}${pagePath}` : undefined;
- // Without an origin the URL is relative — the system browser has nothing to resolve it against.
- const externalUrl = appOrigin && pageUrl ? pageUrl : undefined;
-
- // Secondary actions live behind the title's `…` — the header's right side
- // stays for the portal chrome (open external / close).
- const menuItems: DropdownItem[] = [
- {
- disabled: !pageUrl,
- icon: <Icon icon={Copy} />,
- key: 'copy-link',
- label: t('report.actions.copyLink'),
- onClick: async () => {
- if (!pageUrl) return;
- await copyToClipboard(pageUrl);
- toast.success(t('report.actions.copyLinkSuccess'));
- },
- },
- {
- disabled: !acceptanceId,
- icon: <Icon icon={RefreshCw} />,
- key: 'refresh',
- label: t('acceptance.actions.refresh'),
- onClick: () => {
- if (!acceptanceId) return;
- void globalMutate(verifyKeys.acceptanceBundle(acceptanceId));
- },
- },
- ];
+ const { externalUrl } = useAcceptancePageUrl();
return (
<Header
paddingInline={24}
+ title={<Title />}
rightExtra={
<ActionIcon
disabled={!externalUrl}
@@ -70,24 +30,7 @@ const AcceptanceHeader = memo(() => {
}}
/>
}
- title={
- <Flexbox horizontal align={'center'} gap={2} style={{ minWidth: 0 }}>
- <Title />
- <DropdownMenu
- iconSpaceMode={'group'}
- items={menuItems}
- placement={'bottomLeft'}
- popupProps={{ style: { minWidth: 140 } }}
- >
- <ActionIcon
- icon={MoreHorizontal}
- size={'small'}
- style={{ flex: 'none' }}
- title={t('acceptance.actions.more')}
- />
- </DropdownMenu>
- </Flexbox>
- }
+ onClose={onClose}
/>
);
});
diff --git a/src/features/Portal/Acceptance/index.ts b/src/features/Portal/Acceptance/index.ts
index 5194ef96571..9f4d324653e 100644
--- a/src/features/Portal/Acceptance/index.ts
+++ b/src/features/Portal/Acceptance/index.ts
@@ -2,5 +2,6 @@ import type { PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useAcceptanceMoreMenu } from './useMoreMenu';
-export const Acceptance: PortalImpl = { Body, Header, Title };
+export const Acceptance: PortalImpl = { Body, Header, Title, useMoreMenu: useAcceptanceMoreMenu };
diff --git a/src/features/Portal/Acceptance/useMoreMenu.ts b/src/features/Portal/Acceptance/useMoreMenu.ts
new file mode 100644
index 00000000000..21753546edf
--- /dev/null
+++ b/src/features/Portal/Acceptance/useMoreMenu.ts
@@ -0,0 +1,77 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import { openRenameModal } from '@/components/RenameModal';
+import { useAcceptanceBundle } from '@/features/Acceptance/hooks';
+import { openAcceptanceDeleteConfirm } from '@/features/Acceptance/Workspace/AcceptanceDeleteConfirm';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { usePermission } from '@/hooks/usePermission';
+import { mutate as globalMutate } from '@/libs/swr';
+import { isAcceptanceListKey, verifyKeys } from '@/libs/swr/keys';
+import { verifyService } from '@/services/verify';
+import { useChatStore } from '@/store/chat';
+
+import { useAcceptancePageUrl } from './usePageUrl';
+
+export const useAcceptanceMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const { t } = useTranslation('verify');
+ const { acceptanceId, pageUrl } = useAcceptancePageUrl();
+ // Same SWR key as the title and body, so this shares their request.
+ const { data } = useAcceptanceBundle(acceptanceId ?? null);
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+ const { allowed: canEdit } = usePermission('edit_own_content');
+
+ if (!acceptanceId) return;
+
+ // Rename and delete are the owner's: a shared acceptance opens read-only.
+ const canManage = canEdit && data?.isOwner === true;
+
+ const title = data?.subject.title || t('acceptance.titleFallback');
+ // The workspace list shows the same title, so a rename refreshes both.
+ const refreshAll = () =>
+ Promise.all([
+ globalMutate(verifyKeys.acceptanceBundle(acceptanceId)),
+ globalMutate(isAcceptanceListKey),
+ ]);
+
+ return {
+ copyId: acceptanceId,
+ copyLink: pageUrl,
+ delete: canManage
+ ? () =>
+ openAcceptanceDeleteConfirm({
+ ids: [acceptanceId],
+ onDelete: async (purge) => {
+ await verifyService.deleteAcceptance(acceptanceId, purge);
+ // Close the panel first: the bundle it shows no longer exists.
+ clearPortalStack();
+ await globalMutate(isAcceptanceListKey);
+ toast.success(t('acceptance.workspace.deleteSuccess'));
+ },
+ title,
+ })
+ : undefined,
+ refresh: () => globalMutate(verifyKeys.acceptanceBundle(acceptanceId)),
+ rename: canManage
+ ? () =>
+ openRenameModal({
+ defaultValue: title,
+ description: t('acceptance.workspace.renameModal.description'),
+ onSave: async (next) => {
+ try {
+ await verifyService.renameAcceptance(acceptanceId, next);
+ await refreshAll();
+ toast.success(t('acceptance.workspace.renameSuccess'));
+ } catch (error) {
+ console.error('[acceptance:rename]', error);
+ toast.error(t('acceptance.workspace.renameError'));
+ // The shared modal closes on a resolved save; re-throw so the
+ // typed title survives for a retry.
+ throw error;
+ }
+ },
+ title: t('acceptance.workspace.actions.rename'),
+ })
+ : undefined,
+ };
+};
diff --git a/src/features/Portal/Acceptance/usePageUrl.ts b/src/features/Portal/Acceptance/usePageUrl.ts
new file mode 100644
index 00000000000..e6203ec7d9a
--- /dev/null
+++ b/src/features/Portal/Acceptance/usePageUrl.ts
@@ -0,0 +1,20 @@
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+/** Web URL of the acceptance the portal shows; `undefined` until an id is known. */
+export const useAcceptancePageUrl = () => {
+ const appOrigin = useAppOrigin();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ const acceptanceId = useChatStore(chatPortalSelectors.acceptancePortalId);
+ const pagePath = acceptanceId
+ ? buildWorkspaceAwarePath(`/acceptance/${acceptanceId}`, activeWorkspaceSlug)
+ : undefined;
+ const pageUrl = pagePath ? `${appOrigin}${pagePath}` : undefined;
+ // Without an origin the URL is relative — the system browser has nothing to resolve it against.
+ const externalUrl = appOrigin && pageUrl ? pageUrl : undefined;
+
+ return { acceptanceId, externalUrl, pageUrl };
+};
diff --git a/src/features/Portal/AcceptanceCheck/Header.tsx b/src/features/Portal/AcceptanceCheck/Header.tsx
index 9368d7781c0..6c698986e21 100644
--- a/src/features/Portal/AcceptanceCheck/Header.tsx
+++ b/src/features/Portal/AcceptanceCheck/Header.tsx
@@ -6,7 +6,9 @@ import PortalChromeHeader from '@/features/Portal/components/Header';
import Title from './Title';
-const Header = memo(() => <PortalChromeHeader paddingInline={24} title={<Title />} />);
+const Header = memo<{ onClose?: () => void }>(({ onClose }) => (
+ <PortalChromeHeader paddingInline={24} title={<Title />} onClose={onClose} />
+));
Header.displayName = 'AcceptanceCheckPortalHeader';
diff --git a/src/features/Portal/AcceptanceCheck/index.ts b/src/features/Portal/AcceptanceCheck/index.ts
index 042952908f1..8d694e333de 100644
--- a/src/features/Portal/AcceptanceCheck/index.ts
+++ b/src/features/Portal/AcceptanceCheck/index.ts
@@ -2,5 +2,11 @@ import type { PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useAcceptanceCheckMoreMenu } from './useMoreMenu';
-export const AcceptanceCheck: PortalImpl = { Body, Header, Title };
+export const AcceptanceCheck: PortalImpl = {
+ Body,
+ Header,
+ Title,
+ useMoreMenu: useAcceptanceCheckMoreMenu,
+};
diff --git a/src/features/Portal/AcceptanceCheck/useMoreMenu.ts b/src/features/Portal/AcceptanceCheck/useMoreMenu.ts
new file mode 100644
index 00000000000..6d458a036a4
--- /dev/null
+++ b/src/features/Portal/AcceptanceCheck/useMoreMenu.ts
@@ -0,0 +1,27 @@
+import { acceptanceCheckPath } from '@/features/Acceptance/Viewer/routes';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { mutate as globalMutate } from '@/libs/swr';
+import { verifyKeys } from '@/libs/swr/keys';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
+
+import { usePortalShareUrl } from '../components/PortalMoreMenu/shareUrl';
+
+export const useAcceptanceCheckMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const portal = useChatStore(chatPortalSelectors.acceptanceCheckPortal);
+ const shareUrl = usePortalShareUrl(
+ portal ? acceptanceCheckPath(portal.acceptanceId, portal.checkId) : undefined,
+ );
+
+ if (!portal) return;
+ const { acceptanceId, checkId } = portal;
+
+ return {
+ copyId: checkId,
+ copyLink: shareUrl,
+ openInPage: shareUrl ? () => openTrustedExternalUrl(shareUrl) : undefined,
+ // A check has no cache of its own — it is read out of the acceptance bundle.
+ refresh: () => globalMutate(verifyKeys.acceptanceBundle(acceptanceId)),
+ };
+};
diff --git a/src/features/Portal/AgentDetail/Header.tsx b/src/features/Portal/AgentDetail/Header.tsx
index 49917488701..3a18b187217 100644
--- a/src/features/Portal/AgentDetail/Header.tsx
+++ b/src/features/Portal/AgentDetail/Header.tsx
@@ -13,7 +13,7 @@ import { chatPortalSelectors } from '@/store/chat/selectors';
import Title from './Title';
-const Header = memo(() => {
+const Header = memo<{ onClose?: () => void }>(({ onClose }) => {
const { t } = useTranslation('chat');
const agentId = useChatStore(chatPortalSelectors.agentDetailId);
const navigate = useWorkspaceAwareNavigate();
@@ -35,6 +35,7 @@ const Header = memo(() => {
/>
) : undefined
}
+ onClose={onClose}
/>
);
});
diff --git a/src/features/Portal/AgentDetail/index.ts b/src/features/Portal/AgentDetail/index.ts
index a2c8cd2db32..dc78986b499 100644
--- a/src/features/Portal/AgentDetail/index.ts
+++ b/src/features/Portal/AgentDetail/index.ts
@@ -2,9 +2,11 @@ import type { PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useAgentDetailMoreMenu } from './useMoreMenu';
export const AgentDetail: PortalImpl = {
Body,
Header,
Title,
+ useMoreMenu: useAgentDetailMoreMenu,
};
diff --git a/src/features/Portal/AgentDetail/useMoreMenu.test.ts b/src/features/Portal/AgentDetail/useMoreMenu.test.ts
new file mode 100644
index 00000000000..7c2ef0e6dcc
--- /dev/null
+++ b/src/features/Portal/AgentDetail/useMoreMenu.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { agentRenameField } from './useMoreMenu';
+
+vi.mock('@/components/RenameModal', () => ({ openRenameModal: vi.fn() }));
+
+describe('agentRenameField', () => {
+ it('renames the personal name when the agent has one — that is what the header shows', () => {
+ expect(agentRenameField({ name: 'Alice', title: 'Health Assistant' })).toBe('name');
+ });
+
+ it('renames the title when there is no name to show', () => {
+ expect(agentRenameField({ name: null, title: 'Health Assistant' })).toBe('title');
+ expect(agentRenameField({ title: 'Health Assistant' })).toBe('title');
+ });
+
+ it('treats a blank name as absent, like the label does', () => {
+ expect(agentRenameField({ name: ' ', title: 'Health Assistant' })).toBe('title');
+ });
+});
diff --git a/src/features/Portal/AgentDetail/useMoreMenu.ts b/src/features/Portal/AgentDetail/useMoreMenu.ts
new file mode 100644
index 00000000000..a8b0bb1e057
--- /dev/null
+++ b/src/features/Portal/AgentDetail/useMoreMenu.ts
@@ -0,0 +1,46 @@
+import { AGENT_CHAT_URL } from '@lobechat/const';
+import { agentDisplayName, type AgentNameFields } from '@lobechat/types';
+
+import { openRenameModal } from '@/components/RenameModal';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { usePermission } from '@/hooks/usePermission';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+import { usePortalShareUrl } from '../components/PortalMoreMenu/shareUrl';
+
+/**
+ * The field a rename writes: whichever one the header is showing. `name` wins
+ * the label whenever it is set, so renaming `title` under a named agent would
+ * save without visibly changing anything.
+ */
+export const agentRenameField = (meta: AgentNameFields): 'name' | 'title' =>
+ meta.name?.trim() ? 'name' : 'title';
+
+export const useAgentDetailMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const agentId = useChatStore(chatPortalSelectors.agentDetailId);
+ const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId || ''));
+ const [updateAgentMetaById, refreshAgentConfig] = useAgentStore((s) => [
+ s.updateAgentMetaById,
+ s.internal_refreshAgentConfig,
+ ]);
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const shareUrl = usePortalShareUrl(agentId ? AGENT_CHAT_URL(agentId) : undefined);
+
+ if (!agentId) return;
+
+ return {
+ copyId: agentId,
+ copyLink: shareUrl,
+ refresh: () => refreshAgentConfig(agentId),
+ rename: canEdit
+ ? () =>
+ openRenameModal({
+ defaultValue: agentDisplayName(meta, ''),
+ onSave: (next) => updateAgentMetaById(agentId, { [agentRenameField(meta)]: next }),
+ })
+ : undefined,
+ };
+};
diff --git a/src/features/Portal/Artifacts/Title.tsx b/src/features/Portal/Artifacts/Title.tsx
index 34aa83879c1..bcbe26ad9c1 100644
--- a/src/features/Portal/Artifacts/Title.tsx
+++ b/src/features/Portal/Artifacts/Title.tsx
@@ -1,9 +1,9 @@
import { ArtifactType } from '@lobechat/types';
import { Flexbox, Icon } from '@lobehub/ui';
-import { ActionIcon, Tabs, Text } from '@lobehub/ui/base-ui';
+import { Tabs, Text } from '@lobehub/ui/base-ui';
import { ConfigProvider } from 'antd';
import { cx } from 'antd-style';
-import { ArrowLeft, CodeIcon, EyeIcon } from 'lucide-react';
+import { CodeIcon, EyeIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import ArtifactDeploymentActions from '@/business/client/features/ArtifactDeploymentActions';
@@ -23,7 +23,6 @@ const Title = () => {
artifactType,
artifactTitle,
isArtifactTagClosed,
- closeArtifact,
] = useChatStore((s) => {
const messageId = chatPortalSelectors.artifactMessageId(s) || '';
const identifier = chatPortalSelectors.artifactIdentifier(s);
@@ -36,7 +35,6 @@ const Title = () => {
chatPortalSelectors.artifactType(s),
chatPortalSelectors.artifactTitle(s),
chatPortalSelectors.isArtifactTagClosed(messageId, identifier)(s),
- s.closeArtifact,
];
});
@@ -45,12 +43,10 @@ const Title = () => {
return (
<Flexbox horizontal align={'center'} flex={1} gap={12} justify={'space-between'} width={'100%'}>
- <Flexbox horizontal align={'center'} gap={4}>
- <ActionIcon icon={ArrowLeft} size={'small'} onClick={() => closeArtifact()} />
- <Text className={cx(oneLineEllipsis)} type={'secondary'}>
- {artifactTitle}
- </Text>
- </Flexbox>
+ {/* Back and close live in the shared portal header — no second arrow here. */}
+ <Text className={cx(oneLineEllipsis)} type={'secondary'}>
+ {artifactTitle}
+ </Text>
<ConfigProvider
theme={{
token: {
diff --git a/src/features/Portal/Document/CopyLinkMenuItem.tsx b/src/features/Portal/Document/CopyLinkMenuItem.tsx
deleted file mode 100644
index a7d82921136..00000000000
--- a/src/features/Portal/Document/CopyLinkMenuItem.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-'use client';
-
-import { ActionIcon } from '@lobehub/ui/base-ui';
-import { Link2 } from 'lucide-react';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { usePortalDocumentHeaderActions } from './usePortalDocumentHeader';
-
-/**
- * Copy-link action for the document portal header. Hidden entirely when the
- * viewer lacks the agent-documents binding that proves the active agent owns
- * the document (plain notebook documents have no agent route to link to).
- */
-const CopyLinkMenuItem = memo(() => {
- const { t } = useTranslation(['chat', 'file', 'common']);
- const { agentDocumentId, copyLink } = usePortalDocumentHeaderActions();
-
- if (!agentDocumentId) return null;
-
- const label = t('pageEditor.menu.copyLink', { ns: 'file' });
-
- return <ActionIcon icon={Link2} size={'small'} title={label} onClick={() => void copyLink()} />;
-});
-
-CopyLinkMenuItem.displayName = 'PortalDocumentCopyLink';
-
-export default CopyLinkMenuItem;
diff --git a/src/features/Portal/Document/Header.tsx b/src/features/Portal/Document/Header.tsx
index a9358f12e52..dab772f7e66 100644
--- a/src/features/Portal/Document/Header.tsx
+++ b/src/features/Portal/Document/Header.tsx
@@ -1,19 +1,17 @@
'use client';
import { Flexbox, Icon } from '@lobehub/ui';
-import { ActionIcon, type DropdownItem, DropdownMenu, Skeleton, Text } from '@lobehub/ui/base-ui';
+import { Skeleton, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { ChevronRight, MoreHorizontal, Pencil } from 'lucide-react';
-import { type ChangeEvent, memo, useCallback, useEffect, useMemo, useRef } from 'react';
+import { ChevronRight } from 'lucide-react';
+import { type ChangeEvent, memo, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import AutoSaveHint from './AutoSaveHint';
-import CopyLinkMenuItem from './CopyLinkMenuItem';
-import { TITLE_MAX_LENGTH, usePortalDocumentTitle } from './usePortalDocumentHeader';
+import { usePortalDocumentTitleState } from './titleContext';
+import { TITLE_MAX_LENGTH } from './usePortalDocumentHeader';
const styles = createStaticStyles(({ css }) => ({
root: css`
- flex: 1;
min-width: 0;
`,
separator: css`
@@ -85,7 +83,7 @@ interface HeaderProps {
}
const Header = memo<HeaderProps>(({ onOpenDocumentsIndex }) => {
- const { t } = useTranslation(['chat', 'file', 'common']);
+ const { t } = useTranslation('file');
const {
cancelEdit,
commitEdit,
@@ -97,7 +95,7 @@ const Header = memo<HeaderProps>(({ onOpenDocumentsIndex }) => {
startEdit,
syncIdleDraft,
titleFallback,
- } = usePortalDocumentTitle();
+ } = usePortalDocumentTitleState();
const inputRef = useRef<HTMLInputElement>(null);
@@ -106,11 +104,13 @@ const Header = memo<HeaderProps>(({ onOpenDocumentsIndex }) => {
syncIdleDraft(editing);
}, [editing, syncIdleDraft]);
- const beginEdit = useCallback(() => {
- startEdit();
- // The input mounts during this render; focus once it exists.
- requestAnimationFrame(() => inputRef.current?.focus());
- }, [startEdit]);
+ // Rename from the header's `…` menu flips the same shared edit state, so
+ // focus follows the flag rather than the click that started it.
+ useEffect(() => {
+ if (!editing) return;
+ const frame = requestAnimationFrame(() => inputRef.current?.focus());
+ return () => cancelAnimationFrame(frame);
+ }, [editing]);
const handleTitleKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
@@ -130,96 +130,52 @@ const Header = memo<HeaderProps>(({ onOpenDocumentsIndex }) => {
[cancelEdit],
);
- const menuItems = useMemo<DropdownItem[]>(() => {
- const items: DropdownItem[] = [];
-
- if (!metaLocked) {
- items.push({
- icon: <Icon icon={Pencil} />,
- key: 'rename',
- label: t('rename', { ns: 'common' }),
- onClick: beginEdit,
- });
- }
-
- return items;
- }, [beginEdit, metaLocked, t]);
-
if (isLoading) {
- return (
- <Flexbox
- horizontal
- align={'center'}
- flex={1}
- gap={12}
- justify={'space-between'}
- width={'100%'}
- >
- <Flexbox flex={1}>
- <Skeleton height={16} width={180} />
- </Flexbox>
- </Flexbox>
- );
+ return <Skeleton height={16} width={180} />;
}
return (
+ // Hug the title so the shared `…` rides right behind it; only an open
+ // editor claims the free width to type into.
<Flexbox
horizontal
align={'center'}
className={styles.root}
- flex={1}
- gap={6}
- justify={'space-between'}
- width={'100%'}
+ flex={editing ? 1 : '0 1 auto'}
+ gap={4}
>
- <Flexbox horizontal align={'center'} flex={1} gap={4} style={{ minWidth: 0 }}>
- {/* Navigable crumb gets a real button (keyboard reachable); a plain
+ {/* Navigable crumb gets a real button (keyboard reachable); a plain
notebook document renders a noninteractive label with no affordance. */}
- {onOpenDocumentsIndex ? (
- <button className={styles.crumbButton} type={'button'} onClick={onOpenDocumentsIndex}>
- {t('menu.allPages', { ns: 'file' })}
- </button>
- ) : (
- <Text className={styles.crumbLabel} color={cssVar.colorTextQuaternary}>
- {t('menu.allPages', { ns: 'file' })}
- </Text>
- )}
- <Icon className={styles.separator} icon={ChevronRight} size={14} />
- {editing ? (
- <input
- className={styles.titleInput}
- maxLength={TITLE_MAX_LENGTH}
- ref={inputRef}
- value={draft}
- onBlur={commitEdit}
- onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft(event.target.value)}
- onKeyDown={handleTitleKeyDown}
- />
- ) : (
- <Text
- className={styles.title}
- ellipsis={{ tooltip: draft || titleFallback }}
- style={{ minWidth: 0 }}
- onClick={metaLocked ? undefined : beginEdit}
- >
- {draft || titleFallback}
- </Text>
- )}
- </Flexbox>
- <Flexbox horizontal align={'center'} gap={8}>
- {!metaLocked && <AutoSaveHint />}
- <CopyLinkMenuItem />
- {menuItems.length > 0 && (
- <DropdownMenu
- iconSpaceMode={'group'}
- items={menuItems}
- placement={'bottomRight'}
- popupProps={{ style: { minWidth: 200 } }}
- >
- <ActionIcon icon={MoreHorizontal} size={'small'} />
- </DropdownMenu>
- )}
- </Flexbox>
+ {onOpenDocumentsIndex ? (
+ <button className={styles.crumbButton} type={'button'} onClick={onOpenDocumentsIndex}>
+ {t('menu.allPages', { ns: 'file' })}
+ </button>
+ ) : (
+ <Text className={styles.crumbLabel} color={cssVar.colorTextQuaternary}>
+ {t('menu.allPages', { ns: 'file' })}
+ </Text>
+ )}
+ <Icon className={styles.separator} icon={ChevronRight} size={14} />
+ {editing ? (
+ <input
+ className={styles.titleInput}
+ maxLength={TITLE_MAX_LENGTH}
+ ref={inputRef}
+ value={draft}
+ onBlur={commitEdit}
+ onChange={(event: ChangeEvent<HTMLInputElement>) => setDraft(event.target.value)}
+ onKeyDown={handleTitleKeyDown}
+ />
+ ) : (
+ <Text
+ className={styles.title}
+ ellipsis={{ tooltip: draft || titleFallback }}
+ style={{ minWidth: 0 }}
+ onClick={metaLocked ? undefined : startEdit}
+ >
+ {draft || titleFallback}
+ </Text>
+ )}
</Flexbox>
);
});
diff --git a/src/features/Portal/Document/PortalHeader.tsx b/src/features/Portal/Document/PortalHeader.tsx
index 38a983d9791..4eb32bc5824 100644
--- a/src/features/Portal/Document/PortalHeader.tsx
+++ b/src/features/Portal/Document/PortalHeader.tsx
@@ -1,22 +1,23 @@
'use client';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
+import { Flexbox } from '@lobehub/ui';
import { ActionIcon } from '@lobehub/ui/base-ui';
import { Maximize2Icon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import {
- buildAgentDocumentPath,
- buildAgentDocumentsPath,
-} from '@/features/AgentDocumentPage/navigation';
+import { buildAgentDocumentsPath } from '@/features/AgentDocumentPage/navigation';
import PortalChromeHeader from '@/features/Portal/components/Header';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
-import { useResolvedAgentDocumentId, useResolvedDocumentId } from './documentViewContext';
+import AutoSaveHint from './AutoSaveHint';
+import { useResolvedAgentDocumentId } from './documentViewContext';
import DocumentTitle from './Header';
+import { usePortalDocumentTitleState } from './titleContext';
+import { usePortalDocumentHeaderActions } from './usePortalDocumentHeader';
/**
* Expands the in-chat document portal into the full-page document route, then
@@ -24,12 +25,11 @@ import DocumentTitle from './Header';
*/
const OpenAsPageAction = memo(() => {
const { t } = useTranslation('chat');
- const documentId = useResolvedDocumentId();
- const agentId = useAgentStore((s) => s.activeAgentId);
+ const { path } = usePortalDocumentHeaderActions();
const navigate = useWorkspaceAwareNavigate();
const clearPortalStack = useChatStore((s) => s.clearPortalStack);
- if (!documentId || !agentId) return null;
+ if (!path) return null;
return (
<ActionIcon
@@ -37,7 +37,7 @@ const OpenAsPageAction = memo(() => {
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
title={t('agentDocument.openAsPage')}
onClick={() => {
- navigate(buildAgentDocumentPath(agentId, documentId));
+ navigate(path);
clearPortalStack();
}}
/>
@@ -51,6 +51,7 @@ const PortalHeader = () => {
// and that agent's index is not this document's home.
const agentDocumentId = useResolvedAgentDocumentId();
const navigate = useWorkspaceAwareNavigate();
+ const { isLoading, metaLocked } = usePortalDocumentTitleState();
// Agent documents have a documents index to land on; plain notebook
// documents keep a non-navigating crumb label.
@@ -59,8 +60,13 @@ const PortalHeader = () => {
return (
<PortalChromeHeader
- rightExtra={<OpenAsPageAction />}
title={<DocumentTitle onOpenDocumentsIndex={openDocumentsIndex} />}
+ rightExtra={
+ <Flexbox horizontal align={'center'} gap={4}>
+ {!isLoading && !metaLocked && <AutoSaveHint />}
+ <OpenAsPageAction />
+ </Flexbox>
+ }
/>
);
};
diff --git a/src/features/Portal/Document/Wrapper.tsx b/src/features/Portal/Document/Wrapper.tsx
index 3026f2a0de0..5a1c1cc514a 100644
--- a/src/features/Portal/Document/Wrapper.tsx
+++ b/src/features/Portal/Document/Wrapper.tsx
@@ -5,13 +5,18 @@ import { type PropsWithChildren } from 'react';
import { memo } from 'react';
import { useResolvedDocumentId } from './documentViewContext';
+import { PortalDocumentTitleProvider } from './titleContext';
const Wrapper = memo<PropsWithChildren>(({ children }) => {
const documentId = useResolvedDocumentId();
if (!documentId) return null;
- return <EditorProvider>{children}</EditorProvider>;
+ return (
+ <EditorProvider>
+ <PortalDocumentTitleProvider>{children}</PortalDocumentTitleProvider>
+ </EditorProvider>
+ );
});
export default Wrapper;
diff --git a/src/features/Portal/Document/index.ts b/src/features/Portal/Document/index.ts
index 09ac04e7cb5..11ff5774ce3 100644
--- a/src/features/Portal/Document/index.ts
+++ b/src/features/Portal/Document/index.ts
@@ -2,11 +2,13 @@ import { type PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import PortalHeader from './PortalHeader';
+import { useDocumentMoreMenu } from './useMoreMenu';
import Wrapper from './Wrapper';
export const Document: PortalImpl = {
Body,
Header: PortalHeader,
Title: Header,
+ useMoreMenu: useDocumentMoreMenu,
Wrapper,
};
diff --git a/src/features/Portal/Document/titleContext.tsx b/src/features/Portal/Document/titleContext.tsx
new file mode 100644
index 00000000000..ef99e0baf90
--- /dev/null
+++ b/src/features/Portal/Document/titleContext.tsx
@@ -0,0 +1,26 @@
+'use client';
+
+import { createContext, type PropsWithChildren, use } from 'react';
+
+import { usePortalDocumentTitle } from './usePortalDocumentHeader';
+
+type PortalDocumentTitleState = ReturnType<typeof usePortalDocumentTitle>;
+
+const PortalDocumentTitleContext = createContext<PortalDocumentTitleState | null>(null);
+
+/**
+ * One title edit session per portal document, shared by the inline title and
+ * the header's `…` menu — "Rename" in the menu opens the same inline editor.
+ */
+export const PortalDocumentTitleProvider = ({ children }: PropsWithChildren) => {
+ const value = usePortalDocumentTitle();
+
+ return <PortalDocumentTitleContext value={value}>{children}</PortalDocumentTitleContext>;
+};
+
+export const usePortalDocumentTitleState = (): PortalDocumentTitleState => {
+ const value = use(PortalDocumentTitleContext);
+ if (!value) throw new Error('usePortalDocumentTitleState must be used in the Document Wrapper');
+
+ return value;
+};
diff --git a/src/features/Portal/Document/useMoreMenu.ts b/src/features/Portal/Document/useMoreMenu.ts
new file mode 100644
index 00000000000..5bc79e4ccaa
--- /dev/null
+++ b/src/features/Portal/Document/useMoreMenu.ts
@@ -0,0 +1,18 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+
+import { usePortalDocumentTitleState } from './titleContext';
+import { usePortalDocumentHeaderActions } from './usePortalDocumentHeader';
+
+export const useDocumentMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const { isLoading, metaLocked, startEdit } = usePortalDocumentTitleState();
+ const { documentId, refresh, url } = usePortalDocumentHeaderActions();
+
+ if (!documentId || isLoading) return;
+
+ return {
+ copyId: documentId,
+ copyLink: url,
+ refresh,
+ rename: metaLocked ? undefined : startEdit,
+ };
+};
diff --git a/src/features/Portal/Document/usePortalDocumentHeader.test.ts b/src/features/Portal/Document/usePortalDocumentHeader.test.ts
index 74527c366f7..7b63a4ea177 100644
--- a/src/features/Portal/Document/usePortalDocumentHeader.test.ts
+++ b/src/features/Portal/Document/usePortalDocumentHeader.test.ts
@@ -1,7 +1,11 @@
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { usePortalDocumentHeaderActions, usePortalDocumentTitle } from './usePortalDocumentHeader';
+import {
+ resolvePortalDocumentPath,
+ usePortalDocumentHeaderActions,
+ usePortalDocumentTitle,
+} from './usePortalDocumentHeader';
const mockDocumentMeta = vi.hoisted(() => ({
current: {
@@ -68,7 +72,6 @@ vi.mock('@/store/chat', () => ({
const toastSuccess = vi.hoisted(() => vi.fn());
const toastError = vi.hoisted(() => vi.fn());
-const clipboardWrite = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
@@ -329,40 +332,37 @@ describe('usePortalDocumentHeaderActions', () => {
beforeEach(() => {
mockChatState.current.portalStack[0].agentDocumentId = 'agent-document-1';
mockAgentState.current.activeAgentId = 'agent-1';
- clipboardWrite.mockClear();
- toastSuccess.mockClear();
- // jsdom exposes `navigator.clipboard` as getter-only; swap it per test.
- Object.defineProperty(navigator, 'clipboard', {
- configurable: true,
- value: { writeText: clipboardWrite },
- });
});
- it('copies the agent-document URL when the binding proves ownership', async () => {
+ it('links the agent-document route when the binding proves ownership', () => {
const { result } = renderHook(() => usePortalDocumentHeaderActions());
- await act(async () => {
- await result.current.copyLink();
- });
-
- expect(clipboardWrite).toHaveBeenCalledWith(
- 'https://app.lobehub.com/agent/agent-1/docs/document-1',
- );
- expect(toastSuccess).toHaveBeenCalled();
+ expect(result.current.url).toBe('https://app.lobehub.com/agent/agent-1/docs/document-1');
});
- it('refuses to copy a link for a plain document with no agent binding', async () => {
+ it('links an unbound document (e.g. a goal deliverable) to the page editor', () => {
mockChatState.current.portalStack[0].agentDocumentId = undefined;
const { result } = renderHook(() => usePortalDocumentHeaderActions());
+ // The agent docs route redirects unowned ids to its index, so the link
+ // must not point there.
+ expect(result.current.path).toBe('/page/document-1');
+ expect(result.current.url).toBe('https://app.lobehub.com/page/document-1');
+ });
+
+ it('refresh revalidates the document caches', async () => {
+ const { result } = renderHook(() => usePortalDocumentHeaderActions());
+
await act(async () => {
- await result.current.copyLink();
+ await result.current.refresh();
});
- // No URL was composed (no-op), and no success toast fired.
- expect(clipboardWrite).not.toHaveBeenCalled();
- expect(toastSuccess).not.toHaveBeenCalled();
+ expect(mockInvalidate).toHaveBeenCalledWith({
+ agentDocumentId: 'agent-document-1',
+ agentId: 'agent-1',
+ documentId: 'document-1',
+ });
});
it('surfaces the resolved binding for menu gating', () => {
@@ -372,3 +372,11 @@ describe('usePortalDocumentHeaderActions', () => {
expect(result.current.agentId).toBe('agent-1');
});
});
+
+describe('resolvePortalDocumentPath', () => {
+ it('uses the agent docs route only for a bound document', () => {
+ expect(resolvePortalDocumentPath('docs_abc', 'agt_1', 'ad_1')).toBe('/agent/agt_1/docs/abc');
+ expect(resolvePortalDocumentPath('docs_abc', 'agt_1', undefined)).toBe('/page/abc');
+ expect(resolvePortalDocumentPath(undefined, 'agt_1', 'ad_1')).toBeUndefined();
+ });
+});
diff --git a/src/features/Portal/Document/usePortalDocumentHeader.ts b/src/features/Portal/Document/usePortalDocumentHeader.ts
index f26468d83cd..a2482f5ef4c 100644
--- a/src/features/Portal/Document/usePortalDocumentHeader.ts
+++ b/src/features/Portal/Document/usePortalDocumentHeader.ts
@@ -1,11 +1,11 @@
'use client';
-import { buildAgentDocumentUrl } from '@lobechat/builtin-tool-agent-documents';
import { toast } from '@lobehub/ui/base-ui';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { buildAgentDocumentPath } from '@/features/AgentDocumentPage/navigation';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { useSingleton } from '@/hooks/useSingleton';
import { useClientDataSWR } from '@/libs/swr';
@@ -14,6 +14,7 @@ import { documentService } from '@/services/document';
import { invalidateDocumentMutation } from '@/services/document/invalidation';
import { useAgentStore } from '@/store/agent';
import { getDocumentRenderMode } from '@/utils/documentRenderMode';
+import { standardizeIdentifier } from '@/utils/identifier';
import { isSkillMarkdownDocument } from '@/utils/skillMarkdown';
import { useResolvedAgentDocumentId, useResolvedDocumentId } from './documentViewContext';
@@ -164,37 +165,47 @@ export const usePortalDocumentTitle = () => {
};
/**
- * Header menu entries: rename (hidden when meta is locked) and copy link
- * (only when the portal viewer carries the agent-documents binding that
- * proves the active agent owns the document).
+ * In-app path of the full-page view for the portal document. An agent-bound
+ * document opens in its agent's docs route; any other document (goal
+ * deliverables, notebook docs) has no agent route to land on — that route
+ * redirects unowned ids to the docs index — so it opens in the page editor.
+ */
+export const resolvePortalDocumentPath = (
+ documentId: string | undefined,
+ agentId: string | undefined,
+ agentDocumentId: string | undefined,
+): string | undefined => {
+ if (!documentId) return undefined;
+ if (agentId && agentDocumentId) return buildAgentDocumentPath(agentId, documentId);
+ return `/page/${standardizeIdentifier(documentId)}`;
+};
+
+/**
+ * Header menu actions shared by every portal document: the absolute link to
+ * the full-page view and a refetch of the document from the server.
*/
export const usePortalDocumentHeaderActions = () => {
- const { t } = useTranslation(['chat', 'file', 'common']);
const documentId = useResolvedDocumentId();
- // The doc-anchored chat topic binds (agentId, documentId); the standalone
- // route for "copy link" needs the owning agent id, which equals the store's
- // activeAgentId inside this portal (see Body's panelEligible gate). The
- // resolved agent-documents binding is the ownership proof: a plain notebook
- // document opened beside an active agent must not produce a copy-link for an
- // agent route that doesn't own it.
+ // The resolved agent-documents binding is the ownership proof: only a bound
+ // document may be linked through the active agent's docs route.
const agentId = useAgentStore((s) => s.activeAgentId);
const agentDocumentId = useResolvedAgentDocumentId();
const appOrigin = useAppOrigin();
const activeWorkspaceSlug = useActiveWorkspaceSlug();
- const { startEdit } = usePortalDocumentTitle();
-
- const copyLink = useCallback(async () => {
- // The binding is the runtime guard too: even a stale callback handed to a
- // menu must never compose an agent-document URL for an unowned document.
- if (!documentId || !agentId || !agentDocumentId) return;
- const url = buildAgentDocumentUrl(appOrigin, agentId, documentId, {
- workspaceSlug: activeWorkspaceSlug,
+ const path = resolvePortalDocumentPath(documentId, agentId, agentDocumentId);
+ const workspacePrefix = activeWorkspaceSlug ? `/${activeWorkspaceSlug}` : '';
+ const url =
+ path && appOrigin ? `${appOrigin.replace(/\/+$/, '')}${workspacePrefix}${path}` : undefined;
+
+ const refresh = useCallback(async () => {
+ if (!documentId) return;
+ await invalidateDocumentMutation({
+ agentDocumentId,
+ agentId: agentDocumentId ? (agentId ?? undefined) : undefined,
+ documentId,
});
- if (!url) return;
- await navigator.clipboard.writeText(url);
- toast.success(t('agentDocument.linkCopied', { ns: 'chat' }));
- }, [activeWorkspaceSlug, agentDocumentId, agentId, appOrigin, documentId, t]);
+ }, [agentDocumentId, agentId, documentId]);
- return { agentDocumentId, agentId, copyLink, documentId, startEdit, t };
+ return { agentDocumentId, agentId, documentId, path, refresh, url };
};
diff --git a/src/features/Portal/FilePreview/Title.tsx b/src/features/Portal/FilePreview/Title.tsx
index ea1bc64a065..6662eba7d2e 100644
--- a/src/features/Portal/FilePreview/Title.tsx
+++ b/src/features/Portal/FilePreview/Title.tsx
@@ -1,59 +1,27 @@
-import { DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
-import { ActionIcon, Skeleton, Text } from '@lobehub/ui/base-ui';
-import { ArrowLeft, DownloadIcon, MoreHorizontalIcon } from 'lucide-react';
-import { useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
+import { Flexbox } from '@lobehub/ui';
+import { Skeleton, Text } from '@lobehub/ui/base-ui';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { useFileStore } from '@/store/file';
import { oneLineEllipsis } from '@/styles';
-import { downloadFile } from '@/utils/client/downloadFile';
const Title = () => {
- const { t } = useTranslation('portal');
- const [closeFilePreview, previewFileId] = useChatStore((s) => [
- s.closeFilePreview,
- chatPortalSelectors.previewFileId(s),
- ]);
+ const previewFileId = useChatStore(chatPortalSelectors.previewFileId);
const useFetchFileItem = useFileStore((s) => s.useFetchKnowledgeItem);
const { data, isLoading } = useFetchFileItem(previewFileId);
- const dropdownItems = useMemo(
- () =>
- data?.url
- ? [
- {
- icon: <Icon icon={DownloadIcon} />,
- key: 'download',
- label: t('FilePreview.actions.download'),
- onClick: () => downloadFile(data.url, data.name),
- },
- ]
- : [],
- [data?.url, data?.name, t],
- );
-
return (
- <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>
- <Flexbox horizontal align={'center'} gap={4} style={{ overflow: 'hidden' }}>
- <ActionIcon icon={ArrowLeft} size={'small'} onClick={() => closeFilePreview()} />
-
- {isLoading ? (
- <Skeleton height={28} />
- ) : (
- <Text className={oneLineEllipsis} style={{ fontSize: 16 }} type={'secondary'}>
- {data?.name}
- </Text>
- )}
- </Flexbox>
-
- {dropdownItems.length > 0 && (
- <DropdownMenu items={dropdownItems}>
- <ActionIcon icon={MoreHorizontalIcon} size={'small'} />
- </DropdownMenu>
+ <Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>
+ {/* Back and close live in the shared portal header — no second arrow here. */}
+ {isLoading ? (
+ <Skeleton height={28} />
+ ) : (
+ <Text className={oneLineEllipsis} style={{ fontSize: 16 }} type={'secondary'}>
+ {data?.name}
+ </Text>
)}
</Flexbox>
);
diff --git a/src/features/Portal/FilePreview/index.ts b/src/features/Portal/FilePreview/index.ts
index c75811e0bd2..33b69453c37 100644
--- a/src/features/Portal/FilePreview/index.ts
+++ b/src/features/Portal/FilePreview/index.ts
@@ -1,8 +1,10 @@
import { type PortalImpl } from '../type';
import Body from './Body';
import Title from './Title';
+import { useFilePreviewMoreMenu } from './useMoreMenu';
export const FilePreview: PortalImpl = {
Body,
Title,
+ useMoreMenu: useFilePreviewMoreMenu,
};
diff --git a/src/features/Portal/FilePreview/useMoreMenu.tsx b/src/features/Portal/FilePreview/useMoreMenu.tsx
new file mode 100644
index 00000000000..3eeaff4819a
--- /dev/null
+++ b/src/features/Portal/FilePreview/useMoreMenu.tsx
@@ -0,0 +1,34 @@
+import { Icon } from '@lobehub/ui';
+import { DownloadIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useFileStore } from '@/store/file';
+import { downloadFile } from '@/utils/client/downloadFile';
+
+export const useFilePreviewMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const { t } = useTranslation('portal');
+ const previewFileId = useChatStore(chatPortalSelectors.previewFileId);
+ const useFetchFileItem = useFileStore((s) => s.useFetchKnowledgeItem);
+ // Same SWR key as the title and body, so this shares their request.
+ const { data, mutate } = useFetchFileItem(previewFileId);
+
+ if (!previewFileId) return;
+
+ return {
+ copyId: previewFileId,
+ extraItems: data?.url
+ ? [
+ {
+ icon: <Icon icon={DownloadIcon} />,
+ key: 'download',
+ label: t('FilePreview.actions.download'),
+ onClick: () => downloadFile(data.url, data.name),
+ },
+ ]
+ : undefined,
+ refresh: () => mutate(),
+ };
+};
diff --git a/src/features/Portal/Goal/Title.tsx b/src/features/Portal/Goal/Title.tsx
index e4796e848d0..ec162cf393c 100644
--- a/src/features/Portal/Goal/Title.tsx
+++ b/src/features/Portal/Goal/Title.tsx
@@ -3,7 +3,6 @@ import { Text } from '@lobehub/ui/base-ui';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import GoalDetailActions from '@/features/AgentGoals/GoalDetailActions';
import GoalStatusGlyph from '@/features/AgentGoals/GoalStatusGlyph';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -14,24 +13,13 @@ const Title = memo(() => {
const { t } = useTranslation('chat');
const goalId = useChatStore(chatPortalSelectors.goalPortalId);
const goal = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal);
- const clearPortalStack = useChatStore((s) => s.clearPortalStack);
return (
- <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
{goal && <GoalStatusGlyph size={14} status={goal.status} />}
<Text className={oneLineEllipsis} style={{ flex: '0 1 auto', fontSize: 14, minWidth: 0 }}>
{goal?.title ?? t('goalProcess.portal.title')}
</Text>
- {goal && (
- // Deleting from the side panel keeps the user in their conversation —
- // only the panel showing the now-gone goal closes.
- <GoalDetailActions
- agentId={goal.agentId ?? undefined}
- goalId={goal.id}
- projectId={goal.projectId}
- onDeleted={clearPortalStack}
- />
- )}
</Flexbox>
);
});
diff --git a/src/features/Portal/Goal/index.ts b/src/features/Portal/Goal/index.ts
index 4444650c351..c04a29328fc 100644
--- a/src/features/Portal/Goal/index.ts
+++ b/src/features/Portal/Goal/index.ts
@@ -2,5 +2,6 @@ import { type PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useGoalMoreMenu } from './useMoreMenu';
-export const Goal: PortalImpl = { Body, Header, Title };
+export const Goal: PortalImpl = { Body, Header, Title, useMoreMenu: useGoalMoreMenu };
diff --git a/src/features/Portal/Goal/useMoreMenu.ts b/src/features/Portal/Goal/useMoreMenu.ts
new file mode 100644
index 00000000000..6f47879a92a
--- /dev/null
+++ b/src/features/Portal/Goal/useMoreMenu.ts
@@ -0,0 +1,34 @@
+import { useConfirmDeleteGoal, useGoalShareUrl } from '@/features/AgentGoals/useGoalActions';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { usePermission } from '@/hooks/usePermission';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+
+export const useGoalMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const goalId = useChatStore(chatPortalSelectors.goalPortalId);
+ const goal = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal);
+ const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+ const { allowed: canEdit } = usePermission('create_content');
+
+ const agentId = goal?.agentId ?? undefined;
+ const shareUrl = useGoalShareUrl({ agentId, goalId: goalId ?? '' });
+ // Deleting from the side panel keeps the user in their conversation — only
+ // the panel showing the now-gone goal closes.
+ const confirmDelete = useConfirmDeleteGoal({
+ agentId,
+ goalId: goalId ?? '',
+ onDeleted: clearPortalStack,
+ projectId: goal?.projectId,
+ });
+
+ if (!goalId || !goal) return;
+
+ return {
+ copyId: goalId,
+ copyLink: shareUrl,
+ delete: canEdit ? confirmDelete : undefined,
+ refresh: () => refreshGoalGraph(goalId),
+ };
+};
diff --git a/src/features/Portal/GoalMetric/index.ts b/src/features/Portal/GoalMetric/index.ts
index 26d41936904..fed164a93e7 100644
--- a/src/features/Portal/GoalMetric/index.ts
+++ b/src/features/Portal/GoalMetric/index.ts
@@ -1,5 +1,6 @@
import { type PortalImpl } from '../type';
import Body from './Body';
import Title from './Title';
+import { useGoalMetricMoreMenu } from './useMoreMenu';
-export const GoalMetric: PortalImpl = { Body, Title };
+export const GoalMetric: PortalImpl = { Body, Title, useMoreMenu: useGoalMetricMoreMenu };
diff --git a/src/features/Portal/GoalMetric/useMoreMenu.ts b/src/features/Portal/GoalMetric/useMoreMenu.ts
new file mode 100644
index 00000000000..cdbf38c1b77
--- /dev/null
+++ b/src/features/Portal/GoalMetric/useMoreMenu.ts
@@ -0,0 +1,21 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useGoalStore } from '@/store/goal';
+
+export const useGoalMetricMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const view = useChatStore(chatPortalSelectors.goalMetricView);
+ const [refreshGoalGraph, refreshGoalMetricSeries] = useGoalStore((s) => [
+ s.refreshGoalGraph,
+ s.refreshGoalMetricSeries,
+ ]);
+
+ if (!view) return;
+ const { goalId } = view;
+
+ // A metric has no id or route of its own — it is a drill-down of its goal,
+ // so the only thing to do here is re-read the goal and its time series.
+ return {
+ refresh: () => Promise.all([refreshGoalGraph(goalId), refreshGoalMetricSeries(goalId)]),
+ };
+};
diff --git a/src/features/Portal/GoalNode/Title.tsx b/src/features/Portal/GoalNode/Title.tsx
index a2c58af0800..43e443780df 100644
--- a/src/features/Portal/GoalNode/Title.tsx
+++ b/src/features/Portal/GoalNode/Title.tsx
@@ -23,9 +23,10 @@ const Title = memo(() => {
}, [snapshot, view]);
return (
- <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ // Hug the content so the shared `…` sits right after the title.
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
{node && <KindIcon kind={node.kind} />}
- <Text className={oneLineEllipsis} style={{ flex: 1, fontSize: 14, minWidth: 0 }}>
+ <Text className={oneLineEllipsis} style={{ flex: '0 1 auto', fontSize: 14, minWidth: 0 }}>
{node?.title ?? t('goalProcess.node.detailTitle')}
</Text>
</Flexbox>
diff --git a/src/features/Portal/GoalNode/index.ts b/src/features/Portal/GoalNode/index.ts
index 1f53031241b..327bf2be143 100644
--- a/src/features/Portal/GoalNode/index.ts
+++ b/src/features/Portal/GoalNode/index.ts
@@ -1,5 +1,6 @@
import { type PortalImpl } from '../type';
import Body from './Body';
import Title from './Title';
+import { useGoalNodeMoreMenu } from './useMoreMenu';
-export const GoalNode: PortalImpl = { Body, Title };
+export const GoalNode: PortalImpl = { Body, Title, useMoreMenu: useGoalNodeMoreMenu };
diff --git a/src/features/Portal/GoalNode/useMoreMenu.ts b/src/features/Portal/GoalNode/useMoreMenu.ts
new file mode 100644
index 00000000000..3c711aa80fd
--- /dev/null
+++ b/src/features/Portal/GoalNode/useMoreMenu.ts
@@ -0,0 +1,18 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useGoalStore } from '@/store/goal';
+
+export const useGoalNodeMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const view = useChatStore(chatPortalSelectors.goalNodeView);
+ const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);
+
+ if (!view) return;
+ const { goalId, nodeId } = view;
+
+ return {
+ copyId: nodeId,
+ // Nodes are read out of the goal graph.
+ refresh: () => refreshGoalGraph(goalId),
+ };
+};
diff --git a/src/features/Portal/GroupThread/Header/index.tsx b/src/features/Portal/GroupThread/Header/index.tsx
index cfaba845582..456544b0beb 100644
--- a/src/features/Portal/GroupThread/Header/index.tsx
+++ b/src/features/Portal/GroupThread/Header/index.tsx
@@ -1,57 +1,46 @@
import { agentDisplayName } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
-import { ActionIcon, Avatar } from '@lobehub/ui/base-ui';
-import { cssVar } from 'antd-style';
-import { t } from 'i18next';
-import { XIcon } from 'lucide-react';
+import { Avatar, Text } from '@lobehub/ui/base-ui';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import { DEFAULT_AVATAR } from '@/const/meta';
-import NavHeader from '@/features/NavHeader';
+import PortalHeader from '@/features/Portal/components/Header';
import { useAgentGroupStore } from '@/store/agentGroup';
-import { useChatStore } from '@/store/chat';
import { useSessionStore } from '@/store/session';
import { sessionSelectors } from '@/store/session/selectors';
-const Header = memo(() => {
- const clearPortalStack = useChatStore((s) => s.clearPortalStack);
- const close = () => {
- useAgentGroupStore.setState({ activeThreadAgentId: '' });
- clearPortalStack();
- };
+import { useGroupThreadClose } from './useClose';
+
+const Header = memo<{ onClose?: () => void }>(({ onClose }) => {
+ const { t } = useTranslation('common');
const activeThreadAgentId = useAgentGroupStore((s) => s.activeThreadAgentId);
const agents = useSessionStore(sessionSelectors.currentGroupAgents);
const currentAgent = agents?.find((agent) => agent.id === activeThreadAgentId);
+ const close = useGroupThreadClose(onClose);
+
return (
- <NavHeader
- paddingBlock={6}
- paddingInline={8}
- showTogglePanelButton={false}
- left={
- <Flexbox horizontal align={'center'} gap={8}>
+ <PortalHeader
+ title={
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
<Avatar
avatar={currentAgent?.avatar || DEFAULT_AVATAR}
background={currentAgent?.backgroundColor ?? undefined}
shape={'square'}
size={20}
/>
- <div style={{ fontWeight: 600 }}>
- {agentDisplayName(currentAgent, t('defaultSession', { ns: 'common' }))}
- </div>
+ <Text ellipsis weight={600}>
+ {agentDisplayName(currentAgent, t('defaultSession'))}
+ </Text>
</Flexbox>
}
- right={
- <Flexbox horizontal gap={4}>
- <ActionIcon icon={XIcon} size={'small'} onClick={close} />
- </Flexbox>
- }
- style={{
- background: cssVar.colorBgContainer,
- }}
+ onClose={close}
/>
);
});
+Header.displayName = 'PortalGroupThreadHeader';
+
export default Header;
diff --git a/src/features/Portal/GroupThread/Header/useClose.test.ts b/src/features/Portal/GroupThread/Header/useClose.test.ts
new file mode 100644
index 00000000000..af2554a84ad
--- /dev/null
+++ b/src/features/Portal/GroupThread/Header/useClose.test.ts
@@ -0,0 +1,33 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useGroupThreadClose } from './useClose';
+
+const mocks = vi.hoisted(() => ({ clearPortalStack: vi.fn(), setState: vi.fn() }));
+
+vi.mock('@/store/agentGroup', () => ({ useAgentGroupStore: { setState: mocks.setState } }));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) =>
+ selector({ clearPortalStack: mocks.clearPortalStack }),
+}));
+
+describe('useGroupThreadClose', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ // Regression: the hand-rolled header ignored the host's `onClose`.
+ it('forgets the DM member, then closes through the host', () => {
+ const hostClose = vi.fn();
+ renderHook(() => useGroupThreadClose(hostClose)).result.current();
+
+ expect(mocks.setState).toHaveBeenCalledWith({ activeThreadAgentId: '' });
+ expect(hostClose).toHaveBeenCalledOnce();
+ expect(mocks.clearPortalStack).not.toHaveBeenCalled();
+ });
+
+ it('closes the whole portal when the host supplies no close', () => {
+ renderHook(() => useGroupThreadClose()).result.current();
+
+ expect(mocks.setState).toHaveBeenCalledWith({ activeThreadAgentId: '' });
+ expect(mocks.clearPortalStack).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/features/Portal/GroupThread/Header/useClose.ts b/src/features/Portal/GroupThread/Header/useClose.ts
new file mode 100644
index 00000000000..eaa34bd7e63
--- /dev/null
+++ b/src/features/Portal/GroupThread/Header/useClose.ts
@@ -0,0 +1,17 @@
+import { useCallback } from 'react';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
+
+/**
+ * Closing the DM panel forgets which member it was with, then hands the close
+ * to the host when it supplied one — otherwise the whole portal stack closes.
+ */
+export const useGroupThreadClose = (onClose?: () => void) => {
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+
+ return useCallback(() => {
+ useAgentGroupStore.setState({ activeThreadAgentId: '' });
+ (onClose ?? clearPortalStack)();
+ }, [clearPortalStack, onClose]);
+};
diff --git a/src/features/Portal/GroupThread/index.ts b/src/features/Portal/GroupThread/index.ts
index 7de758ad0b7..1346d166a04 100644
--- a/src/features/Portal/GroupThread/index.ts
+++ b/src/features/Portal/GroupThread/index.ts
@@ -2,9 +2,11 @@ import { type PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useGroupThreadMoreMenu } from './useMoreMenu';
export const GroupThread: PortalImpl = {
Body,
Header,
Title,
+ useMoreMenu: useGroupThreadMoreMenu,
};
diff --git a/src/features/Portal/GroupThread/useMoreMenu.ts b/src/features/Portal/GroupThread/useMoreMenu.ts
new file mode 100644
index 00000000000..7967a2584b2
--- /dev/null
+++ b/src/features/Portal/GroupThread/useMoreMenu.ts
@@ -0,0 +1,15 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
+
+export const useGroupThreadMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const agentId = useAgentGroupStore((s) => s.activeThreadAgentId);
+ const refreshMessages = useChatStore((s) => s.refreshMessages);
+
+ if (!agentId) return;
+
+ // The DM is a client-side filter of the group topic, not an entity of its
+ // own: the member's agent id is its only handle, and refreshing re-reads the
+ // group topic it is filtered from.
+ return { copyId: agentId, refresh: () => refreshMessages() };
+};
diff --git a/src/features/Portal/LocalFile/Header.tsx b/src/features/Portal/LocalFile/Header.tsx
index b4e802b516c..5214cd95298 100644
--- a/src/features/Portal/LocalFile/Header.tsx
+++ b/src/features/Portal/LocalFile/Header.tsx
@@ -1,45 +1,26 @@
'use client';
-import {
- AGENT_CHAT_TOPIC_PAGE_URL,
- AGENT_CHAT_TOPIC_URL,
- DESKTOP_HEADER_ICON_SMALL_SIZE,
- isDesktop,
-} from '@lobechat/const';
+import { DESKTOP_HEADER_ICON_SMALL_SIZE, isDesktop } from '@lobechat/const';
import { ActionIcon } from '@lobehub/ui/base-ui';
-import { ArrowLeft, FolderOpen, X } from 'lucide-react';
-import { Fragment, memo, useCallback } from 'react';
+import { FolderOpen } from 'lucide-react';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation, useParams } from 'react-router';
-import NavHeader from '@/features/NavHeader';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import PortalHeader from '@/features/Portal/components/Header';
import { localFileService } from '@/services/electron/localFileService';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import TabStrip from './TabStrip';
-const Header = memo(() => {
+const Header = memo<{ onClose?: () => void }>(({ onClose }) => {
const { t } = useTranslation('chat');
- const location = useLocation();
- const navigate = useWorkspaceAwareNavigate();
- const params = useParams<{ aid?: string; topicId?: string }>();
const activeLocalFilePath = useChatStore(chatPortalSelectors.activeLocalFilePath);
// Sandbox-backed tabs point at paths inside the cloud sandbox, not the local
// filesystem — "show in system" would open an unrelated folder or fail.
const isSandboxFile = useChatStore(
(s) => !!chatPortalSelectors.currentLocalFile(s)?.sandboxTopicId,
);
- const [canGoBack, goBack, clearPortalStack] = useChatStore((s) => [
- chatPortalSelectors.canGoBack(s),
- s.goBack,
- s.clearPortalStack,
- ]);
- const isTopicPageRoute =
- !!params.aid &&
- !!params.topicId &&
- location.pathname.startsWith(AGENT_CHAT_TOPIC_PAGE_URL(params.aid, params.topicId));
const handleOpenFileFolder = useCallback(() => {
if (!activeLocalFilePath) return;
@@ -47,47 +28,25 @@ const Header = memo(() => {
}, [activeLocalFilePath]);
return (
- <NavHeader
- showTogglePanelButton={false}
+ <PortalHeader
+ // The tab strip runs the full header height and starts at the edge.
+ paddingInline={0}
style={{ padding: '0 8px 0 0' }}
- left={
- <Fragment>
- {canGoBack && (
- <ActionIcon icon={ArrowLeft} size={DESKTOP_HEADER_ICON_SMALL_SIZE} onClick={goBack} />
- )}
- <TabStrip />
- </Fragment>
- }
- right={
- <Fragment>
- {isDesktop && activeLocalFilePath && !isSandboxFile && (
- <ActionIcon
- icon={FolderOpen}
- size={DESKTOP_HEADER_ICON_SMALL_SIZE}
- title={t('workingPanel.files.showInSystem')}
- onClick={handleOpenFileFolder}
- />
- )}
+ title={<TabStrip />}
+ rightExtra={
+ isDesktop &&
+ activeLocalFilePath &&
+ !isSandboxFile && (
<ActionIcon
- icon={X}
+ aria-label={t('workingPanel.files.showInSystem')}
+ icon={FolderOpen}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
- onClick={() => {
- if (params.aid && params.topicId && isTopicPageRoute) {
- navigate(AGENT_CHAT_TOPIC_URL(params.aid, params.topicId));
- return;
- }
-
- clearPortalStack();
- }}
+ title={t('workingPanel.files.showInSystem')}
+ onClick={handleOpenFileFolder}
/>
- </Fragment>
+ )
}
- styles={{
- left: {
- flex: 1,
- minWidth: 0,
- },
- }}
+ onClose={onClose}
/>
);
});
diff --git a/src/features/Portal/LocalFile/TabStrip.tsx b/src/features/Portal/LocalFile/TabStrip.tsx
index cd4abddf210..b685075d470 100644
--- a/src/features/Portal/LocalFile/TabStrip.tsx
+++ b/src/features/Portal/LocalFile/TabStrip.tsx
@@ -131,7 +131,9 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const SCROLL_AREA_STYLE = {
background: 'transparent',
borderRadius: 0,
- flex: 1,
+ // Hug the tabs so the portal header's `…` sits right after the last one;
+ // still shrinks (and scrolls) once the tabs outgrow the header.
+ flex: '0 1 auto',
minWidth: 0,
};
diff --git a/src/features/Portal/LocalFile/index.ts b/src/features/Portal/LocalFile/index.ts
index 925446ac3be..785452ec22d 100644
--- a/src/features/Portal/LocalFile/index.ts
+++ b/src/features/Portal/LocalFile/index.ts
@@ -2,9 +2,11 @@ import { type PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useLocalFileMoreMenu } from './useMoreMenu';
export const LocalFile: PortalImpl = {
Body,
Header,
Title,
+ useMoreMenu: useLocalFileMoreMenu,
};
diff --git a/src/features/Portal/LocalFile/previewKeyMatcher.test.ts b/src/features/Portal/LocalFile/previewKeyMatcher.test.ts
new file mode 100644
index 00000000000..924810c0879
--- /dev/null
+++ b/src/features/Portal/LocalFile/previewKeyMatcher.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import { localFileKeys } from '@/libs/swr/keys';
+
+import { matchLocalFilePreviewKey } from './previewKeyMatcher';
+
+const tab = { filePath: '/repo/src/a.ts', workingDirectory: '/repo' };
+
+describe('matchLocalFilePreviewKey', () => {
+ it('matches every preview variant the body may key for the tab', () => {
+ const match = matchLocalFilePreviewKey(tab);
+
+ expect(match(localFileKeys.preview(tab))).toBe(true);
+ expect(match(localFileKeys.preview({ ...tab, accept: 'image' }))).toBe(true);
+ expect(match(localFileKeys.preview({ ...tab, allowExternalFile: true }))).toBe(true);
+ expect(match(localFileKeys.preview({ ...tab, resourceScope: 'workspace' }))).toBe(true);
+ });
+
+ it('still matches once the SWR layer appends the workspace id', () => {
+ expect(matchLocalFilePreviewKey(tab)([...localFileKeys.preview(tab), 'ws_1'])).toBe(true);
+ });
+
+ it('leaves other files, directories, devices and sandboxes alone', () => {
+ const match = matchLocalFilePreviewKey(tab);
+
+ expect(match(localFileKeys.preview({ ...tab, filePath: '/repo/src/b.ts' }))).toBe(false);
+ expect(match(localFileKeys.preview({ ...tab, workingDirectory: '/other' }))).toBe(false);
+ expect(match(localFileKeys.preview({ ...tab, deviceId: 'dev_1' }))).toBe(false);
+ expect(match(localFileKeys.preview({ ...tab, sandboxTopicId: 'tpc_1' }))).toBe(false);
+ expect(match(['localFile:projectIndex', 'local', '/repo'])).toBe(false);
+ expect(match('localFile:preview')).toBe(false);
+ });
+
+ it('targets the device or sandbox a tab lives on', () => {
+ const deviceTab = { ...tab, deviceId: 'dev_1' };
+ const sandboxTab = { ...tab, sandboxTopicId: 'tpc_1' };
+
+ expect(matchLocalFilePreviewKey(deviceTab)(localFileKeys.preview(deviceTab))).toBe(true);
+ expect(matchLocalFilePreviewKey(sandboxTab)(localFileKeys.preview(sandboxTab))).toBe(true);
+ });
+});
diff --git a/src/features/Portal/LocalFile/previewKeyMatcher.ts b/src/features/Portal/LocalFile/previewKeyMatcher.ts
new file mode 100644
index 00000000000..83aae40ca5d
--- /dev/null
+++ b/src/features/Portal/LocalFile/previewKeyMatcher.ts
@@ -0,0 +1,23 @@
+import { localFileKeys } from '@/libs/swr/keys';
+import { type OpenLocalFileParams } from '@/store/chat/slices/portal/initialState';
+
+type PreviewTarget = Pick<
+ OpenLocalFileParams,
+ 'deviceId' | 'filePath' | 'sandboxTopicId' | 'workingDirectory'
+>;
+
+/**
+ * `mutate` matcher for every cached preview of one open tab. The body keys its
+ * preview on more than the tab identity (image accept, external-file and
+ * resource scope flags), so the header matches on the identity prefix — the
+ * leading elements of `localFileKeys.preview` — and refreshes each variant.
+ * A workspace suffix appended by the SWR layer sits after them and is ignored.
+ */
+export const matchLocalFilePreviewKey =
+ ({ deviceId, filePath, sandboxTopicId, workingDirectory }: PreviewTarget) =>
+ (key: unknown): boolean =>
+ Array.isArray(key) &&
+ key[0] === localFileKeys.preview.root &&
+ key[1] === (sandboxTopicId ? `sandbox:${sandboxTopicId}` : (deviceId ?? 'local')) &&
+ key[2] === filePath &&
+ key[3] === workingDirectory;
diff --git a/src/features/Portal/LocalFile/useMoreMenu.ts b/src/features/Portal/LocalFile/useMoreMenu.ts
new file mode 100644
index 00000000000..98ee9b36c8a
--- /dev/null
+++ b/src/features/Portal/LocalFile/useMoreMenu.ts
@@ -0,0 +1,18 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { mutate as globalMutate } from '@/libs/swr';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+import { matchLocalFilePreviewKey } from './previewKeyMatcher';
+
+export const useLocalFileMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const file = useChatStore(chatPortalSelectors.currentLocalFile);
+
+ if (!file) return;
+
+ // A local file has no server id or shareable URL — its handle is the path.
+ return {
+ copyPath: file.filePath,
+ refresh: () => globalMutate(matchLocalFilePreviewKey(file)),
+ };
+};
diff --git a/src/features/Portal/MessageDetail/index.ts b/src/features/Portal/MessageDetail/index.ts
index ba1a275f44d..b6bcd24ab41 100644
--- a/src/features/Portal/MessageDetail/index.ts
+++ b/src/features/Portal/MessageDetail/index.ts
@@ -1,8 +1,10 @@
import { type PortalImpl } from '../type';
import Body from './Body';
import Title from './Title';
+import { useMessageDetailMoreMenu } from './useMoreMenu';
export const MessageDetail: PortalImpl = {
Body,
Title,
+ useMoreMenu: useMessageDetailMoreMenu,
};
diff --git a/src/features/Portal/MessageDetail/useMoreMenu.ts b/src/features/Portal/MessageDetail/useMoreMenu.ts
new file mode 100644
index 00000000000..34a00d921f0
--- /dev/null
+++ b/src/features/Portal/MessageDetail/useMoreMenu.ts
@@ -0,0 +1,18 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+export const useMessageDetailMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const [messageId, refreshMessages] = useChatStore((s) => [
+ chatPortalSelectors.messageDetailId(s),
+ s.refreshMessages,
+ ]);
+
+ if (!messageId) return;
+
+ return {
+ copyId: messageId,
+ // The body reads the message out of the active conversation's list.
+ refresh: () => refreshMessages(),
+ };
+};
diff --git a/src/features/Portal/Notebook/index.ts b/src/features/Portal/Notebook/index.ts
index 2708d61bb1e..a06f6b28e66 100644
--- a/src/features/Portal/Notebook/index.ts
+++ b/src/features/Portal/Notebook/index.ts
@@ -1,8 +1,10 @@
import { type PortalImpl } from '../type';
import Body from './Body';
import Title from './Title';
+import { useNotebookMoreMenu } from './useMoreMenu';
export const Notebook: PortalImpl = {
Body,
Title,
+ useMoreMenu: useNotebookMoreMenu,
};
diff --git a/src/features/Portal/Notebook/useMoreMenu.ts b/src/features/Portal/Notebook/useMoreMenu.ts
new file mode 100644
index 00000000000..2086fec3dd2
--- /dev/null
+++ b/src/features/Portal/Notebook/useMoreMenu.ts
@@ -0,0 +1,13 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useChatStore } from '@/store/chat';
+import { useNotebookStore } from '@/store/notebook';
+
+export const useNotebookMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const topicId = useChatStore((s) => s.activeTopicId);
+ const refreshDocuments = useNotebookStore((s) => s.refreshDocuments);
+
+ if (!topicId) return;
+
+ // The notebook is the topic's page list — no id, name or route of its own.
+ return { refresh: () => refreshDocuments(topicId) };
+};
diff --git a/src/features/Portal/Plugins/Header.tsx b/src/features/Portal/Plugins/Header.tsx
index 95f41b4ec10..f7d8d99914f 100644
--- a/src/features/Portal/Plugins/Header.tsx
+++ b/src/features/Portal/Plugins/Header.tsx
@@ -12,7 +12,7 @@ import Title from './Title';
* ToolUI portal header: the generic back/close chrome plus the tool's title and,
* when a tool registers them, header right-actions (e.g. prev/next nav).
*/
-const Header = () => {
+const Header = ({ onClose }: { onClose?: () => void }) => {
const [toolUIIdentifier = '', messageId] = useChatStore((s) => [
chatPortalSelectors.toolUIIdentifier(s),
chatPortalSelectors.toolMessageId(s),
@@ -35,6 +35,7 @@ const Header = () => {
/>
) : undefined
}
+ onClose={onClose}
/>
);
};
diff --git a/src/features/Portal/Plugins/index.ts b/src/features/Portal/Plugins/index.ts
index 4ab5b42eab0..de0513a21f0 100644
--- a/src/features/Portal/Plugins/index.ts
+++ b/src/features/Portal/Plugins/index.ts
@@ -2,9 +2,11 @@ import { type PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useToolUIMoreMenu } from './useMoreMenu';
export const Plugins: PortalImpl = {
Body,
Header,
Title,
+ useMoreMenu: useToolUIMoreMenu,
};
diff --git a/src/features/Portal/Plugins/useMoreMenu.ts b/src/features/Portal/Plugins/useMoreMenu.ts
new file mode 100644
index 00000000000..7298ebb88ed
--- /dev/null
+++ b/src/features/Portal/Plugins/useMoreMenu.ts
@@ -0,0 +1,13 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+export const useToolUIMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const messageId = useChatStore(chatPortalSelectors.toolMessageId);
+
+ if (!messageId) return;
+
+ // The view renders one tool-call message: its id is the only handle. The
+ // content is derived live from the chat store, so there is nothing to refresh.
+ return { copyId: messageId };
+};
diff --git a/src/features/Portal/TaskDetail/Header.tsx b/src/features/Portal/TaskDetail/Header.tsx
index 62d3d8febb7..3ed59db3175 100644
--- a/src/features/Portal/TaskDetail/Header.tsx
+++ b/src/features/Portal/TaskDetail/Header.tsx
@@ -15,7 +15,7 @@ import PortalHeader from '../components/Header';
import Title from './Title';
import { getTaskDetailPageUrl } from './url';
-const TaskDetailHeader = memo(() => {
+const TaskDetailHeader = memo<{ onClose?: () => void }>(({ onClose }) => {
const { t } = useTranslation('verify');
const appOrigin = useAppOrigin();
const activeWorkspaceSlug = useActiveWorkspaceSlug();
@@ -49,6 +49,7 @@ const TaskDetailHeader = memo(() => {
}}
/>
}
+ onClose={onClose}
/>
);
});
diff --git a/src/features/Portal/TaskDetail/Title.tsx b/src/features/Portal/TaskDetail/Title.tsx
index fdf8b6933b9..92b4233fc3b 100644
--- a/src/features/Portal/TaskDetail/Title.tsx
+++ b/src/features/Portal/TaskDetail/Title.tsx
@@ -31,12 +31,13 @@ const Title = memo(() => {
const name = detail?.name;
return (
- <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ // Hug the content so the shared `…` sits right after the name.
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
{identifier && <span className={styles.identifier}>{identifier}</span>}
{name && (
<Text
className={oneLineEllipsis}
- style={{ color: cssVar.colorText, flex: 1, fontSize: 14, minWidth: 0 }}
+ style={{ color: cssVar.colorText, flex: '0 1 auto', fontSize: 14, minWidth: 0 }}
>
{name}
</Text>
diff --git a/src/features/Portal/TaskDetail/index.ts b/src/features/Portal/TaskDetail/index.ts
index 188c65bac36..f8d7d419cf8 100644
--- a/src/features/Portal/TaskDetail/index.ts
+++ b/src/features/Portal/TaskDetail/index.ts
@@ -2,5 +2,6 @@ import { type PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useTaskDetailMoreMenu } from './useMoreMenu';
-export const TaskDetail: PortalImpl = { Body, Header, Title };
+export const TaskDetail: PortalImpl = { Body, Header, Title, useMoreMenu: useTaskDetailMoreMenu };
diff --git a/src/features/Portal/TaskDetail/useMoreMenu.test.ts b/src/features/Portal/TaskDetail/useMoreMenu.test.ts
new file mode 100644
index 00000000000..bb0fbfa4e75
--- /dev/null
+++ b/src/features/Portal/TaskDetail/useMoreMenu.test.ts
@@ -0,0 +1,90 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTaskDetailMoreMenu } from './useMoreMenu';
+
+const mocks = vi.hoisted(() => ({
+ allowed: true,
+ clearPortalStack: vi.fn(),
+ confirmModal: vi.fn(),
+ deleteTask: vi.fn(),
+ openRenameModal: vi.fn(),
+ refreshTaskDetail: vi.fn(),
+ updateTask: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({ confirmModal: mocks.confirmModal }));
+vi.mock('@/components/RenameModal', () => ({ openRenameModal: mocks.openRenameModal }));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: mocks.allowed }) }));
+vi.mock('@/features/AgentTasks/AgentTaskDetail/useTaskCopyActions', () => ({
+ useTaskCopyActions: () => ({
+ link: 'https://app.lobehub.com/agent/agt_1/task/T-7/fix-login',
+ taskId: 'T-7',
+ }),
+}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) =>
+ selector({ clearPortalStack: mocks.clearPortalStack }),
+}));
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: (s: unknown) => unknown) =>
+ selector({
+ deleteTask: mocks.deleteTask,
+ internal_refreshTaskDetail: mocks.refreshTaskDetail,
+ taskDetailMap: { 'T-7': { name: 'Fix login' } },
+ updateTask: mocks.updateTask,
+ }),
+}));
+
+describe('useTaskDetailMoreMenu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.allowed = true;
+ });
+
+ it('declares rename, copy link, copy id, refresh and delete', () => {
+ const { result } = renderHook(() => useTaskDetailMoreMenu());
+
+ expect(result.current).toMatchObject({
+ copyId: 'T-7',
+ copyLink: 'https://app.lobehub.com/agent/agt_1/task/T-7/fix-login',
+ });
+ expect(Object.keys(result.current!).sort()).toEqual(
+ ['copyId', 'copyLink', 'delete', 'refresh', 'rename'].sort(),
+ );
+ });
+
+ it('closes the panel after deleting instead of leaving for the task list', async () => {
+ const { result } = renderHook(() => useTaskDetailMoreMenu());
+ result.current!.delete!();
+
+ await mocks.confirmModal.mock.calls[0][0].onOk();
+ expect(mocks.deleteTask).toHaveBeenCalledWith('T-7');
+ expect(mocks.clearPortalStack).toHaveBeenCalledOnce();
+ });
+
+ it('renames the task name', async () => {
+ const { result } = renderHook(() => useTaskDetailMoreMenu());
+ result.current!.rename!();
+
+ const { defaultValue, onSave } = mocks.openRenameModal.mock.calls[0][0];
+ expect(defaultValue).toBe('Fix login');
+ await onSave('Fix sign-in');
+ expect(mocks.updateTask).toHaveBeenCalledWith('T-7', { name: 'Fix sign-in' });
+ });
+
+ it('refreshes the task detail cache', () => {
+ const { result } = renderHook(() => useTaskDetailMoreMenu());
+ result.current!.refresh!();
+
+ expect(mocks.refreshTaskDetail).toHaveBeenCalledWith('T-7');
+ });
+
+ it('hides rename and delete for members who cannot edit tasks', () => {
+ mocks.allowed = false;
+ const { result } = renderHook(() => useTaskDetailMoreMenu());
+
+ expect(result.current?.rename).toBeUndefined();
+ expect(result.current?.delete).toBeUndefined();
+ });
+});
diff --git a/src/features/Portal/TaskDetail/useMoreMenu.ts b/src/features/Portal/TaskDetail/useMoreMenu.ts
new file mode 100644
index 00000000000..2e5aa0edca7
--- /dev/null
+++ b/src/features/Portal/TaskDetail/useMoreMenu.ts
@@ -0,0 +1,55 @@
+import { confirmModal } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import { openRenameModal } from '@/components/RenameModal';
+import { useTaskCopyActions } from '@/features/AgentTasks/AgentTaskDetail/useTaskCopyActions';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { usePermission } from '@/hooks/usePermission';
+import { useChatStore } from '@/store/chat';
+import { useTaskStore } from '@/store/task';
+
+export const useTaskDetailMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const { t } = useTranslation('chat');
+ // The body marks this task active while the panel is open, so the copied
+ // link is byte-for-byte the one the task page's own header copies.
+ const { link, taskId } = useTaskCopyActions();
+ const name = useTaskStore((s) => (taskId ? s.taskDetailMap[taskId]?.name : undefined));
+ const [updateTask, deleteTask, refreshTaskDetail] = useTaskStore((s) => [
+ s.updateTask,
+ s.deleteTask,
+ s.internal_refreshTaskDetail,
+ ]);
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+ // Same gate as the task page's header menu.
+ const { allowed: canEdit } = usePermission('create_content');
+
+ if (!taskId) return;
+
+ return {
+ copyId: taskId,
+ copyLink: link,
+ delete: canEdit
+ ? () =>
+ confirmModal({
+ content: t('taskDetail.deleteConfirm.content'),
+ okButtonProps: { danger: true },
+ okText: t('taskDetail.deleteConfirm.ok'),
+ onOk: async () => {
+ await deleteTask(taskId);
+ // The task page redirects to the list; from a side panel only the
+ // panel showing the now-gone task closes.
+ clearPortalStack();
+ },
+ title: t('taskDetail.deleteConfirm.title'),
+ })
+ : undefined,
+ refresh: () => refreshTaskDetail(taskId),
+ rename: canEdit
+ ? () =>
+ openRenameModal({
+ defaultValue: name ?? '',
+ onSave: (next) => updateTask(taskId, { name: next }),
+ })
+ : undefined,
+ };
+};
diff --git a/src/features/Portal/TaskResult/Actions.tsx b/src/features/Portal/TaskResult/Actions.tsx
deleted file mode 100644
index efb4aa92c36..00000000000
--- a/src/features/Portal/TaskResult/Actions.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { type DropdownItem, DropdownMenu } from '@lobehub/ui';
-import { ActionIcon } from '@lobehub/ui/base-ui';
-import { CopyIcon, LinkIcon, MoreHorizontal } from 'lucide-react';
-import { memo, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { useTaskCopyActions } from '@/features/AgentTasks/AgentTaskDetail/useTaskCopyActions';
-
-/**
- * The "⋯" that rides right behind the task name, the way the goal and
- * supervision headers place theirs — the menu belongs to the thing it names,
- * not to the panel chrome on the far edge.
- */
-const Actions = memo(() => {
- const { t } = useTranslation('chat');
- // The body marks this task active while the panel is open, so the copied
- // link is byte-for-byte the one the task page's own header copies.
- const { copyId, copyLink, taskId } = useTaskCopyActions();
-
- const menuItems = useMemo<DropdownItem[]>(
- () => [
- {
- icon: LinkIcon,
- key: 'copyLink',
- label: t('taskList.contextMenu.copyLink'),
- onClick: copyLink,
- },
- {
- icon: CopyIcon,
- key: 'copyId',
- label: t('taskList.contextMenu.copyId'),
- onClick: copyId,
- },
- ],
- [copyId, copyLink, t],
- );
-
- if (!taskId) return null;
-
- return (
- <DropdownMenu items={menuItems}>
- <ActionIcon icon={MoreHorizontal} size={'small'} style={{ flexShrink: 0 }} />
- </DropdownMenu>
- );
-});
-
-Actions.displayName = 'TaskResultPortalActions';
-export default Actions;
diff --git a/src/features/Portal/TaskResult/Header.tsx b/src/features/Portal/TaskResult/Header.tsx
index 6a55d5055ab..0a4567c5263 100644
--- a/src/features/Portal/TaskResult/Header.tsx
+++ b/src/features/Portal/TaskResult/Header.tsx
@@ -9,7 +9,7 @@ import { chatPortalSelectors } from '@/store/chat/selectors';
import PortalHeader from '../components/Header';
import Title from './Title';
-const Header = memo(() => {
+const Header = memo<{ onClose?: () => void }>(({ onClose }) => {
const { t } = useTranslation('chat');
const taskId = useChatStore(chatPortalSelectors.taskResultId);
const openTaskDetail = useChatStore((state) => state.openTaskDetail);
@@ -28,6 +28,7 @@ const Header = memo(() => {
{t('goalDetail.viewOriginalTask')}
</Button>
}
+ onClose={onClose}
/>
);
});
diff --git a/src/features/Portal/TaskResult/Title.tsx b/src/features/Portal/TaskResult/Title.tsx
index 670da797553..a479d158563 100644
--- a/src/features/Portal/TaskResult/Title.tsx
+++ b/src/features/Portal/TaskResult/Title.tsx
@@ -11,7 +11,6 @@ import { chatPortalSelectors } from '@/store/chat/selectors';
import { useTaskStore } from '@/store/task';
import { oneLineEllipsis } from '@/styles';
-import Actions from './Actions';
import { useLiveRun } from './useLiveRun';
const Title = memo(() => {
@@ -25,7 +24,7 @@ const Title = memo(() => {
// then what this run is about.
if (liveRun)
return (
- <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
<AssigneeAvatar agentId={liveRun.agentId} size={20} />
<Text fontSize={14} style={{ flexShrink: 0 }} weight={500}>
{agentMeta?.title ?? liveRun.activity.author?.name}
@@ -37,14 +36,13 @@ const Title = memo(() => {
>
{liveRun.activity.title}
</Text>
- <Actions />
</Flexbox>
);
// The panel is headed by the task itself: the generic "Task result" label
// only pushed the name aside. It stays as the placeholder until the task loads.
return (
- <Flexbox horizontal align={'center'} flex={1} gap={8} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
{detail?.identifier && (
<Text fontSize={13} style={{ color: cssVar.colorTextTertiary, flexShrink: 0 }}>
{detail.identifier}
@@ -58,7 +56,6 @@ const Title = memo(() => {
>
{detail?.name || t('goalDetail.taskResult')}
</Text>
- <Actions />
</Flexbox>
);
});
diff --git a/src/features/Portal/TaskResult/index.ts b/src/features/Portal/TaskResult/index.ts
index e4fef23f528..c9172511254 100644
--- a/src/features/Portal/TaskResult/index.ts
+++ b/src/features/Portal/TaskResult/index.ts
@@ -2,5 +2,6 @@ import { type PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useTaskResultMoreMenu } from './useMoreMenu';
-export const TaskResult: PortalImpl = { Body, Header, Title };
+export const TaskResult: PortalImpl = { Body, Header, Title, useMoreMenu: useTaskResultMoreMenu };
diff --git a/src/features/Portal/TaskResult/useMoreMenu.ts b/src/features/Portal/TaskResult/useMoreMenu.ts
new file mode 100644
index 00000000000..fc228c00816
--- /dev/null
+++ b/src/features/Portal/TaskResult/useMoreMenu.ts
@@ -0,0 +1,14 @@
+import { useTaskCopyActions } from '@/features/AgentTasks/AgentTaskDetail/useTaskCopyActions';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useTaskStore } from '@/store/task';
+
+export const useTaskResultMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ // The body marks this task active while the panel is open, so the copied
+ // link is byte-for-byte the one the task page's own header copies.
+ const { link, taskId } = useTaskCopyActions();
+ const refreshTaskDetail = useTaskStore((s) => s.internal_refreshTaskDetail);
+ if (!taskId) return;
+
+ // The result is read off the task detail, so refreshing the task refreshes it.
+ return { copyId: taskId, copyLink: link, refresh: () => refreshTaskDetail(taskId) };
+};
diff --git a/src/features/Portal/Thread/Header/index.tsx b/src/features/Portal/Thread/Header/index.tsx
index 09c1ad7e031..03ee46b719e 100644
--- a/src/features/Portal/Thread/Header/index.tsx
+++ b/src/features/Portal/Thread/Header/index.tsx
@@ -1,50 +1,44 @@
-import { Flexbox } from '@lobehub/ui';
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
import { ActionIcon } from '@lobehub/ui/base-ui';
-import { cssVar } from 'antd-style';
-import { ArrowLeftRight, XIcon } from 'lucide-react';
+import { ArrowLeftRight } from 'lucide-react';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
-import NavHeader from '@/features/NavHeader';
+import PortalHeader from '@/features/Portal/components/Header';
import { useChatStore } from '@/store/chat';
import Title from './Title';
-const Header = memo(() => {
- const [hasPortal, portalThreadId, closeThreadPortal, switchThread] = useChatStore((s) => [
- !!s.portalThreadId,
+const Header = memo<{ onClose?: () => void }>(({ onClose }) => {
+ const { t } = useTranslation('thread');
+ const [portalThreadId, closeThreadPortal, switchThread] = useChatStore((s) => [
s.portalThreadId,
s.closeThreadPortal,
s.switchThread,
]);
return (
- <NavHeader
- left={<Title />}
- paddingBlock={6}
- paddingInline={8}
- showTogglePanelButton={false}
- right={
- <Flexbox horizontal gap={4}>
- {hasPortal && (
- <ActionIcon
- icon={ArrowLeftRight}
- size={'small'}
- onClick={() => {
- if (!portalThreadId) return;
-
- switchThread(portalThreadId);
- closeThreadPortal();
- }}
- />
- )}
- <ActionIcon icon={XIcon} size={'small'} onClick={closeThreadPortal} />
- </Flexbox>
+ <PortalHeader
+ title={<Title />}
+ rightExtra={
+ portalThreadId && (
+ <ActionIcon
+ aria-label={t('portal.openInMain')}
+ icon={ArrowLeftRight}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('portal.openInMain')}
+ onClick={() => {
+ switchThread(portalThreadId);
+ closeThreadPortal();
+ }}
+ />
+ )
}
- style={{
- borderBottom: `1px solid ${cssVar.colorBorderSecondary}`,
- }}
+ onClose={onClose ?? closeThreadPortal}
/>
);
});
+Header.displayName = 'PortalThreadHeader';
+
export default Header;
diff --git a/src/features/Portal/Thread/index.ts b/src/features/Portal/Thread/index.ts
index a73682c75dc..f7394b4f555 100644
--- a/src/features/Portal/Thread/index.ts
+++ b/src/features/Portal/Thread/index.ts
@@ -1,9 +1,11 @@
import { type PortalImpl } from '../type';
import Chat from './Chat';
import Header from './Header';
+import { useThreadMoreMenu } from './useMoreMenu';
export const Thread: PortalImpl = {
Body: Chat,
Header,
Title: () => null,
+ useMoreMenu: useThreadMoreMenu,
};
diff --git a/src/features/Portal/Thread/sharePath.test.ts b/src/features/Portal/Thread/sharePath.test.ts
new file mode 100644
index 00000000000..c25a81bf73c
--- /dev/null
+++ b/src/features/Portal/Thread/sharePath.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildThreadSharePath, PORTAL_THREAD_QUERY_KEY } from './sharePath';
+
+describe('buildThreadSharePath', () => {
+ it('points at the topic and reopens the thread in the side panel', () => {
+ expect(buildThreadSharePath({ agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' })).toBe(
+ '/agent/agt_1/tpc_1?portalThread=thd_1',
+ );
+ });
+
+ it('points at the group topic inside a group, not the supervisor agent', () => {
+ expect(
+ buildThreadSharePath({
+ agentId: 'agt_supervisor',
+ groupId: 'grp_1',
+ threadId: 'thd_1',
+ topicId: 'tpc_1',
+ }),
+ ).toBe('/group/grp_1/tpc_1?portalThread=thd_1');
+ });
+
+ it('uses the query key ThreadHydration reads', () => {
+ const path = buildThreadSharePath({ agentId: 'a', threadId: 'thd_1', topicId: 't' })!;
+
+ expect(new URL(path, 'https://x').searchParams.get(PORTAL_THREAD_QUERY_KEY)).toBe('thd_1');
+ expect(PORTAL_THREAD_QUERY_KEY).toBe('portalThread');
+ });
+
+ it('has no path until agent, topic and thread are all known', () => {
+ expect(
+ buildThreadSharePath({ agentId: 'a', threadId: undefined, topicId: 't' }),
+ ).toBeUndefined();
+ expect(
+ buildThreadSharePath({ agentId: 'a', threadId: 'thd', topicId: undefined }),
+ ).toBeUndefined();
+ expect(buildThreadSharePath({ agentId: null, threadId: 'thd', topicId: 't' })).toBeUndefined();
+ });
+});
diff --git a/src/features/Portal/Thread/sharePath.ts b/src/features/Portal/Thread/sharePath.ts
new file mode 100644
index 00000000000..3f99709a753
--- /dev/null
+++ b/src/features/Portal/Thread/sharePath.ts
@@ -0,0 +1,34 @@
+import { AGENT_CHAT_TOPIC_URL, GROUP_CHAT_TOPIC_URL } from '@lobechat/const';
+
+/** Query key `ThreadHydration` reads to reopen a thread in the side panel. */
+export const PORTAL_THREAD_QUERY_KEY = 'portalThread';
+
+/**
+ * Route that reopens a thread in the side panel of its topic:
+ * `/agent/<agentId>/<topicId>?portalThread=<threadId>`, or
+ * `/group/<groupId>/<topicId>?portalThread=<threadId>` inside a group, where
+ * `agentId` is the supervisor and would open a different conversation.
+ */
+export const buildThreadSharePath = ({
+ agentId,
+ groupId,
+ threadId,
+ topicId,
+}: {
+ agentId?: string | null;
+ groupId?: string | null;
+ threadId?: string | null;
+ topicId?: string | null;
+}): string | undefined => {
+ if (!topicId || !threadId) return;
+
+ const topicPath = groupId
+ ? GROUP_CHAT_TOPIC_URL(groupId, topicId)
+ : agentId
+ ? AGENT_CHAT_TOPIC_URL(agentId, topicId)
+ : undefined;
+ if (!topicPath) return;
+
+ const query = new URLSearchParams({ [PORTAL_THREAD_QUERY_KEY]: threadId });
+ return `${topicPath}?${query.toString()}`;
+};
diff --git a/src/features/Portal/Thread/useMoreMenu.test.ts b/src/features/Portal/Thread/useMoreMenu.test.ts
new file mode 100644
index 00000000000..53db926ca0e
--- /dev/null
+++ b/src/features/Portal/Thread/useMoreMenu.test.ts
@@ -0,0 +1,94 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useThreadMoreMenu } from './useMoreMenu';
+
+const mocks = vi.hoisted(() => ({
+ closeThreadPortal: vi.fn(),
+ confirmModal: vi.fn(),
+ openRenameModal: vi.fn(),
+ portalThreadId: 'thd_1' as string | undefined,
+ refreshMessages: vi.fn(),
+ refreshThreads: vi.fn(),
+ removeThread: vi.fn(),
+ thread: { agentId: null, id: 'thd_1', title: 'Side question', topicId: 'tpc_1' } as
+ Record<string, unknown> | undefined,
+ updateThreadTitle: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({ confirmModal: mocks.confirmModal }));
+vi.mock('@/components/RenameModal', () => ({ openRenameModal: mocks.openRenameModal }));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://app.lobehub.com' }));
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => null,
+}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) =>
+ selector({
+ activeAgentId: 'agt_1',
+ closeThreadPortal: mocks.closeThreadPortal,
+ portalThreadId: mocks.portalThreadId,
+ refreshMessages: mocks.refreshMessages,
+ refreshThreads: mocks.refreshThreads,
+ removeThread: mocks.removeThread,
+ updateThreadTitle: mocks.updateThreadTitle,
+ }),
+}));
+vi.mock('@/store/chat/selectors', () => ({
+ portalThreadSelectors: { portalCurrentThread: () => mocks.thread },
+}));
+
+describe('useThreadMoreMenu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.portalThreadId = 'thd_1';
+ mocks.thread = { agentId: null, id: 'thd_1', title: 'Side question', topicId: 'tpc_1' };
+ });
+
+ it('links to the topic with the thread reopened in the side panel', () => {
+ const { result } = renderHook(() => useThreadMoreMenu());
+
+ expect(result.current).toMatchObject({
+ copyId: 'thd_1',
+ copyLink: 'https://app.lobehub.com/agent/agt_1/tpc_1?portalThread=thd_1',
+ });
+ });
+
+ it('shows no menu while a thread is still being forked', () => {
+ mocks.portalThreadId = undefined;
+ mocks.thread = undefined;
+ const { result } = renderHook(() => useThreadMoreMenu());
+
+ expect(result.current).toBeUndefined();
+ });
+
+ it('closes the panel once the shown thread is deleted', async () => {
+ const { result } = renderHook(() => useThreadMoreMenu());
+ result.current!.delete!();
+
+ await mocks.confirmModal.mock.calls[0][0].onOk();
+ expect(mocks.removeThread).toHaveBeenCalledWith('thd_1');
+ expect(mocks.closeThreadPortal).toHaveBeenCalledOnce();
+ });
+
+ it('renames the thread from its current title', async () => {
+ const { result } = renderHook(() => useThreadMoreMenu());
+ result.current!.rename!();
+
+ const { defaultValue, onSave } = mocks.openRenameModal.mock.calls[0][0];
+ expect(defaultValue).toBe('Side question');
+ await onSave('Renamed');
+ expect(mocks.updateThreadTitle).toHaveBeenCalledWith('thd_1', 'Renamed');
+ });
+
+ it('refreshes the thread list and the thread messages', async () => {
+ const { result } = renderHook(() => useThreadMoreMenu());
+ await result.current!.refresh!();
+
+ expect(mocks.refreshThreads).toHaveBeenCalledOnce();
+ expect(mocks.refreshMessages).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' }),
+ );
+ });
+});
diff --git a/src/features/Portal/Thread/useMoreMenu.ts b/src/features/Portal/Thread/useMoreMenu.ts
new file mode 100644
index 00000000000..22e1e4c07f3
--- /dev/null
+++ b/src/features/Portal/Thread/useMoreMenu.ts
@@ -0,0 +1,84 @@
+import { confirmModal } from '@lobehub/ui/base-ui';
+import isEqual from 'fast-deep-equal';
+import { useTranslation } from 'react-i18next';
+
+import { openRenameModal } from '@/components/RenameModal';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { usePermission } from '@/hooks/usePermission';
+import { useChatStore } from '@/store/chat';
+import { portalThreadSelectors } from '@/store/chat/selectors';
+
+import { usePortalShareUrl } from '../components/PortalMoreMenu/shareUrl';
+import { buildThreadSharePath } from './sharePath';
+
+export const useThreadMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const { t } = useTranslation(['thread', 'common']);
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const thread = useChatStore(portalThreadSelectors.portalCurrentThread, isEqual);
+ const [
+ activeAgentId,
+ activeGroupId,
+ threadId,
+ updateThreadTitle,
+ removeThread,
+ refreshThreads,
+ refreshMessages,
+ closeThreadPortal,
+ ] = useChatStore((s) => [
+ s.activeAgentId,
+ s.activeGroupId,
+ s.portalThreadId,
+ s.updateThreadTitle,
+ s.removeThread,
+ s.refreshThreads,
+ s.refreshMessages,
+ s.closeThreadPortal,
+ ]);
+ const shareUrl = usePortalShareUrl(
+ buildThreadSharePath({
+ agentId: activeAgentId,
+ groupId: activeGroupId,
+ threadId,
+ topicId: thread?.topicId,
+ }),
+ );
+
+ // A thread being forked has no id yet — nothing to act on until it exists.
+ if (!threadId || !thread) return;
+
+ return {
+ copyId: threadId,
+ copyLink: shareUrl,
+ delete: canEdit
+ ? () =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('actions.confirmRemoveThread'),
+ okButtonProps: { danger: true },
+ okText: t('delete', { ns: 'common' }),
+ onOk: async () => {
+ await removeThread(threadId);
+ closeThreadPortal();
+ },
+ title: t('delete', { ns: 'common' }),
+ })
+ : undefined,
+ refresh: () =>
+ Promise.all([
+ refreshThreads(),
+ refreshMessages({
+ agentId: thread.agentId || activeAgentId,
+ scope: 'thread',
+ threadId,
+ topicId: thread.topicId,
+ }),
+ ]),
+ rename: canEdit
+ ? () =>
+ openRenameModal({
+ defaultValue: thread.title,
+ onSave: (next) => updateThreadTitle(threadId, next),
+ })
+ : undefined,
+ };
+};
diff --git a/src/features/Portal/Topic/Header/index.tsx b/src/features/Portal/Topic/Header/index.tsx
index 428e6f90785..de9ec0fd373 100644
--- a/src/features/Portal/Topic/Header/index.tsx
+++ b/src/features/Portal/Topic/Header/index.tsx
@@ -1,28 +1,18 @@
-import { ActionIcon } from '@lobehub/ui/base-ui';
-import { cssVar } from 'antd-style';
-import { XIcon } from 'lucide-react';
import { memo } from 'react';
-import NavHeader from '@/features/NavHeader';
+import PortalHeader from '@/features/Portal/components/Header';
import { useChatStore } from '@/store/chat';
import Title from './Title';
-const Header = memo(() => {
+const Header = memo<{ onClose?: () => void }>(({ onClose }) => {
const closeTopicPortal = useChatStore((s) => s.closeTopicPortal);
- return (
- <NavHeader
- left={<Title />}
- paddingBlock={6}
- paddingInline={8}
- right={<ActionIcon icon={XIcon} size={'small'} onClick={closeTopicPortal} />}
- showTogglePanelButton={false}
- style={{
- borderBottom: `1px solid ${cssVar.colorBorderSecondary}`,
- }}
- />
- );
+ // Closing pops only this topic view; a host-provided close (e.g. a drawer)
+ // still wins so the host can tear itself down.
+ return <PortalHeader title={<Title />} onClose={onClose ?? closeTopicPortal} />;
});
+Header.displayName = 'PortalTopicHeader';
+
export default Header;
diff --git a/src/features/Portal/Topic/index.ts b/src/features/Portal/Topic/index.ts
index 4cbdba7a10f..d7dd722f19f 100644
--- a/src/features/Portal/Topic/index.ts
+++ b/src/features/Portal/Topic/index.ts
@@ -1,9 +1,11 @@
import { type PortalImpl } from '../type';
import Chat from './Chat';
import Header from './Header';
+import { useTopicMoreMenu } from './useMoreMenu';
export const Topic: PortalImpl = {
Body: Chat,
Header,
Title: () => null,
+ useMoreMenu: useTopicMoreMenu,
};
diff --git a/src/features/Portal/Topic/useMoreMenu.test.ts b/src/features/Portal/Topic/useMoreMenu.test.ts
new file mode 100644
index 00000000000..93fd5d42cfb
--- /dev/null
+++ b/src/features/Portal/Topic/useMoreMenu.test.ts
@@ -0,0 +1,123 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTopicMoreMenu } from './useMoreMenu';
+
+const mocks = vi.hoisted(() => ({
+ activeGroupId: undefined as string | undefined,
+ allowed: true,
+ closeTopicPortal: vi.fn(),
+ confirmRemoveTopic: vi.fn(),
+ openRenameModal: vi.fn(),
+ portalTopicId: 'tpc_2' as string | undefined,
+ refreshMessages: vi.fn(),
+ removeTopic: vi.fn(),
+ updateTopicTitle: vi.fn(),
+ workspaceSlug: null as string | null,
+}));
+
+vi.mock('@/components/RenameModal', () => ({ openRenameModal: mocks.openRenameModal }));
+vi.mock('@/features/DeleteTopicConfirm', () => ({ confirmRemoveTopic: mocks.confirmRemoveTopic }));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: mocks.allowed }) }));
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://app.lobehub.com' }));
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => mocks.workspaceSlug,
+}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) =>
+ selector({
+ activeAgentId: 'agt_1',
+ activeGroupId: mocks.activeGroupId,
+ closeTopicPortal: mocks.closeTopicPortal,
+ refreshMessages: mocks.refreshMessages,
+ removeTopic: mocks.removeTopic,
+ updateTopicTitle: mocks.updateTopicTitle,
+ }),
+}));
+vi.mock('@/store/chat/selectors', () => ({
+ chatPortalSelectors: { portalTopicId: () => mocks.portalTopicId },
+ topicSelectors: { getTopicById: () => () => ({ title: 'Second topic' }) },
+}));
+
+describe('useTopicMoreMenu', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.activeGroupId = undefined;
+ mocks.allowed = true;
+ mocks.portalTopicId = 'tpc_2';
+ mocks.workspaceSlug = null;
+ });
+
+ it('declares every capability the matrix marks available for a topic', () => {
+ const { result } = renderHook(() => useTopicMoreMenu());
+
+ expect(result.current).toMatchObject({
+ copyId: 'tpc_2',
+ copyLink: 'https://app.lobehub.com/agent/agt_1/tpc_2',
+ });
+ expect(result.current?.rename).toBeTypeOf('function');
+ expect(result.current?.delete).toBeTypeOf('function');
+ expect(result.current?.refresh).toBeTypeOf('function');
+ // No full page for a topic panel — the capability is left out, not stubbed.
+ expect(result.current?.openInPage).toBeUndefined();
+ });
+
+ it('links into the active workspace', () => {
+ mocks.workspaceSlug = 'acme';
+ const { result } = renderHook(() => useTopicMoreMenu());
+
+ expect(result.current?.copyLink).toBe('https://app.lobehub.com/acme/agent/agt_1/tpc_2');
+ });
+
+ it('links to the group topic on the group screen, not the supervisor agent', () => {
+ mocks.activeGroupId = 'grp_1';
+ const { result } = renderHook(() => useTopicMoreMenu());
+
+ expect(result.current?.copyLink).toBe('https://app.lobehub.com/group/grp_1/tpc_2');
+ });
+
+ it('hides rename and delete without edit permission', () => {
+ mocks.allowed = false;
+ const { result } = renderHook(() => useTopicMoreMenu());
+
+ expect(result.current?.rename).toBeUndefined();
+ expect(result.current?.delete).toBeUndefined();
+ expect(result.current?.copyId).toBe('tpc_2');
+ });
+
+ it('closes the panel once the shown topic is deleted', async () => {
+ const { result } = renderHook(() => useTopicMoreMenu());
+ result.current!.delete!();
+
+ const { onConfirm, topicIds } = mocks.confirmRemoveTopic.mock.calls[0][0];
+ expect(topicIds).toEqual(['tpc_2']);
+ await onConfirm(true);
+
+ expect(mocks.removeTopic).toHaveBeenCalledWith('tpc_2', true);
+ expect(mocks.closeTopicPortal).toHaveBeenCalledOnce();
+ });
+
+ it('renames through the shared rename modal', async () => {
+ const { result } = renderHook(() => useTopicMoreMenu());
+ result.current!.rename!();
+
+ const { defaultValue, onSave } = mocks.openRenameModal.mock.calls[0][0];
+ expect(defaultValue).toBe('Second topic');
+ await onSave('Renamed');
+ expect(mocks.updateTopicTitle).toHaveBeenCalledWith('tpc_2', 'Renamed');
+ });
+
+ it('refreshes the messages of the panel topic, not the main column one', () => {
+ const { result } = renderHook(() => useTopicMoreMenu());
+ result.current!.refresh!();
+
+ expect(mocks.refreshMessages).toHaveBeenCalledWith({ agentId: 'agt_1', topicId: 'tpc_2' });
+ });
+
+ it('shows no menu without a topic', () => {
+ mocks.portalTopicId = undefined;
+ const { result } = renderHook(() => useTopicMoreMenu());
+
+ expect(result.current).toBeUndefined();
+ });
+});
diff --git a/src/features/Portal/Topic/useMoreMenu.ts b/src/features/Portal/Topic/useMoreMenu.ts
new file mode 100644
index 00000000000..c10b8eab801
--- /dev/null
+++ b/src/features/Portal/Topic/useMoreMenu.ts
@@ -0,0 +1,96 @@
+import { AGENT_CHAT_TOPIC_URL, GROUP_CHAT_TOPIC_URL } from '@lobechat/const';
+import { toast } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import { openRenameModal } from '@/components/RenameModal';
+import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { usePermission } from '@/hooks/usePermission';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors, topicSelectors } from '@/store/chat/selectors';
+import { isForbiddenError } from '@/utils/forbiddenError';
+
+import { usePortalShareUrl } from '../components/PortalMoreMenu/shareUrl';
+
+export const useTopicMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const { t } = useTranslation(['topic', 'common']);
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ // The side-by-side topic belongs to the conversation of the main column: an
+ // agent, or a group — where `activeAgentId` is only the supervisor.
+ const [
+ agentId,
+ groupId,
+ topicId,
+ title,
+ updateTopicTitle,
+ removeTopic,
+ refreshMessages,
+ closeTopicPortal,
+ ] = useChatStore((s) => {
+ const id = chatPortalSelectors.portalTopicId(s);
+ return [
+ s.activeAgentId,
+ s.activeGroupId,
+ id,
+ id ? topicSelectors.getTopicById(id)(s)?.title : undefined,
+ s.updateTopicTitle,
+ s.removeTopic,
+ s.refreshMessages,
+ s.closeTopicPortal,
+ ] as const;
+ });
+ const shareUrl = usePortalShareUrl(
+ !topicId
+ ? undefined
+ : groupId
+ ? GROUP_CHAT_TOPIC_URL(groupId, topicId)
+ : agentId
+ ? AGENT_CHAT_TOPIC_URL(agentId, topicId)
+ : undefined,
+ );
+
+ if (!topicId) return;
+
+ const toastWriteError = (error: unknown) =>
+ toast.error(
+ isForbiddenError(error)
+ ? t('manageOnlyCreator', { ns: 'common' })
+ : t('operationFailed', { ns: 'common' }),
+ );
+
+ return {
+ copyId: topicId,
+ copyLink: shareUrl,
+ delete: canEdit
+ ? () =>
+ void confirmRemoveTopic({
+ onConfirm: async (removeFiles) => {
+ try {
+ await removeTopic(topicId, removeFiles);
+ // The store never closes the pane showing the removed topic.
+ closeTopicPortal();
+ } catch (error) {
+ toastWriteError(error);
+ }
+ },
+ topicIds: [topicId],
+ })
+ : undefined,
+ refresh: () => refreshMessages({ agentId, topicId }),
+ rename: canEdit
+ ? () =>
+ openRenameModal({
+ defaultValue: title ?? '',
+ description: t('renameModal.description'),
+ onSave: async (next) => {
+ try {
+ await updateTopicTitle(topicId, next);
+ } catch (error) {
+ toastWriteError(error);
+ }
+ },
+ title: t('renameModal.title'),
+ })
+ : undefined,
+ };
+};
diff --git a/src/features/Portal/VerifyReport/Header.tsx b/src/features/Portal/VerifyReport/Header.tsx
index e569c341842..5d514fd64ee 100644
--- a/src/features/Portal/VerifyReport/Header.tsx
+++ b/src/features/Portal/VerifyReport/Header.tsx
@@ -1,60 +1,35 @@
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@lobechat/const';
-import { copyToClipboard, Flexbox } from '@lobehub/ui';
-import { ActionIcon, toast } from '@lobehub/ui/base-ui';
-import { Copy, ExternalLink } from 'lucide-react';
+import { ActionIcon } from '@lobehub/ui/base-ui';
+import { ExternalLink } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
-import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
-import { useAppOrigin } from '@/hooks/useAppOrigin';
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';
import Header from '../components/Header';
import Title from './Title';
+import { useVerifyReportUrl } from './useReportUrl';
-const VerifyReportHeader = memo(() => {
+const VerifyReportHeader = memo<{ onClose?: () => void }>(({ onClose }) => {
const { t } = useTranslation('verify');
- const appOrigin = useAppOrigin();
- const activeWorkspaceSlug = useActiveWorkspaceSlug();
- const runId = useChatStore(chatPortalSelectors.verifyReportRunId);
- const reportPath = runId
- ? buildWorkspaceAwarePath(`/verify/${runId}`, activeWorkspaceSlug)
- : undefined;
- const reportUrl = reportPath ? `${appOrigin}${reportPath}` : undefined;
- // Without an origin the URL is relative — the system browser has nothing to resolve it against.
- const externalUrl = appOrigin && reportUrl ? reportUrl : undefined;
+ const { externalUrl } = useVerifyReportUrl();
return (
<Header
title={<Title />}
rightExtra={
- <Flexbox horizontal gap={4}>
- <ActionIcon
- disabled={!reportUrl}
- icon={Copy}
- size={DESKTOP_HEADER_ICON_SMALL_SIZE}
- title={t('report.actions.copyLink')}
- onClick={async () => {
- if (!reportUrl) return;
- await copyToClipboard(reportUrl);
- toast.success(t('report.actions.copyLinkSuccess'));
- }}
- />
- <ActionIcon
- disabled={!externalUrl}
- icon={ExternalLink}
- size={DESKTOP_HEADER_ICON_SMALL_SIZE}
- title={t('report.actions.openInBrowser')}
- onClick={() => {
- if (!externalUrl) return;
- openTrustedExternalUrl(externalUrl);
- }}
- />
- </Flexbox>
+ <ActionIcon
+ disabled={!externalUrl}
+ icon={ExternalLink}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('report.actions.openInBrowser')}
+ onClick={() => {
+ if (!externalUrl) return;
+ openTrustedExternalUrl(externalUrl);
+ }}
+ />
}
+ onClose={onClose}
/>
);
});
diff --git a/src/features/Portal/VerifyReport/index.ts b/src/features/Portal/VerifyReport/index.ts
index 51a4b247098..a0844a9d9a0 100644
--- a/src/features/Portal/VerifyReport/index.ts
+++ b/src/features/Portal/VerifyReport/index.ts
@@ -2,5 +2,11 @@ import type { PortalImpl } from '../type';
import Body from './Body';
import Header from './Header';
import Title from './Title';
+import { useVerifyReportMoreMenu } from './useMoreMenu';
-export const VerifyReport: PortalImpl = { Body, Header, Title };
+export const VerifyReport: PortalImpl = {
+ Body,
+ Header,
+ Title,
+ useMoreMenu: useVerifyReportMoreMenu,
+};
diff --git a/src/features/Portal/VerifyReport/useMoreMenu.test.ts b/src/features/Portal/VerifyReport/useMoreMenu.test.ts
new file mode 100644
index 00000000000..3a3b9e4dc87
--- /dev/null
+++ b/src/features/Portal/VerifyReport/useMoreMenu.test.ts
@@ -0,0 +1,46 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useVerifyReportMoreMenu } from './useMoreMenu';
+
+const mocks = vi.hoisted(() => ({
+ allowed: true,
+ isOwner: true,
+}));
+
+vi.mock('@/components/RenameModal', () => ({ openRenameModal: vi.fn() }));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: mocks.allowed }) }));
+vi.mock('@/libs/swr', () => ({ mutate: vi.fn() }));
+vi.mock('@/services/verify', () => ({ verifyService: { updateRunTitle: vi.fn() } }));
+vi.mock('./useReportUrl', () => ({
+ useVerifyReportUrl: () => ({ reportUrl: 'https://app.lobehub.com/verify/run_1', runId: 'run_1' }),
+}));
+vi.mock('@/features/Acceptance/hooks', () => ({
+ useVerifyReportBundle: () => ({
+ data: { isOwner: mocks.isOwner, report: null, results: [], run: { title: 'Run' } },
+ }),
+}));
+
+describe('useVerifyReportMoreMenu', () => {
+ beforeEach(() => {
+ mocks.allowed = true;
+ mocks.isOwner = true;
+ });
+
+ it('offers rename to the author of the run', () => {
+ const { result } = renderHook(() => useVerifyReportMoreMenu());
+
+ expect(result.current?.rename).toBeTypeOf('function');
+ });
+
+ it('hides rename on a public report opened by someone else', () => {
+ mocks.isOwner = false;
+ const { result } = renderHook(() => useVerifyReportMoreMenu());
+
+ expect(result.current?.rename).toBeUndefined();
+ expect(result.current).toMatchObject({
+ copyId: 'run_1',
+ copyLink: 'https://app.lobehub.com/verify/run_1',
+ });
+ });
+});
diff --git a/src/features/Portal/VerifyReport/useMoreMenu.ts b/src/features/Portal/VerifyReport/useMoreMenu.ts
new file mode 100644
index 00000000000..201bc576fc7
--- /dev/null
+++ b/src/features/Portal/VerifyReport/useMoreMenu.ts
@@ -0,0 +1,55 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+import { openRenameModal } from '@/components/RenameModal';
+import { useVerifyReportBundle } from '@/features/Acceptance/hooks';
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { usePermission } from '@/hooks/usePermission';
+import { mutate as globalMutate } from '@/libs/swr';
+import { verifyKeys } from '@/libs/swr/keys';
+import { verifyService } from '@/services/verify';
+
+import { useVerifyReportUrl } from './useReportUrl';
+
+export const useVerifyReportMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const { t } = useTranslation('verify');
+ const { reportUrl, runId } = useVerifyReportUrl();
+ // Same SWR key as the title and body, so this shares their request.
+ const { data } = useVerifyReportBundle(runId ?? null);
+ const { allowed: canEdit } = usePermission('edit_own_content');
+
+ if (!runId) return;
+
+ const refresh = () => globalMutate(verifyKeys.reportBundle(runId));
+
+ return {
+ copyId: runId,
+ copyLink: reportUrl,
+ refresh,
+ rename:
+ // Report URLs are public; only the author can rename the run.
+ canEdit && data?.isOwner
+ ? () =>
+ openRenameModal({
+ defaultValue: data.run.title ?? '',
+ onSave: async (next) => {
+ try {
+ await verifyService.updateRunTitle(runId, next);
+ await Promise.all([
+ refresh(),
+ globalMutate(
+ (key) => Array.isArray(key) && key[0] === verifyKeys.reportSummaries.root,
+ ),
+ ]);
+ toast.success(t('workspace.renameSuccess'));
+ } catch (error) {
+ console.error('[verify-report:rename]', error);
+ toast.error(t('workspace.renameError'));
+ // Keep the modal open with the typed title for a retry.
+ throw error;
+ }
+ },
+ })
+ : undefined,
+ };
+};
diff --git a/src/features/Portal/VerifyReport/useReportUrl.ts b/src/features/Portal/VerifyReport/useReportUrl.ts
new file mode 100644
index 00000000000..cf195ba9c85
--- /dev/null
+++ b/src/features/Portal/VerifyReport/useReportUrl.ts
@@ -0,0 +1,20 @@
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+/** Web URL of the verify report the portal shows; `undefined` until a run id is known. */
+export const useVerifyReportUrl = () => {
+ const appOrigin = useAppOrigin();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ const runId = useChatStore(chatPortalSelectors.verifyReportRunId);
+ const reportPath = runId
+ ? buildWorkspaceAwarePath(`/verify/${runId}`, activeWorkspaceSlug)
+ : undefined;
+ const reportUrl = reportPath ? `${appOrigin}${reportPath}` : undefined;
+ // Without an origin the URL is relative — the system browser has nothing to resolve it against.
+ const externalUrl = appOrigin && reportUrl ? reportUrl : undefined;
+
+ return { externalUrl, reportUrl, runId };
+};
diff --git a/src/features/Portal/VerifyResult/index.ts b/src/features/Portal/VerifyResult/index.ts
index f1d11a2bb60..149051c3424 100644
--- a/src/features/Portal/VerifyResult/index.ts
+++ b/src/features/Portal/VerifyResult/index.ts
@@ -1,8 +1,10 @@
import { type PortalImpl } from '../type';
import Body from './Body';
import Title from './Title';
+import { useVerifyResultMoreMenu } from './useMoreMenu';
export const VerifyResult: PortalImpl = {
Body,
Title,
+ useMoreMenu: useVerifyResultMoreMenu,
};
diff --git a/src/features/Portal/VerifyResult/useMoreMenu.ts b/src/features/Portal/VerifyResult/useMoreMenu.ts
new file mode 100644
index 00000000000..362efa09821
--- /dev/null
+++ b/src/features/Portal/VerifyResult/useMoreMenu.ts
@@ -0,0 +1,23 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { mutate as globalMutate } from '@/libs/swr';
+import { verifyKeys } from '@/libs/swr/keys';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+export const useVerifyResultMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const operationId = useChatStore(chatPortalSelectors.verifyResultOperationId);
+ const checkItemId = useChatStore(chatPortalSelectors.verifyResultCheckItemId);
+
+ if (!operationId || !checkItemId) return;
+
+ return {
+ // The plan item id — the handle `lh verify` commands and evidence take.
+ copyId: checkItemId,
+ // Title reads the plan (state), the badge and body read the results.
+ refresh: () =>
+ Promise.all([
+ globalMutate(verifyKeys.state(operationId)),
+ globalMutate(verifyKeys.results(operationId)),
+ ]),
+ };
+};
diff --git a/src/features/Portal/components/Header.tsx b/src/features/Portal/components/Header.tsx
index 791e4fec171..9e8b93227d6 100644
--- a/src/features/Portal/components/Header.tsx
+++ b/src/features/Portal/components/Header.tsx
@@ -8,7 +8,7 @@ import {
import { Flexbox } from '@lobehub/ui';
import { ActionIcon } from '@lobehub/ui/base-ui';
import { ArrowLeft, X } from 'lucide-react';
-import { Fragment, type ReactNode } from 'react';
+import { type CSSProperties, Fragment, type ReactNode } from 'react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useParams } from 'react-router';
@@ -18,12 +18,16 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { PortalMoreMenuSlot } from './PortalMoreMenu/context';
+
const Header = memo<{
onClose?: () => void;
paddingInline?: number;
rightExtra?: ReactNode;
+ /** Overrides the default block/inline padding, e.g. for a full-height tab strip. */
+ style?: CSSProperties;
title: ReactNode;
-}>(({ onClose, paddingInline = 8, rightExtra, title }) => {
+}>(({ onClose, paddingInline = 8, rightExtra, style, title }) => {
const { t } = useTranslation('common');
const location = useLocation();
const navigate = useWorkspaceAwareNavigate();
@@ -41,7 +45,7 @@ const Header = memo<{
return (
<NavHeader
showTogglePanelButton={false}
- style={{ paddingBlock: 8, paddingInline, width: '100%' }}
+ style={{ paddingBlock: 8, paddingInline, width: '100%', ...style }}
left={
<Flexbox horizontal align="center" flex={1} gap={4} style={{ minWidth: 0 }}>
{canGoBack && (
@@ -54,6 +58,9 @@ const Header = memo<{
/>
)}
{title}
+ {/* The `…` belongs to the thing the title names, not to the panel
+ chrome on the far edge, so it rides right behind the title. */}
+ <PortalMoreMenuSlot />
</Flexbox>
}
right={
diff --git a/src/features/Portal/components/PortalMoreMenu/buildItems.test.ts b/src/features/Portal/components/PortalMoreMenu/buildItems.test.ts
new file mode 100644
index 00000000000..d6450acb30c
--- /dev/null
+++ b/src/features/Portal/components/PortalMoreMenu/buildItems.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildPortalMoreMenuItems } from './buildItems';
+import { type PortalMoreMenuConfig } from './types';
+
+const t = (key: string) => `t:${key}`;
+
+const build = (config: PortalMoreMenuConfig | undefined, copy = vi.fn()) =>
+ buildPortalMoreMenuItems(config, { copy, t });
+
+const keysOf = (items: ReturnType<typeof build>) =>
+ items.map((item) => (item && 'type' in item && item.type === 'divider' ? '|' : item?.key));
+
+describe('buildPortalMoreMenuItems', () => {
+ it('renders nothing without a config or with no capability declared', () => {
+ expect(build(undefined)).toEqual([]);
+ expect(build({})).toEqual([]);
+ });
+
+ it('orders every capability in the shared fixed order with group dividers', () => {
+ const items = build({
+ copyId: 'id_1',
+ copyLink: 'https://app.lobehub.com/x',
+ delete: vi.fn(),
+ extraItems: [{ key: 'download', label: 'Download' }],
+ openInPage: vi.fn(),
+ refresh: vi.fn(),
+ rename: vi.fn(),
+ });
+
+ expect(keysOf(items)).toEqual([
+ 'rename',
+ '|',
+ 'copyLink',
+ 'copyId',
+ 'openInPage',
+ 'refresh',
+ '|',
+ 'download',
+ '|',
+ 'delete',
+ ]);
+ });
+
+ it('places copy path right after copy id in the share group', () => {
+ const items = build({ copyId: 'id_1', copyPath: '/repo/a.ts', refresh: vi.fn() });
+
+ expect(keysOf(items)).toEqual(['copyId', 'copyPath', 'refresh']);
+ });
+
+ it('copies a path with its own label and success message', () => {
+ const copy = vi.fn();
+ const [item] = build({ copyPath: '/repo/a.ts' }, copy);
+
+ expect(item).toMatchObject({ label: 't:moreMenu.copyPath' });
+ (item as any).onClick();
+ expect(copy).toHaveBeenCalledWith('/repo/a.ts', 'moreMenu.copyPathSuccess');
+ });
+
+ it('ignores the declaration order of the config', () => {
+ const items = build({
+ delete: vi.fn(),
+ refresh: vi.fn(),
+ copyId: 'id_1',
+ rename: vi.fn(),
+ });
+
+ expect(keysOf(items)).toEqual(['rename', '|', 'copyId', 'refresh', '|', 'delete']);
+ });
+
+ it('hides unsupported capabilities instead of disabling them', () => {
+ const items = build({ copyId: 'id_1', copyLink: undefined, delete: undefined });
+
+ expect(keysOf(items)).toEqual(['copyId']);
+ expect(items.some((item) => item && 'disabled' in item && item.disabled)).toBe(false);
+ });
+
+ it('drops the divider of an empty group (no leading or doubled dividers)', () => {
+ expect(keysOf(build({ delete: vi.fn(), refresh: vi.fn() }))).toEqual([
+ 'refresh',
+ '|',
+ 'delete',
+ ]);
+ expect(keysOf(build({ delete: vi.fn() }))).toEqual(['delete']);
+ expect(keysOf(build({ extraItems: [], rename: vi.fn() }))).toEqual(['rename']);
+ });
+
+ it('labels items from the portal namespace and marks delete as danger', () => {
+ const items = build({ delete: vi.fn(), rename: vi.fn() });
+
+ expect(items[0]).toMatchObject({ label: 't:moreMenu.rename' });
+ expect(items.at(-1)).toMatchObject({ danger: true, label: 't:moreMenu.delete' });
+ });
+
+ it('copies link and id with their own success messages', () => {
+ const copy = vi.fn();
+ const items = build({ copyId: 'id_1', copyLink: 'https://app.lobehub.com/x' }, copy);
+
+ (items[0] as any).onClick();
+ (items[1] as any).onClick();
+
+ expect(copy).toHaveBeenNthCalledWith(
+ 1,
+ 'https://app.lobehub.com/x',
+ 'moreMenu.copyLinkSuccess',
+ );
+ expect(copy).toHaveBeenNthCalledWith(2, 'id_1', 'moreMenu.copyIdSuccess');
+ });
+
+ it('wires action capabilities straight to their handlers', () => {
+ const config = {
+ delete: vi.fn(),
+ openInPage: vi.fn(),
+ refresh: vi.fn(),
+ rename: vi.fn(),
+ };
+ const items = build(config);
+ const byKey = (key: string) => items.find((item) => item?.key === key) as any;
+
+ byKey('rename').onClick();
+ byKey('openInPage').onClick();
+ byKey('refresh').onClick();
+ byKey('delete').onClick();
+
+ expect(config.rename).toHaveBeenCalledOnce();
+ expect(config.openInPage).toHaveBeenCalledOnce();
+ expect(config.refresh).toHaveBeenCalledOnce();
+ expect(config.delete).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/features/Portal/components/PortalMoreMenu/buildItems.ts b/src/features/Portal/components/PortalMoreMenu/buildItems.ts
new file mode 100644
index 00000000000..04e6ac8d582
--- /dev/null
+++ b/src/features/Portal/components/PortalMoreMenu/buildItems.ts
@@ -0,0 +1,102 @@
+import { Icon } from '@lobehub/ui';
+import { type DropdownItem } from '@lobehub/ui/base-ui';
+import { Copy, FileText, Link, Maximize2, Pencil, RotateCw, Trash2 } from 'lucide-react';
+import { createElement } from 'react';
+
+import { type PortalMoreMenuConfig } from './types';
+
+export type PortalMoreMenuLabelKey =
+ | 'moreMenu.copyId'
+ | 'moreMenu.copyIdSuccess'
+ | 'moreMenu.copyLink'
+ | 'moreMenu.copyLinkSuccess'
+ | 'moreMenu.copyPath'
+ | 'moreMenu.copyPathSuccess'
+ | 'moreMenu.delete'
+ | 'moreMenu.openInPage'
+ | 'moreMenu.refresh'
+ | 'moreMenu.rename';
+
+interface BuildOptions {
+ copy: (value: string, successKey: PortalMoreMenuLabelKey) => void;
+ t: (key: PortalMoreMenuLabelKey) => string;
+}
+
+/**
+ * Maps declared capabilities to menu items in the one fixed order every
+ * portal shares:
+ *
+ * rename | copy link, copy id, copy path, open in page, refresh | extra items | delete
+ *
+ * Groups with nothing declared vanish together with their divider.
+ */
+export const buildPortalMoreMenuItems = (
+ config: PortalMoreMenuConfig | undefined,
+ { copy, t }: BuildOptions,
+): DropdownItem[] => {
+ if (!config) return [];
+
+ const edit: DropdownItem[] = [];
+ if (config.rename)
+ edit.push({
+ icon: createElement(Icon, { icon: Pencil }),
+ key: 'rename',
+ label: t('moreMenu.rename'),
+ onClick: config.rename,
+ });
+
+ const share: DropdownItem[] = [];
+ const { copyId, copyLink, copyPath } = config;
+ if (copyLink)
+ share.push({
+ icon: createElement(Icon, { icon: Link }),
+ key: 'copyLink',
+ label: t('moreMenu.copyLink'),
+ onClick: () => copy(copyLink, 'moreMenu.copyLinkSuccess'),
+ });
+ if (copyId)
+ share.push({
+ icon: createElement(Icon, { icon: Copy }),
+ key: 'copyId',
+ label: t('moreMenu.copyId'),
+ onClick: () => copy(copyId, 'moreMenu.copyIdSuccess'),
+ });
+ if (copyPath)
+ share.push({
+ icon: createElement(Icon, { icon: FileText }),
+ key: 'copyPath',
+ label: t('moreMenu.copyPath'),
+ onClick: () => copy(copyPath, 'moreMenu.copyPathSuccess'),
+ });
+ if (config.openInPage)
+ share.push({
+ icon: createElement(Icon, { icon: Maximize2 }),
+ key: 'openInPage',
+ label: t('moreMenu.openInPage'),
+ onClick: config.openInPage,
+ });
+ const { refresh } = config;
+ if (refresh)
+ share.push({
+ icon: createElement(Icon, { icon: RotateCw }),
+ key: 'refresh',
+ label: t('moreMenu.refresh'),
+ onClick: () => void refresh(),
+ });
+
+ const danger: DropdownItem[] = [];
+ if (config.delete)
+ danger.push({
+ danger: true,
+ icon: createElement(Icon, { icon: Trash2 }),
+ key: 'delete',
+ label: t('moreMenu.delete'),
+ onClick: config.delete,
+ });
+
+ const groups = [edit, share, config.extraItems ?? [], danger].filter((group) => group.length);
+
+ return groups.flatMap((group, index) =>
+ index === 0 ? group : [{ key: `divider-${index}`, type: 'divider' } as DropdownItem, ...group],
+ );
+};
diff --git a/src/features/Portal/components/PortalMoreMenu/context.tsx b/src/features/Portal/components/PortalMoreMenu/context.tsx
new file mode 100644
index 00000000000..16b6a2214a1
--- /dev/null
+++ b/src/features/Portal/components/PortalMoreMenu/context.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { createContext, memo, use } from 'react';
+
+import PortalMoreMenu from './index';
+import { type UsePortalMoreMenu } from './types';
+
+interface PortalMoreMenuSource {
+ /** Remounts the hook host when the view changes, so hook order never mixes. */
+ key: string;
+ useMoreMenu: UsePortalMoreMenu;
+}
+
+const PortalMoreMenuContext = createContext<PortalMoreMenuSource | null>(null);
+
+/** Set by the portal router around the active view's header. */
+export const PortalMoreMenuProvider = PortalMoreMenuContext.Provider;
+
+const MoreMenuHost = memo<{ useMoreMenu: UsePortalMoreMenu }>(({ useMoreMenu }) => {
+ const config = useMoreMenu();
+
+ return <PortalMoreMenu config={config} />;
+});
+
+MoreMenuHost.displayName = 'PortalMoreMenuHost';
+
+/** Title-slot mount point in the shared header; empty for views with no menu. */
+export const PortalMoreMenuSlot = memo(() => {
+ const source = use(PortalMoreMenuContext);
+ if (!source) return null;
+
+ return <MoreMenuHost key={source.key} useMoreMenu={source.useMoreMenu} />;
+});
+
+PortalMoreMenuSlot.displayName = 'PortalMoreMenuSlot';
diff --git a/src/features/Portal/components/PortalMoreMenu/index.tsx b/src/features/Portal/components/PortalMoreMenu/index.tsx
new file mode 100644
index 00000000000..d657c2c7a11
--- /dev/null
+++ b/src/features/Portal/components/PortalMoreMenu/index.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import { copyToClipboard } from '@lobehub/ui';
+import { ActionIcon, DropdownMenu, toast } from '@lobehub/ui/base-ui';
+import { MoreHorizontal } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { buildPortalMoreMenuItems } from './buildItems';
+import { type PortalMoreMenuConfig } from './types';
+
+interface PortalMoreMenuProps {
+ config?: PortalMoreMenuConfig;
+}
+
+/**
+ * The one `…` every portal header shows right after its title. Portals never
+ * render it themselves — they declare capabilities on `PortalImpl.useMoreMenu`
+ * and the shared header mounts this menu in its title slot.
+ */
+const PortalMoreMenu = memo<PortalMoreMenuProps>(({ config }) => {
+ const { t } = useTranslation('portal');
+
+ const items = useMemo(
+ () =>
+ buildPortalMoreMenuItems(config, {
+ copy: async (value, successKey) => {
+ await copyToClipboard(value);
+ toast.success(t(successKey));
+ },
+ t: (key) => t(key),
+ }),
+ [config, t],
+ );
+
+ if (items.length === 0) return null;
+
+ return (
+ <DropdownMenu
+ iconSpaceMode={'group'}
+ items={items}
+ placement={'bottomLeft'}
+ popupProps={{ style: { minWidth: 180 } }}
+ >
+ <ActionIcon
+ aria-label={t('moreMenu.trigger')}
+ icon={MoreHorizontal}
+ size={'small'}
+ style={{ flex: 'none' }}
+ title={t('moreMenu.trigger')}
+ />
+ </DropdownMenu>
+ );
+});
+
+PortalMoreMenu.displayName = 'PortalMoreMenu';
+
+export default PortalMoreMenu;
diff --git a/src/features/Portal/components/PortalMoreMenu/shareUrl.test.ts b/src/features/Portal/components/PortalMoreMenu/shareUrl.test.ts
new file mode 100644
index 00000000000..1193cbd9d77
--- /dev/null
+++ b/src/features/Portal/components/PortalMoreMenu/shareUrl.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildPortalShareUrl } from './shareUrl';
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => null,
+}));
+
+describe('buildPortalShareUrl', () => {
+ it('joins the app origin and the entity route', () => {
+ expect(buildPortalShareUrl('https://app.lobehub.com', '/agent/agt_1', null)).toBe(
+ 'https://app.lobehub.com/agent/agt_1',
+ );
+ });
+
+ it('carries the active workspace prefix', () => {
+ expect(buildPortalShareUrl('https://app.lobehub.com', '/agent/agt_1/tpc_1', 'acme')).toBe(
+ 'https://app.lobehub.com/acme/agent/agt_1/tpc_1',
+ );
+ });
+
+ it('keeps the query string of the route', () => {
+ expect(
+ buildPortalShareUrl('https://app.lobehub.com', '/agent/a/t?portalThread=thd_1', 'acme'),
+ ).toBe('https://app.lobehub.com/acme/agent/a/t?portalThread=thd_1');
+ });
+
+ it('hides the link when the origin or the route is unknown', () => {
+ // A relative link cannot be pasted anywhere useful — no link beats a broken one.
+ expect(buildPortalShareUrl('', '/agent/agt_1', null)).toBeUndefined();
+ expect(buildPortalShareUrl(undefined, '/agent/agt_1', null)).toBeUndefined();
+ expect(buildPortalShareUrl('https://app.lobehub.com', undefined, null)).toBeUndefined();
+ });
+});
diff --git a/src/features/Portal/components/PortalMoreMenu/shareUrl.ts b/src/features/Portal/components/PortalMoreMenu/shareUrl.ts
new file mode 100644
index 00000000000..8d9606ee379
--- /dev/null
+++ b/src/features/Portal/components/PortalMoreMenu/shareUrl.ts
@@ -0,0 +1,27 @@
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+
+/**
+ * Absolute link for the menu's copy-link capability. Not `window.location`:
+ * on desktop that is the `app://renderer` shell — the link is the app origin
+ * plus the entity route, carrying the active workspace prefix so it resolves
+ * in the same workspace. `undefined` (capability hidden) when either the
+ * origin or the route is unknown, because a relative link cannot be shared.
+ */
+export const buildPortalShareUrl = (
+ appOrigin: string | null | undefined,
+ path: string | null | undefined,
+ workspaceSlug: string | null | undefined,
+): string | undefined => {
+ if (!appOrigin || !path) return;
+
+ return `${appOrigin}${buildWorkspaceAwarePath(path, workspaceSlug)}`;
+};
+
+export const usePortalShareUrl = (path: string | null | undefined): string | undefined => {
+ const appOrigin = useAppOrigin();
+ const workspaceSlug = useActiveWorkspaceSlug();
+
+ return buildPortalShareUrl(appOrigin, path, workspaceSlug);
+};
diff --git a/src/features/Portal/components/PortalMoreMenu/types.ts b/src/features/Portal/components/PortalMoreMenu/types.ts
new file mode 100644
index 00000000000..35ffc8fc1d7
--- /dev/null
+++ b/src/features/Portal/components/PortalMoreMenu/types.ts
@@ -0,0 +1,34 @@
+import { type DropdownItem } from '@lobehub/ui/base-ui';
+
+/**
+ * What a portal can do with the entity it shows. Every field is optional: a
+ * capability the portal does not declare is simply absent from the menu —
+ * never rendered disabled.
+ */
+export interface PortalMoreMenuConfig {
+ /** Copy the entity id verbatim. */
+ copyId?: string;
+ /** Absolute shareable URL of the entity; the menu copies it and confirms. */
+ copyLink?: string;
+ /**
+ * Copy the entity's file path — for entities addressed by a path instead of
+ * an id (local files).
+ */
+ copyPath?: string;
+ /**
+ * Delete the entity. The portal owns the confirmation dialog and what
+ * happens to the panel afterwards.
+ */
+ delete?: () => void;
+ /** Portal-specific actions, rendered as their own group before delete. */
+ extraItems?: DropdownItem[];
+ /** Leave the panel for the entity's full page. */
+ openInPage?: () => void;
+ /** Refetch the entity from the server. */
+ refresh?: () => unknown;
+ /** Start renaming the entity (inline edit or a rename modal). */
+ rename?: () => void;
+}
+
+/** Declared on `PortalImpl.useMoreMenu`; returning `undefined` hides the menu. */
+export type UsePortalMoreMenu = () => PortalMoreMenuConfig | undefined;
diff --git a/src/features/Portal/router.tsx b/src/features/Portal/router.tsx
index 41a8cde689b..dd5c96084d0 100644
--- a/src/features/Portal/router.tsx
+++ b/src/features/Portal/router.tsx
@@ -1,6 +1,6 @@
'use client';
-import React, { Fragment, memo } from 'react';
+import React, { Fragment, memo, useMemo } from 'react';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -11,6 +11,7 @@ import { AcceptanceCheck } from './AcceptanceCheck';
import { AgentDetail } from './AgentDetail';
import { Artifacts } from './Artifacts';
import Header from './components/Header';
+import { PortalMoreMenuProvider } from './components/PortalMoreMenu/context';
import { Document } from './Document';
import { FilePreview } from './FilePreview';
import { Goal } from './Goal';
@@ -94,10 +95,17 @@ export const PortalContent = memo<PortalContentProps>(
<Header title={<Title />} onClose={onClose} />
);
const bodyContent = <Body />;
+ const moreMenuSource = useMemo(
+ () =>
+ ViewImpl?.useMoreMenu
+ ? { key: viewType ?? 'home', useMoreMenu: ViewImpl.useMoreMenu }
+ : null,
+ [ViewImpl, viewType],
+ );
return (
<Wrapper>
- {headerContent}
+ <PortalMoreMenuProvider value={moreMenuSource}>{headerContent}</PortalMoreMenuProvider>
{renderBody ? renderBody(bodyContent) : bodyContent}
</Wrapper>
);
diff --git a/src/features/Portal/type.ts b/src/features/Portal/type.ts
index 72ef99c4928..c1a22508b7b 100644
--- a/src/features/Portal/type.ts
+++ b/src/features/Portal/type.ts
@@ -1,8 +1,15 @@
import { type FC, type PropsWithChildren } from 'react';
+import { type UsePortalMoreMenu } from './components/PortalMoreMenu/types';
+
export interface PortalImpl {
Body: FC;
Header?: FC<{ onClose?: () => void }>;
Title: FC;
+ /**
+ * Capabilities for the shared `…` menu after the title. Called inside the
+ * view's Wrapper; unsupported capabilities are left out and never shown.
+ */
+ useMoreMenu?: UsePortalMoreMenu;
Wrapper?: FC<PropsWithChildren>;
}
diff --git a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
index df15007b167..d54e7485e57 100644
--- a/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
+++ b/src/features/Workspace/__tests__/workspaceAwarePath.test.ts
@@ -37,6 +37,14 @@ describe('buildWorkspaceAwarePath', () => {
);
});
+ // Regression: `/goal/:goalId` is mirrored under `/:workspaceSlug`, but the
+ // prefix allowlist missed it — a copied workspace goal link (a goal with no
+ // agent, e.g. a project goal) opened in the personal scope.
+ it('prefixes top-level goal paths', () => {
+ expect(buildWorkspaceAwarePath('/goal/goal_1', 'acme')).toBe('/acme/goal/goal_1');
+ expect(buildWorkspaceAwarePath('/goal', 'acme')).toBe('/acme/goal');
+ });
+
it('bypasses the prefix when `escape` is true', () => {
expect(buildWorkspaceAwarePath('/settings/memory', 'acme', { escape: true })).toBe(
'/settings/memory',
diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.ts
index 116c1521667..42209929f3c 100644
--- a/src/features/Workspace/workspaceAwarePath.ts
+++ b/src/features/Workspace/workspaceAwarePath.ts
@@ -80,6 +80,8 @@ const WORKSPACE_MIRRORED_FIRST_SEGMENTS = new Set([
'agents',
'community',
'eval',
+ // Top-level goal detail lives beside task/tasks in the shared main area.
+ 'goal',
'group',
'image',
'memory',