🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(task): open cross-workspace task links in the side panel (#22473)
Lobehub Coderb9d4eb4f3bc8
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 00b43b98b02..e50ebb5cc1d 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2496,6 +2496,8 @@"taskDetail.find.position": "{{current}}/{{total}}","taskDetail.find.prev": "Previous match","taskDetail.followUpFailed": "Couldn’t send the follow-up. Your message is kept — try again.",+ "taskDetail.foreignWorkspace.notice": "This task belongs to {{workspace}}. It is shown read-only here.",+ "taskDetail.foreignWorkspace.open": "Open in {{workspace}}","taskDetail.goalTimeline.hover.cost": "Cost","taskDetail.goalTimeline.hover.duration": "Duration","taskDetail.goalTimeline.hover.status": "Status",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 7167f5fb7b3..094a5ef6721 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2496,6 +2496,8 @@"taskDetail.find.position": "{{current}}/{{total}}","taskDetail.find.prev": "上一个","taskDetail.followUpFailed": "追问未发送成功,内容已保留,请重试。",+ "taskDetail.foreignWorkspace.notice": "该任务属于 {{workspace}},此处仅供查看。",+ "taskDetail.foreignWorkspace.open": "在 {{workspace}} 中打开","taskDetail.goalTimeline.hover.cost": "成本","taskDetail.goalTimeline.hover.duration": "时长","taskDetail.goalTimeline.hover.status": "状态",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex c73901068bd..ae53432aaa2 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2183,6 +2183,9 @@ export default {'The task moves to the trash with its runs and can be restored within 30 days.','taskDetail.deleteConfirm.ok': 'Delete','taskDetail.deleteConfirm.title': 'Delete this task?',+ 'taskDetail.foreignWorkspace.notice':+ 'This task belongs to {{workspace}}. It is shown read-only here.',+ 'taskDetail.foreignWorkspace.open': 'Open in {{workspace}}','taskDetail.instruction': 'Instruction','taskDetail.modelConfig': 'Model Override','taskDetail.saveModelConfig': 'Save',diff --git a/src/features/EntityLink/Render/InternalEntityLink.tsx b/src/features/EntityLink/Render/InternalEntityLink.tsxindex eeda48fbe66..2c59d168f17 100644--- a/src/features/EntityLink/Render/InternalEntityLink.tsx+++ b/src/features/EntityLink/Render/InternalEntityLink.tsx@@ -17,6 +17,7 @@ import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';import { shouldHardNavigateToWorkbench } from '@/libs/next/workbenchNavigation';@@ -111,6 +112,7 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,const activeAgentId = useAgentStore((s) => s.activeAgentId);const portalAvailable = useEntityLinkPortal(reference.type);const dismissHost = useEntityLinkHostDismiss();+ const workspaces = useWorkspaces();const [openAcceptance,openAgentDetail,@@ -192,6 +194,17 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,return;}+ // A task in another workspace still opens beside the conversation: the+ // panel reads it through that workspace's scope (read-only) instead of+ // switching the whole page into it.+ if (reference.type === 'task' && reference.workspaceSlug && portalAvailable) {+ const workspace = workspaces.find((item) => item.slug === reference.workspaceSlug);+ if (workspace) {+ openTaskDetail(reference.taskId, { id: workspace.id, slug: workspace.slug });+ return;+ }+ }+// Portal-backed entities (verify / acceptance) open in-context regardless// of workspace scope — their reads are id-addressed and scope-independent.if (@@ -294,6 +307,7 @@ export const InternalEntityLink = memo<InternalEntityLinkProps>(({ href, label,reference,linkedAgentId,shouldResolveAgentDocument,+ workspaces,],);diff --git a/src/features/EntityLink/Render/index.test.tsx b/src/features/EntityLink/Render/index.test.tsxindex f34ed09abe2..89942896f41 100644--- a/src/features/EntityLink/Render/index.test.tsx+++ b/src/features/EntityLink/Render/index.test.tsx@@ -761,8 +761,8 @@ describe('Link Render — open an external link in the side browser', () => {expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/tasks', { escape: true });});- it('navigates workspace-qualified entities before opening a scoped portal', () => {- const { getByRole, queryByRole } = renderLink({+ it('opens a task from another workspace beside the chat, scoped to that workspace', () => {+ const { getByRole } = renderLink({linkHref: '/lobe-team/task/T-198',linkKind: 'generic',linkLabel: 'Workspace task',@@ -770,9 +770,21 @@ describe('Link Render — open an external link in the side browser', () => {fireEvent.click(getByRole('link', { name: 'Workspace task' }));- expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/task/T-198', { escape: true });- expect(mockOpenTaskDetail).not.toHaveBeenCalled();- expect(queryByRole('dialog')).not.toBeInTheDocument();+ expect(mockOpenTaskDetail).toHaveBeenCalledWith('T-198', { id: 'ws-1', slug: 'lobe-team' });+ expect(mockNavigate).not.toHaveBeenCalled();+ });++ it('still navigates other workspace-qualified entities into their workspace', () => {+ const { getByRole } = renderLink({+ linkHref: '/lobe-team/agent/agt_9',+ linkKind: 'generic',+ linkLabel: 'Workspace agent',+ });++ fireEvent.click(getByRole('link', { name: 'Workspace agent' }));++ expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/agent/agt_9', { escape: true });+ expect(mockOpenAgentDetail).not.toHaveBeenCalled();});it('preserves a different agent context for agent-scoped document links', () => {@@ -847,6 +859,18 @@ describe('Link Render — host portal scope', () => {expect(mockOpenTaskDetail).not.toHaveBeenCalled();});+ it('navigates a task from another workspace when the host has no panel', () => {+ const { getByRole } = renderLinkInHost(+ { linkHref: '/lobe-team/task/T-198', linkKind: 'generic', linkLabel: 'Workspace task' },+ false,+ );++ fireEvent.click(getByRole('link', { name: 'Workspace task' }));++ expect(mockNavigate).toHaveBeenCalledWith('/lobe-team/task/T-198', { escape: true });+ expect(mockOpenTaskDetail).not.toHaveBeenCalled();+ });+it('still opens the kinds the host can present', () => {const { getByRole } = renderLinkInHost({ linkHref: '/acceptance/acceptance-1', linkKind: 'generic', linkLabel: 'Acceptance' },diff --git a/src/features/Portal/TaskDetail/Body.tsx b/src/features/Portal/TaskDetail/Body.tsxindex 43187a95838..95b8a94499f 100644--- a/src/features/Portal/TaskDetail/Body.tsx+++ b/src/features/Portal/TaskDetail/Body.tsx@@ -13,7 +13,9 @@ import {import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';-const Body = memo(() => {+import ForeignTaskDetail from './ForeignTaskDetail';++const ActiveScopeBody = memo(() => {const { t } = useTranslation('chat');const taskId = useChatStore(chatPortalSelectors.taskDetailId);// Same data wiring as the full /task/[tid] page — owns activeTaskId + polling@@ -53,4 +55,23 @@ const Body = memo(() => {);});+ActiveScopeBody.displayName = 'ActiveScopeTaskDetailBody';++const Body = memo(() => {+ const isForeign = useChatStore((s) => !!chatPortalSelectors.taskDetailWorkspace(s));++ if (!isForeign) return <ActiveScopeBody />;++ return (+ <Flexbox+ flex={1}+ height={'100%'}+ paddingInline={16}+ style={{ minHeight: 0, overflowY: 'auto' }}+ >+ <ForeignTaskDetail />+ </Flexbox>+ );+});+export default Body;diff --git a/src/features/Portal/TaskDetail/ForeignTaskDetail.tsx b/src/features/Portal/TaskDetail/ForeignTaskDetail.tsxnew file mode 100644index 00000000000..7fee1b5c613--- /dev/null+++ b/src/features/Portal/TaskDetail/ForeignTaskDetail.tsx@@ -0,0 +1,91 @@+import type { TaskStatus } from '@lobechat/types';+import { Alert, Button, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';+import NotFound from '@/components/404';+import AsyncError from '@/components/AsyncError';+import { TaskDetailSkeleton } from '@/features/AgentTasks';+import { STATUS_META } from '@/features/AgentTasks/features/taskStatusMeta';+import { normalizeAsyncError } from '@/libs/swr/normalizeError';++import { getTaskDetailPagePath } from './url';+import { FOREIGN_TASK_NOT_FOUND, useForeignTaskDetail } from './useForeignTaskDetail';+import { useOpenForeignTaskPage } from './useOpenForeignTaskPage';++/**+ * A task from another workspace, shown beside the conversation without moving+ * the page into that workspace. Every editor of the full detail reads and writes+ * the ACTIVE scope's task store, so this view stays read-only and hands editing+ * to the task's own page.+ */+const ForeignTaskDetail = memo(() => {+ const { t } = useTranslation('chat');+ const openTaskPage = useOpenForeignTaskPage();+ const workspaces = useWorkspaces();+ const { data: task, error, isLoading, mutate, taskId, workspace } = useForeignTaskDetail();++ if (!taskId || !workspace) return null;++ const workspaceName = workspaces.find((item) => item.id === workspace.id)?.name || workspace.slug;++ if (error && !task) {+ if (normalizeAsyncError(error).code === FOREIGN_TASK_NOT_FOUND)+ return (+ <NotFound desc={t('taskDetail.notFound.desc')} title={t('taskDetail.notFound.title')} />+ );++ return <AsyncError error={error} variant={'page'} onRetry={() => mutate()} />;+ }++ if (isLoading || !task) return <TaskDetailSkeleton chrome={'body'} />;++ const status = STATUS_META[task.status as TaskStatus] ?? STATUS_META.backlog;+ const pagePath = getTaskDetailPagePath({+ agentId: task.agentId ?? undefined,+ identifier: task.identifier,+ title: task.name,+ workspaceSlug: workspace.slug,+ });+ const openInWorkspace = () => pagePath && openTaskPage(pagePath);++ return (+ <Flexbox gap={20} paddingBlock={16} style={{ paddingBottom: 120 }}>+ <Alert+ showIcon+ title={t('taskDetail.foreignWorkspace.notice', { workspace: workspaceName })}+ type={'info'}+ action={+ <Button size={'small'} onClick={openInWorkspace}>+ {t('taskDetail.foreignWorkspace.open', { workspace: workspaceName })}+ </Button>+ }+ />+ <Flexbox gap={8}>+ <Text fontSize={20} weight={600}>+ {task.name || task.identifier}+ </Text>+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon color={status.color} icon={status.icon} size={14} />+ <Text fontSize={13} type={'secondary'}>+ {t(`taskDetail.${status.labelKey}`, { defaultValue: status.label })}+ </Text>+ </Flexbox>+ </Flexbox>+ {task.description && <Text type={'secondary'}>{task.description}</Text>}+ {task.instruction && (+ <Flexbox gap={8}>+ <Text weight={500}>{t('taskDetail.instruction')}</Text>+ <Markdown style={{ overflow: 'unset' }} variant={'chat'}>+ {task.instruction}+ </Markdown>+ </Flexbox>+ )}+ </Flexbox>+ );+});++ForeignTaskDetail.displayName = 'ForeignTaskDetail';++export default ForeignTaskDetail;diff --git a/src/features/Portal/TaskDetail/Header.tsx b/src/features/Portal/TaskDetail/Header.tsxindex c31a940413b..6213e5cb7e9 100644--- a/src/features/Portal/TaskDetail/Header.tsx+++ b/src/features/Portal/TaskDetail/Header.tsx@@ -14,30 +14,28 @@ import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';import PortalHeader from '../components/Header';import Title from './Title';import { getTaskDetailPageUrl } from './url';+import { useForeignTaskDetail } from './useForeignTaskDetail';const TaskDetailHeader = memo<{ onClose?: () => void }>(({ onClose }) => {const { t } = useTranslation('verify');const appOrigin = useAppOrigin();const activeWorkspaceSlug = useActiveWorkspaceSlug();const taskId = useChatStore(chatPortalSelectors.taskDetailId);- const agentId = useTaskStore((state) =>- taskId- ? (state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId]?.agentId ?? undefined)- : undefined,- );- const taskTitle = useTaskStore((state) =>- taskId- ? (state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId]?.name ?? undefined)+ const foreignWorkspace = useChatStore(chatPortalSelectors.taskDetailWorkspace);+ const activeDetail = useTaskStore((state) =>+ taskId && !foreignWorkspace+ ? state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId]: undefined,);+ const { data: foreignDetail } = useForeignTaskDetail();+ const detail = foreignWorkspace ? foreignDetail : activeDetail;const pageUrl = getTaskDetailPageUrl({- agentId,+ agentId: detail?.agentId ?? undefined,appOrigin,- identifier: useTaskStore((state) =>- taskId ? state.taskDetailMap[state.taskRefIndex?.[taskId] ?? taskId]?.identifier : undefined,- ),- title: taskTitle,- workspaceSlug: activeWorkspaceSlug,+ identifier: detail?.identifier,+ title: detail?.name,+ // A task from another workspace links to its own workspace's page.+ workspaceSlug: foreignWorkspace ? foreignWorkspace.slug : activeWorkspaceSlug,});return (diff --git a/src/features/Portal/TaskDetail/Title.tsx b/src/features/Portal/TaskDetail/Title.tsxindex a6cfa86440b..de6577d3321 100644--- a/src/features/Portal/TaskDetail/Title.tsx+++ b/src/features/Portal/TaskDetail/Title.tsx@@ -6,6 +6,8 @@ import { chatPortalSelectors } from '@/store/chat/selectors';import { useTaskStore } from '@/store/task';import { oneLineEllipsis } from '@/styles';+import { useForeignTaskDetail } from './useForeignTaskDetail';+const styles = createStaticStyles(({ css, cssVar }) => ({identifier: css`flex-shrink: 0;@@ -24,9 +26,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({const Title = memo(() => {const taskId = useChatStore(chatPortalSelectors.taskDetailId);- const detail = useTaskStore((s) =>- taskId ? s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId] : undefined,+ const isForeign = useChatStore((s) => !!chatPortalSelectors.taskDetailWorkspace(s));+ const activeDetail = useTaskStore((s) =>+ taskId && !isForeign ? s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId] : undefined,);+ const { data: foreignDetail } = useForeignTaskDetail();+ const detail = isForeign ? foreignDetail : activeDetail;const identifier = detail?.identifier ?? taskId;const name = detail?.name;diff --git a/src/features/Portal/TaskDetail/url.test.ts b/src/features/Portal/TaskDetail/url.test.tsindex 127de793ef9..5de3189aebc 100644--- a/src/features/Portal/TaskDetail/url.test.ts+++ b/src/features/Portal/TaskDetail/url.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { getTaskDetailPageUrl } from './url';+import { getTaskDetailPagePath, getTaskDetailPageUrl } from './url';describe('getTaskDetailPageUrl', () => {it('uses a public short link while the portal keeps a stable task id', () => {@@ -47,3 +47,20 @@ describe('getTaskDetailPageUrl', () => {expect(getTaskDetailPageUrl({ taskId: 'T-245' })).toBeUndefined();});});++describe('getTaskDetailPagePath', () => {+ it('scopes a task from another workspace to that workspace', () => {+ expect(+ getTaskDetailPagePath({+ agentId: 'agt_1',+ identifier: 'T-198',+ title: 'Ship it',+ workspaceSlug: 'lobe-team',+ }),+ ).toBe('/lobe-team/agent/agt_1/task/T-198/ship-it');+ });++ it('has no path without a task reference', () => {+ expect(getTaskDetailPagePath({ workspaceSlug: 'lobe-team' })).toBeUndefined();+ });+});diff --git a/src/features/Portal/TaskDetail/url.ts b/src/features/Portal/TaskDetail/url.tsindex 0c3ef693a53..3b343042a43 100644--- a/src/features/Portal/TaskDetail/url.ts+++ b/src/features/Portal/TaskDetail/url.ts@@ -11,17 +11,26 @@ interface TaskDetailPageUrlOptions {workspaceSlug?: string | null;}-export const getTaskDetailPageUrl = ({+/** App-relative path of a task's own page, scoped to the given workspace. */+export const getTaskDetailPagePath = ({agentId,- appOrigin,taskId,identifier,title,workspaceSlug,-}: TaskDetailPageUrlOptions): string | undefined => {+}: Omit<TaskDetailPageUrlOptions, 'appOrigin'>): string | undefined => {const taskRef = identifier ?? taskId;- if (!appOrigin || !taskRef) return;+ if (!taskRef) return;++ return buildWorkspaceAwarePath(taskDetailPath(taskRef, agentId, title), workspaceSlug);+};++export const getTaskDetailPageUrl = ({+ appOrigin,+ ...options+}: TaskDetailPageUrlOptions): string | undefined => {+ if (!appOrigin) return;- const path = buildWorkspaceAwarePath(taskDetailPath(taskRef, agentId, title), workspaceSlug);- return `${appOrigin}${path}`;+ const path = getTaskDetailPagePath(options);+ return path && `${appOrigin}${path}`;};diff --git a/src/features/Portal/TaskDetail/useForeignTaskDetail.test.ts b/src/features/Portal/TaskDetail/useForeignTaskDetail.test.tsnew file mode 100644index 00000000000..955730a1de5--- /dev/null+++ b/src/features/Portal/TaskDetail/useForeignTaskDetail.test.ts@@ -0,0 +1,84 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { SWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { FOREIGN_TASK_NOT_FOUND, useForeignTaskDetail } from './useForeignTaskDetail';++const mocks = vi.hoisted(() => ({+ createWorkspaceLambdaClient: vi.fn(),+ detailQuery: vi.fn(),+ lambdaDetailQuery: vi.fn(),+ portalStack: [] as unknown[],+}));++vi.mock('@/libs/trpc/client', () => ({+ createWorkspaceLambdaClient: (workspaceId: string | null) => {+ mocks.createWorkspaceLambdaClient(workspaceId);+ return { task: { detail: { query: mocks.detailQuery } } };+ },+ lambdaClient: { task: { detail: { query: mocks.lambdaDetailQuery } } },+ withLlmRelay: vi.fn(),+}));+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => 'ws-active',+}));+vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: unknown) => unknown) => selector({ portalStack: mocks.portalStack }),+}));++const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);++describe('useForeignTaskDetail', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.portalStack = [+ { taskId: 'T-198', type: 'taskDetail', workspace: { id: 'ws-1', slug: 'lobe-team' } },+ ];+ });++ it('reads the task through its own workspace, not the active scope', async () => {+ mocks.detailQuery.mockResolvedValue({+ data: { id: 'task_1', identifier: 'T-198', status: 'completed' },+ });+ const { result } = renderHook(() => useForeignTaskDetail(), { wrapper });++ await waitFor(() => expect(result.current.data?.identifier).toBe('T-198'));+ expect(mocks.createWorkspaceLambdaClient).toHaveBeenCalledWith('ws-1');+ expect(mocks.detailQuery).toHaveBeenCalledWith({ id: 'T-198' });+ expect(mocks.lambdaDetailQuery).not.toHaveBeenCalled();+ });++ it.each([+ [+ 'a tRPC NOT_FOUND',+ () => mocks.detailQuery.mockRejectedValue({ data: { code: 'NOT_FOUND' } }),+ ],+ ['an empty result', () => mocks.detailQuery.mockResolvedValue({ data: null })],+ ])('maps %s to a resolved not-found', async (_, arrange) => {+ arrange();+ const { result } = renderHook(() => useForeignTaskDetail(), { wrapper });++ await waitFor(() => expect(result.current.error).toBeDefined());+ expect((result.current.error as { code?: string }).code).toBe(FOREIGN_TASK_NOT_FOUND);+ });++ it('keeps other failures retryable', async () => {+ const failure = Object.assign(new Error('boom'), { data: { code: 'INTERNAL_SERVER_ERROR' } });+ mocks.detailQuery.mockRejectedValue(failure);+ const { result } = renderHook(() => useForeignTaskDetail(), { wrapper });++ await waitFor(() => expect(result.current.error).toBe(failure));+ });++ it('reads nothing for an active-scope task', () => {+ mocks.portalStack = [{ taskId: 'T-7', type: 'taskDetail' }];+ renderHook(() => useForeignTaskDetail(), { wrapper });++ expect(mocks.createWorkspaceLambdaClient).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Portal/TaskDetail/useForeignTaskDetail.ts b/src/features/Portal/TaskDetail/useForeignTaskDetail.tsnew file mode 100644index 00000000000..d7f8a5f8c5b--- /dev/null+++ b/src/features/Portal/TaskDetail/useForeignTaskDetail.ts@@ -0,0 +1,52 @@+import type { TaskDetailData } from '@lobechat/types';++import { useClientDataSWR } from '@/libs/swr';+import { taskService } from '@/services/task';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import {+ hasInFlightActivity,+ TASK_DETAIL_POLL_INTERVAL,+} from '@/store/task/slices/detail/inFlight';+import { isTrpcErrorCode } from '@/utils/trpcError';++export const FOREIGN_TASK_NOT_FOUND = 'TASK_NOT_FOUND';++export const foreignTaskDetailKey = (workspaceId: string, taskId: string) =>+ ['portal-foreign-task-detail', workspaceId, taskId] as const;++const taskNotFound = () =>+ Object.assign(new Error('Task not found'), { code: FOREIGN_TASK_NOT_FOUND });++const fetchForeignTaskDetail = async (+ taskId: string,+ workspaceId: string,+): Promise<TaskDetailData> => {+ const result = await taskService.getDetailInWorkspace(taskId, workspaceId).catch((error) => {+ throw isTrpcErrorCode(error, 'NOT_FOUND') ? taskNotFound() : error;+ });+ if (!result.data?.id) throw taskNotFound();+ return result.data;+};++/**+ * The task shown in the portal when it lives in another workspace. Header,+ * title and body share one SWR key, so they read a single request.+ */+export const useForeignTaskDetail = () => {+ const taskId = useChatStore(chatPortalSelectors.taskDetailId);+ const workspace = useChatStore(chatPortalSelectors.taskDetailWorkspace);++ const swr = useClientDataSWR(+ taskId && workspace ? foreignTaskDetailKey(workspace.id, taskId) : null,+ () => fetchForeignTaskDetail(taskId!, workspace!.id),+ {+ // Same rule as the active-scope detail: follow a run until it settles.+ refreshInterval: (data?: TaskDetailData) =>+ hasInFlightActivity(data) ? TASK_DETAIL_POLL_INTERVAL : 0,+ revalidateOnFocus: false,+ },+ );++ return { ...swr, taskId, workspace };+};diff --git a/src/features/Portal/TaskDetail/useMoreMenu.test.ts b/src/features/Portal/TaskDetail/useMoreMenu.test.tsindex 6fc96a770f1..a2e0e2e574c 100644--- a/src/features/Portal/TaskDetail/useMoreMenu.test.ts+++ b/src/features/Portal/TaskDetail/useMoreMenu.test.ts@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({clearPortalStack: vi.fn(),confirmModal: vi.fn(),deleteTask: vi.fn(),+ foreign: {} as Record<string, unknown>,openRenameModal: vi.fn(),refreshTaskDetail: vi.fn(),updateTask: vi.fn(),@@ -15,6 +16,8 @@ const mocks = vi.hoisted(() => ({vi.mock('@lobehub/ui', () => ({ confirmModal: mocks.confirmModal }));vi.mock('@/components/RenameModal', () => ({ openRenameModal: mocks.openRenameModal }));+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://app.lobehub.com' }));+vi.mock('./useForeignTaskDetail', () => ({ useForeignTaskDetail: () => mocks.foreign }));vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: mocks.allowed }) }));vi.mock('@/features/AgentTasks/AgentTaskDetail/useTaskCopyActions', () => ({useTaskCopyActions: () => ({@@ -40,6 +43,7 @@ describe('useTaskDetailMoreMenu', () => {beforeEach(() => {vi.clearAllMocks();mocks.allowed = true;+ mocks.foreign = {};});it('declares rename, copy link, copy id, refresh and delete', () => {@@ -87,4 +91,25 @@ describe('useTaskDetailMoreMenu', () => {expect(result.current?.rename).toBeUndefined();expect(result.current?.delete).toBeUndefined();});++ it('offers only copy and refresh for a task from another workspace', () => {+ const mutate = vi.fn();+ mocks.foreign = {+ data: { agentId: null, identifier: 'T-198', name: 'Ship it' },+ mutate,+ taskId: 'T-198',+ workspace: { id: 'ws-1', slug: 'lobe-team' },+ };+ const { result } = renderHook(() => useTaskDetailMoreMenu());++ // Rename/delete write through the active scope, where T-198 names another task.+ expect(Object.keys(result.current!).sort()).toEqual(['copyId', 'copyLink', 'refresh']);+ expect(result.current).toMatchObject({+ copyId: 'T-198',+ copyLink: 'https://app.lobehub.com/lobe-team/task/T-198/ship-it',+ });+ result.current!.refresh!();+ expect(mutate).toHaveBeenCalledOnce();+ expect(mocks.refreshTaskDetail).not.toHaveBeenCalled();+ });});diff --git a/src/features/Portal/TaskDetail/useMoreMenu.ts b/src/features/Portal/TaskDetail/useMoreMenu.tsindex 59224f8e1c2..331abd0cef2 100644--- a/src/features/Portal/TaskDetail/useMoreMenu.ts+++ b/src/features/Portal/TaskDetail/useMoreMenu.ts@@ -4,10 +4,14 @@ 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 { useAppOrigin } from '@/hooks/useAppOrigin';import { usePermission } from '@/hooks/usePermission';import { useChatStore } from '@/store/chat';import { useTaskStore } from '@/store/task';+import { getTaskDetailPageUrl } from './url';+import { useForeignTaskDetail } from './useForeignTaskDetail';+export const useTaskDetailMoreMenu = (): PortalMoreMenuConfig | undefined => {const { t } = useTranslation('chat');// The body marks this task active while the panel is open, so the copied@@ -24,6 +28,27 @@ export const useTaskDetailMoreMenu = (): PortalMoreMenuConfig | undefined => {const clearPortalStack = useChatStore((s) => s.clearPortalStack);// Same gate as the task page's header menu.const { allowed: canEdit } = usePermission('create_content');+ const appOrigin = useAppOrigin();+ const foreign = useForeignTaskDetail();++ // A task from another workspace is shown read-only: the edit actions here+ // write through the active scope, where its identifier can name another task.+ if (foreign.workspace) {+ if (!foreign.taskId) return;+ const detail = foreign.data;++ return {+ copyId: detail?.identifier ?? foreign.taskId,+ copyLink: getTaskDetailPageUrl({+ agentId: detail?.agentId ?? undefined,+ appOrigin,+ identifier: detail?.identifier,+ title: detail?.name,+ workspaceSlug: foreign.workspace.slug,+ }),+ refresh: () => foreign.mutate(),+ };+ }if (!taskId) return;diff --git a/src/features/Portal/TaskDetail/useOpenForeignTaskPage.test.ts b/src/features/Portal/TaskDetail/useOpenForeignTaskPage.test.tsnew file mode 100644index 00000000000..5c510ed048a--- /dev/null+++ b/src/features/Portal/TaskDetail/useOpenForeignTaskPage.test.ts@@ -0,0 +1,29 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useOpenForeignTaskPage } from './useOpenForeignTaskPage';++const calls: string[] = [];+const navigate = vi.fn(() => calls.push('navigate'));+const clearPortalStack = vi.fn(() => calls.push('clearPortalStack'));++vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => navigate,+}));+vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: unknown) => unknown) => selector({ clearPortalStack }),+}));++describe('useOpenForeignTaskPage', () => {+ it('closes the read-only panel before entering the task page in its workspace', () => {+ const { result } = renderHook(() => useOpenForeignTaskPage());++ result.current('/lobe-team/task/T-198/ship-it');++ expect(navigate).toHaveBeenCalledWith('/lobe-team/task/T-198/ship-it', { escape: true });+ expect(calls).toEqual(['clearPortalStack', 'navigate']);+ });+});diff --git a/src/features/Portal/TaskDetail/useOpenForeignTaskPage.ts b/src/features/Portal/TaskDetail/useOpenForeignTaskPage.tsnew file mode 100644index 00000000000..ca124cf1553--- /dev/null+++ b/src/features/Portal/TaskDetail/useOpenForeignTaskPage.ts@@ -0,0 +1,22 @@+import { useCallback } from 'react';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useChatStore } from '@/store/chat';++/**+ * Leave the read-only panel for the task's own page in its workspace. The panel+ * closes first: left open, the destination page would show the same task twice,+ * once editable and once behind the "read-only here" notice.+ */+export const useOpenForeignTaskPage = () => {+ const navigate = useWorkspaceAwareNavigate();+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);++ return useCallback(+ (pagePath: string) => {+ clearPortalStack();+ navigate(pagePath, { escape: true });+ },+ [clearPortalStack, navigate],+ );+};diff --git a/src/services/task.ts b/src/services/task.tsindex 92c353de0bf..03272e12306 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -8,7 +8,7 @@ import type {TaskStatus,} from '@lobechat/types';-import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';+import { createWorkspaceLambdaClient, lambdaClient, withLlmRelay } from '@/libs/trpc/client';import { buildLlmExecutorDeclaration, oneShotRelay } from '@/services/llmRelay';import { useUserStore } from '@/store/user';import { systemAgentSelectors } from '@/store/user/selectors';@@ -23,6 +23,14 @@ class TaskService {getDetail = async (id: string) => lambdaClient.task.detail.query({ id });+ /**+ * Read a task from a workspace other than the active one. Task identifiers+ * are only unique within a workspace, so the read is pinned to the owning+ * workspace instead of resolving against the active scope.+ */+ getDetailInWorkspace = async (id: string, workspaceId: string) =>+ createWorkspaceLambdaClient(workspaceId).task.detail.query({ id });+list = async (params: {/** Keyset cursor: rows strictly after this `(orderBy timestamp, seq)` position. */after?: { at: Date | string; seq: number };diff --git a/src/store/chat/slices/portal/action.taskDetail.test.ts b/src/store/chat/slices/portal/action.taskDetail.test.tsnew file mode 100644index 00000000000..5270158db1f--- /dev/null+++ b/src/store/chat/slices/portal/action.taskDetail.test.ts@@ -0,0 +1,26 @@+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++describe('portal openTaskDetail', () => {+ it('keeps the owning workspace of a task from another workspace', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.openTaskDetail('T-198', { id: 'ws-1', slug: 'lobe-team' });+ });+ expect(chatPortalSelectors.taskDetailWorkspace(result.current)).toEqual({+ id: 'ws-1',+ slug: 'lobe-team',+ });++ // Replacing it with an active-scope task drops the foreign scope.+ act(() => {+ result.current.openTaskDetail('T-7');+ });+ expect(chatPortalSelectors.taskDetailId(result.current)).toBe('T-7');+ expect(chatPortalSelectors.taskDetailWorkspace(result.current)).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex 73bcf7fcc03..8676a5838c0 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -19,6 +19,7 @@ import {type GoalMetricKind,type OpenLocalFileParams,type PortalFile,+ type PortalTaskWorkspace,type PortalViewData,} from './initialState';import { PortalViewType } from './initialState';@@ -722,8 +723,12 @@ export class ChatPortalActionImpl {this.#get().pushPortalView({ type: PortalViewType.Notebook });};- openTaskDetail = (taskId: string): void => {- this.#get().pushPortalView({ taskId, type: PortalViewType.TaskDetail });+ openTaskDetail = (taskId: string, workspace?: PortalTaskWorkspace): void => {+ this.#get().pushPortalView({+ taskId,+ type: PortalViewType.TaskDetail,+ ...(workspace ? { workspace } : {}),+ });};openTaskResult = (taskId: string): void => {diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex ca5a886e0e2..8ffdd2bd1be 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -89,6 +89,11 @@ export interface OpenLocalFileEntry extends OpenLocalFileParams {export type GoalMetricKind ='budget' | 'duration' | 'findings' | 'lifecycle' | 'liveness' | 'tasks';+export interface PortalTaskWorkspace {+ id: string;+ slug: string;+}+export type PortalViewData =| { type: PortalViewType.Home }| { goalId: string; type: PortalViewType.Goal }@@ -119,7 +124,16 @@ export type PortalViewData =| { startMessageId?: string; threadId?: string; type: PortalViewType.Thread }| { topicId: string; type: PortalViewType.Topic }| { agentId: string; type: PortalViewType.GroupThread }- | { taskId: string; type: PortalViewType.TaskDetail }+ | {+ taskId: string;+ type: PortalViewType.TaskDetail;+ /**+ * Set when the task lives in a workspace other than the active one. The+ * panel then reads it through that workspace's scope, read-only, instead+ * of the active-scope task store.+ */+ workspace?: PortalTaskWorkspace;+ }| { taskId: string; type: PortalViewType.TaskResult }| {focusCommentId?: string;diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex e32d3bc1671..f93f657ded2 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -264,6 +264,9 @@ const taskDetailId = (s: ChatStoreState): string | undefined => {return view?.taskId;};+const taskDetailWorkspace = (s: ChatStoreState) =>+ getStackViewData(s, PortalViewType.TaskDetail)?.workspace;+const taskResultId = (s: ChatStoreState): string | undefined => {const view = getStackViewData(s, PortalViewType.TaskResult);return view?.taskId;@@ -391,6 +394,7 @@ export const chatPortalSelectors = {// Task detail datataskDetailId,+ taskDetailWorkspace,taskResultId,// Topic chat datadiff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 70210a557ab..f01c91c21b7 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -1,4 +1,4 @@-import type { TaskDetailActivityAuthor, TaskDetailData, TaskDetailSubtask } from '@lobechat/types';+import type { TaskDetailActivityAuthor, TaskDetailData } from '@lobechat/types';import {clearTaskReposSelection,readTaskExecutionConfig,@@ -24,6 +24,7 @@ import { isTrpcErrorCode } from '@/utils/trpcError';import type { TaskStore } from '../../store';import { useTaskStore } from '../../store';+import { hasInFlightActivity, TASK_DETAIL_POLL_INTERVAL } from './inFlight';import {appendOptimisticPropertyActivity,buildOptimisticAssignmentActivities,@@ -81,31 +82,6 @@ export interface TaskUpdateOptions {source?: 'editor' | 'external';}-const TASK_DETAIL_POLL_INTERVAL = 10_000;--const hasInFlightSubtask = (subtasks: TaskDetailSubtask[] | undefined): boolean =>- subtasks?.some(- (subtask) =>- Boolean(subtask.runningTopic) ||- subtask.status === 'running' ||- subtask.status === 'pending' ||- hasInFlightSubtask(subtask.children),- ) ?? false;--// Poll while the task itself or any topic activity is still in flight, so the-// UI picks up status transitions (running → completed/failed) without needing-// a manual refresh. Returns false once everything settles so SWR stops polling.-const hasInFlightActivity = (detail: TaskDetailData | undefined): boolean => {- if (!detail) return false;- if (detail.status === 'running' || detail.status === 'pending') return true;- if (hasInFlightSubtask(detail.subtasks)) return true;- return (- detail.activities?.some(- (a) => a.type === 'topic' && (a.status === 'running' || a.status === 'pending'),- ) ?? false- );-};-const hasInstructionSnapshotChanged = (current: TaskDetailData | undefined,next: TaskDetailData | undefined,diff --git a/src/store/task/slices/detail/inFlight.ts b/src/store/task/slices/detail/inFlight.tsnew file mode 100644index 00000000000..c71b97fdf44--- /dev/null+++ b/src/store/task/slices/detail/inFlight.ts@@ -0,0 +1,26 @@+import type { TaskDetailData, TaskDetailSubtask } from '@lobechat/types';++export const TASK_DETAIL_POLL_INTERVAL = 10_000;++const hasInFlightSubtask = (subtasks: TaskDetailSubtask[] | undefined): boolean =>+ subtasks?.some(+ (subtask) =>+ Boolean(subtask.runningTopic) ||+ subtask.status === 'running' ||+ subtask.status === 'pending' ||+ hasInFlightSubtask(subtask.children),+ ) ?? false;++// Poll while the task itself or any topic activity is still in flight, so the+// UI picks up status transitions (running → completed/failed) without needing+// a manual refresh. Returns false once everything settles so SWR stops polling.+export const hasInFlightActivity = (detail: TaskDetailData | undefined): boolean => {+ if (!detail) return false;+ if (detail.status === 'running' || detail.status === 'pending') return true;+ if (hasInFlightSubtask(detail.subtasks)) return true;+ return (+ detail.activities?.some(+ (a) => a.type === 'topic' && (a.status === 'running' || a.status === 'pending'),+ ) ?? false+ );+};