Skip to content

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

🐛 fix(tasks): preserve agent context in task routes (#14926)

AmAzing-c21076eec441
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index dbee11296aa..53c8ea62418 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -306,7 +306,7 @@ export interface TaskDetailData {
identifier: string;
instruction: string;
name?: string | null;
- parent?: { identifier: string; name: string | null } | null;
+ parent?: { agentId?: string | null; identifier: string; name: string | null } | null;
priority?: number | null;
review?: Record<string, any> | null;
schedule?: {
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
index 0074d36fbb3..4c83d8e61f6 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx
@@ -9,12 +9,15 @@ import { useAppOrigin } from '@/hooks/useAppOrigin';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
+import { taskDetailPath } from '../shared/taskDetailPath';
+
const TaskDetailHeaderActions = memo(() => {
const { t } = useTranslation(['chat', 'common']);
const { modal, message } = App.useApp();
const navigate = useNavigate();
const appOrigin = useAppOrigin();
const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
+ const taskAgentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);
const deleteTask = useTaskStore((s) => s.deleteTask);
const triggerDelete = useCallback(() => {
@@ -36,7 +39,7 @@ const TaskDetailHeaderActions = memo(() => {
const menuItems = useMemo<DropdownItem[]>(() => {
if (!taskId) return [];
- const taskUrl = `${appOrigin}/task/${taskId}`;
+ const taskUrl = `${appOrigin}${taskDetailPath(taskId, taskAgentId ?? undefined)}`;
return [
{
@@ -66,7 +69,7 @@ const TaskDetailHeaderActions = memo(() => {
onClick: triggerDelete,
},
];
- }, [taskId, appOrigin, t, message, triggerDelete]);
+ }, [taskId, taskAgentId, appOrigin, t, message, triggerDelete]);
if (!taskId) return null;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
index 310d0433cc6..d9cb5b06326 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
@@ -27,10 +27,11 @@ import TaskSubtasks from './TaskSubtasks';
import TopicChatDrawer from './TopicChatDrawer';
interface TaskDetailPageProps {
+ showTaskAgentPanelToggle?: boolean;
taskId: string;
}
-const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId }) => {
+const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelToggle = true }) => {
const setActiveTaskId = useTaskStore((s) => s.setActiveTaskId);
const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);
const isLoading = useTaskStore(taskDetailSelectors.isTaskDetailLoading);
@@ -58,11 +59,13 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId }) => {
</>
}
right={
- <ToggleRightPanelButton
- hideWhenExpanded
- expand={showTaskAgentPanel}
- onToggle={() => toggleTaskAgentPanel()}
- />
+ showTaskAgentPanelToggle ? (
+ <ToggleRightPanelButton
+ hideWhenExpanded
+ expand={showTaskAgentPanel}
+ onToggle={() => toggleTaskAgentPanel()}
+ />
+ ) : undefined
}
styles={{
left: {
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx
new file mode 100644
index 00000000000..ae11b042102
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx
@@ -0,0 +1,171 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TaskParentBar from './TaskParentBar';
+
+const mocks = vi.hoisted(() => ({
+ getDetail: vi.fn(),
+ navigate: vi.fn(),
+ taskState: {} as any,
+}));
+
+const createState = (parent: any) => ({
+ activeTaskId: 'T-child',
+ taskDetailMap: {
+ 'T-child': {
+ identifier: 'T-child',
+ instruction: 'Child instruction',
+ parent,
+ status: 'running',
+ },
+ },
+});
+
+vi.mock('@lobehub/ui', () => ({
+ Button: ({
+ children,
+ icon,
+ onClick,
+ }: {
+ children: ReactNode;
+ icon?: ReactNode;
+ onClick?: () => void;
+ }) => (
+ <button type="button" onClick={onClick}>
+ {icon}
+ {children}
+ </button>
+ ),
+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => mocks.navigate,
+}));
+
+vi.mock('@/services/task', () => ({
+ taskService: {
+ getDetail: mocks.getDetail,
+ },
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: any) => selector(mocks.taskState),
+}));
+
+vi.mock('../features/TaskStatusIcon', () => ({
+ default: () => <span>status</span>,
+}));
+
+vi.mock('../features/TaskSubtaskProgressTag', () => ({
+ default: ({
+ onSubtaskClick,
+ subtasks,
+ }: {
+ onSubtaskClick?: (identifier: string, assigneeAgentId?: string) => void;
+ subtasks?: any[];
+ }) => {
+ const subtask = subtasks?.[0];
+ if (!subtask) return null;
+
+ return (
+ <button
+ data-testid="parent-subtask"
+ type="button"
+ onClick={() => onSubtaskClick?.(subtask.identifier, subtask.assignee?.id ?? undefined)}
+ >
+ subtask
+ </button>
+ );
+ },
+}));
+
+describe('TaskParentBar', () => {
+ beforeEach(() => {
+ mocks.navigate.mockClear();
+ mocks.getDetail.mockReset();
+ mocks.taskState = createState({
+ agentId: 'agt_parent',
+ identifier: 'T-parent',
+ name: 'Parent task',
+ });
+ mocks.getDetail.mockResolvedValue({
+ data: {
+ agentId: 'agt_parent',
+ identifier: 'T-parent',
+ instruction: 'Parent instruction',
+ status: 'running',
+ subtasks: [],
+ },
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("opens the parent task inside the parent task's owning agent route", async () => {
+ render(<TaskParentBar />);
+
+ fireEvent.click(screen.getByText('Parent task').closest('button')!);
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_parent/task/T-parent');
+ await waitFor(() => expect(mocks.getDetail).toHaveBeenCalledWith('T-parent'));
+ });
+
+ it('falls back to the global route when the parent task owner is unknown', async () => {
+ mocks.taskState = createState({
+ identifier: 'T-parent',
+ name: 'Parent task',
+ });
+ mocks.getDetail.mockResolvedValue({
+ data: {
+ agentId: null,
+ identifier: 'T-parent',
+ instruction: 'Parent instruction',
+ status: 'running',
+ subtasks: [],
+ },
+ });
+
+ render(<TaskParentBar />);
+
+ await waitFor(() => expect(mocks.getDetail).toHaveBeenCalledWith('T-parent'));
+ fireEvent.click(screen.getByText('Parent task').closest('button')!);
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-parent');
+ });
+
+ it("opens parent subtasks inside the clicked subtask's owning agent route", async () => {
+ mocks.getDetail.mockResolvedValue({
+ data: {
+ agentId: 'agt_parent',
+ identifier: 'T-parent',
+ instruction: 'Parent instruction',
+ status: 'running',
+ subtasks: [
+ {
+ assignee: { id: 'agt_sibling' },
+ identifier: 'T-sibling',
+ status: 'backlog',
+ },
+ ],
+ },
+ });
+
+ render(<TaskParentBar />);
+
+ fireEvent.click(await screen.findByTestId('parent-subtask'));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_sibling/task/T-sibling');
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
index 60f27e0cbf8..f34790524fc 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx
@@ -10,6 +10,7 @@ import { taskDetailSelectors } from '@/store/task/selectors';
import TaskStatusIcon from '../features/TaskStatusIcon';
import TaskSubtaskProgressTag from '../features/TaskSubtaskProgressTag';
+import { taskDetailPath } from '../shared/taskDetailPath';
const TASK_STATUS_SET = new Set([
'backlog',
@@ -31,10 +32,15 @@ const TaskParentBar = memo(() => {
const parent = useTaskStore(taskDetailSelectors.activeTaskParent);
const currentIdentifier = useTaskStore(taskDetailSelectors.activeTaskDetail)?.identifier;
+ const [fetchedParentAgent, setFetchedParentAgent] = useState<
+ { agentId?: string | null; identifier: string } | undefined
+ >();
const [parentSubtasks, setParentSubtasks] = useState<TaskDetailSubtask[]>([]);
const [parentStatus, setParentStatus] = useState<TaskStatus>('backlog');
useEffect(() => {
+ let isActive = true;
+ setFetchedParentAgent(undefined);
setParentSubtasks([]);
setParentStatus('backlog');
if (!parent?.identifier) return;
@@ -42,17 +48,31 @@ const TaskParentBar = memo(() => {
taskService
.getDetail(parent.identifier)
.then((res) => {
+ if (!isActive) return;
const detail = res.data as TaskDetailData;
+ setFetchedParentAgent({ agentId: detail.agentId, identifier: parent.identifier });
setParentStatus(toTaskStatus(detail.status));
setParentSubtasks(detail.subtasks ?? []);
})
.catch((err) => {
+ if (!isActive) return;
console.error('[TaskParentBar] Failed to load parent subtasks', err);
});
+
+ return () => {
+ isActive = false;
+ };
}, [parent?.identifier]);
if (!parent) return null;
+ const parentAgentId =
+ parent.agentId === undefined
+ ? fetchedParentAgent?.identifier === parent.identifier
+ ? fetchedParentAgent.agentId
+ : undefined
+ : parent.agentId;
+
return (
<Flexbox horizontal align="center" gap={8}>
<Text fontSize={12} type={'secondary'}>
@@ -62,7 +82,7 @@ const TaskParentBar = memo(() => {
icon={<TaskStatusIcon size={16} status={parentStatus} />}
size={'small'}
type={'text'}
- onClick={() => navigate(`/task/${parent.identifier}`)}
+ onClick={() => navigate(taskDetailPath(parent.identifier, parentAgentId ?? undefined))}
>
<Text weight={500}>{parent.name}</Text>
</Button>
@@ -70,7 +90,9 @@ const TaskParentBar = memo(() => {
<TaskSubtaskProgressTag
currentIdentifier={currentIdentifier}
subtasks={parentSubtasks}
- onSubtaskClick={(identifier) => navigate(`/task/${identifier}`)}
+ onSubtaskClick={(identifier, assigneeAgentId) =>
+ navigate(taskDetailPath(identifier, assigneeAgentId))
+ }
/>
)}
</Flexbox>
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
new file mode 100644
index 00000000000..85694b0a42c
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
@@ -0,0 +1,193 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TaskSubtasks from './TaskSubtasks';
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ runReadySubtasks: vi.fn(),
+ taskState: {
+ activeTaskId: 'T-parent',
+ taskDetailMap: {
+ 'T-parent': {
+ agentId: 'agt_parent',
+ identifier: 'T-parent',
+ instruction: 'Parent instruction',
+ status: 'running',
+ subtasks: [
+ {
+ assignee: { avatar: null, backgroundColor: null, id: 'agt_child', title: 'Child' },
+ identifier: 'T-child',
+ name: 'Child task',
+ status: 'backlog',
+ },
+ ],
+ },
+ },
+ } as any,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ onClick }: { onClick?: () => void }) => (
+ <button type="button" onClick={onClick}>
+ action
+ </button>
+ ),
+ Block: ({
+ children,
+ clickable,
+ onClick,
+ }: {
+ children: ReactNode;
+ clickable?: boolean;
+ onClick?: () => void;
+ }) =>
+ clickable ? (
+ <button type="button" onClick={onClick}>
+ {children}
+ </button>
+ ) : (
+ <div>{children}</div>
+ ),
+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Icon: () => <span>icon</span>,
+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+ showContextMenu: vi.fn(),
+}));
+
+vi.mock('antd', () => ({
+ App: {
+ useApp: () => ({
+ message: { error: vi.fn(), info: vi.fn(), success: vi.fn(), warning: vi.fn() },
+ modal: { confirm: vi.fn() },
+ }),
+ },
+ ConfigProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+ Tree: ({ onSelect }: { onSelect?: (keys: string[]) => void }) => (
+ <button data-testid="subtask-tree-node" type="button" onClick={() => onSelect?.(['T-child'])}>
+ T-child
+ </button>
+ ),
+}));
+
+vi.mock('antd-style', () => ({
+ cssVar: {
+ colorTextDescription: '#999',
+ colorTextSecondary: '#666',
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => mocks.navigate,
+}));
+
+vi.mock('@/services/task', () => ({
+ taskService: {
+ previewSubtaskLayers: vi.fn(),
+ },
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: any) =>
+ selector({
+ ...mocks.taskState,
+ runReadySubtasks: mocks.runReadySubtasks,
+ }),
+}));
+
+vi.mock('../AgentTaskList/CreateTaskInlineEntry', () => ({
+ default: () => <div>create task</div>,
+}));
+
+vi.mock('../features/AssigneeAgentSelector', () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock('../features/AssigneeAvatar', () => ({
+ default: () => <span>assignee</span>,
+}));
+
+vi.mock('../features/TaskPriorityTag', () => ({
+ default: () => <span>priority</span>,
+}));
+
+vi.mock('../features/TaskStatusTag', () => ({
+ default: () => <span>status</span>,
+}));
+
+vi.mock('../features/TaskSubtaskProgressTag', () => ({
+ default: () => <span>progress</span>,
+}));
+
+vi.mock('../features/TaskTriggerTag', () => ({
+ default: () => <span>trigger</span>,
+}));
+
+vi.mock('../features/useTaskItemContextMenu', () => ({
+ useTaskContextMenuActions: () => ({
+ buildItems: vi.fn(() => []),
+ installKeyboardHandlers: vi.fn(),
+ }),
+}));
+
+vi.mock('../shared/AccordionArrowIcon', () => ({
+ default: () => <span>arrow</span>,
+}));
+
+vi.mock('../shared/style', () => ({
+ styles: { subtaskTree: 'subtask-tree' },
+}));
+
+vi.mock('./RunSubtasksPreview', () => ({
+ default: () => <div>preview</div>,
+}));
+
+describe('TaskSubtasks', () => {
+ beforeEach(() => {
+ mocks.navigate.mockClear();
+ mocks.taskState.taskDetailMap['T-parent'].subtasks = [
+ {
+ assignee: { avatar: null, backgroundColor: null, id: 'agt_child', title: 'Child' },
+ identifier: 'T-child',
+ name: 'Child task',
+ status: 'backlog',
+ },
+ ];
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("opens a selected subtask using the subtask's assignee agent", () => {
+ render(<TaskSubtasks />);
+
+ fireEvent.click(screen.getByTestId('subtask-tree-node'));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_child/task/T-child');
+ });
+
+ it('falls back to the global task route when the selected subtask has no assignee', () => {
+ mocks.taskState.taskDetailMap['T-parent'].subtasks = [
+ {
+ identifier: 'T-child',
+ name: 'Child task',
+ status: 'backlog',
+ },
+ ];
+
+ render(<TaskSubtasks />);
+
+ fireEvent.click(screen.getByTestId('subtask-tree-node'));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-child');
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
index 28d143c56da..41e5682a092 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx
@@ -23,6 +23,7 @@ import TaskTriggerTag from '../features/TaskTriggerTag';
import { useTaskContextMenuActions } from '../features/useTaskItemContextMenu';
import AccordionArrowIcon from '../shared/AccordionArrowIcon';
import { styles } from '../shared/style';
+import { taskDetailPath } from '../shared/taskDetailPath';
import RunSubtasksPreview from './RunSubtasksPreview';
type TaskStatus = 'backlog' | 'canceled' | 'completed' | 'failed' | 'paused' | 'running';
@@ -139,13 +140,6 @@ const TaskSubtasks = memo(() => {
const [isExpanded, setIsExpanded] = useState(true);
const [isPlanning, setIsPlanning] = useState(false);
- const handleNavigate = useCallback(
- (identifier: string) => {
- navigate(`/task/${identifier}`);
- },
- [navigate],
- );
-
const subtaskMap = useMemo(() => {
const map = new Map<string, TaskDetailSubtask>();
const walk = (items: TaskDetailSubtask[]) => {
@@ -158,6 +152,14 @@ const TaskSubtasks = memo(() => {
return map;
}, [subtasks]);
+ const handleNavigate = useCallback(
+ (identifier: string) => {
+ const subtask = subtaskMap.get(identifier);
+ navigate(taskDetailPath(identifier, subtask?.assignee?.id ?? undefined));
+ },
+ [navigate, subtaskMap],
+ );
+
const treeData = useMemo(() => {
if (subtasks.length === 0) return [];
return toTreeData(buildTree(subtasks));
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 7cd29707b25..1eb6d1ca7f8 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -15,6 +15,7 @@ import { taskListSelectors } from '@/store/task/selectors';
import { createTaskModal } from '../CreateTaskModal';
import Breadcrumb from '../shared/Breadcrumb';
+import { taskDetailPath } from '../shared/taskDetailPath';
import CreateTaskInlineEntry from './CreateTaskInlineEntry';
import EmptyState from './EmptyState';
import KanbanBoard from './KanbanBoard';
@@ -50,7 +51,7 @@ const AgentTasksPage = memo(() => {
const handleCreateTask = useCallback(() => {
createTaskModal({
onCreated: (task) => {
- navigate(`/task/${task.identifier}`);
+ navigate(taskDetailPath(task.identifier, task.agentId));
},
});
}, [navigate]);
diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
index 3f0c0fcdc26..d0226cbad65 100644
--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx
@@ -24,6 +24,7 @@ import type { TaskGroupItem, TaskListItem } from '@/store/task/slices/list/initi
import { createTaskModal } from '../CreateTaskModal';
import AgentTaskItem from '../features/AgentTaskItem';
+import { taskDetailPath } from '../shared/taskDetailPath';
import HiddenColumnsPanel from './HiddenColumnsPanel';
import KanbanColumn, { COLUMN_I18N_KEYS, COLUMN_STATUS_ICON, COLUMN_WIDTH } from './KanbanColumn';
@@ -135,7 +136,7 @@ const KanbanBoard = memo(() => {
const handleCreateTask = useCallback(() => {
createTaskModal({
onCreated: (task) => {
- navigate(`/task/${task.identifier}`);
+ navigate(taskDetailPath(task.identifier, task.agentId));
},
showInlineToggle: false,
});
diff --git a/src/features/AgentTasks/features/AgentTaskItem.test.tsx b/src/features/AgentTasks/features/AgentTaskItem.test.tsx
new file mode 100644
index 00000000000..631a22369a0
--- /dev/null
+++ b/src/features/AgentTasks/features/AgentTaskItem.test.tsx
@@ -0,0 +1,190 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import AgentTaskItem from './AgentTaskItem';
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ taskDetailMap: {} as Record<string, { subtasks?: any[] }>,
+ useFetchTaskDetail: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Block: ({
+ children,
+ clickable,
+ onClick,
+ }: {
+ children: ReactNode;
+ clickable?: boolean;
+ onClick?: () => void;
+ }) =>
+ clickable ? (
+ <button data-testid="task-card" type="button" onClick={onClick}>
+ {children}
+ </button>
+ ) : (
+ <span>{children}</span>
+ ),
+ ContextMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ i18n: { language: 'en-US' },
+ t: (key: string, options?: { defaultValue?: string }) => options?.defaultValue ?? key,
+ }),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => mocks.navigate,
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: any) =>
+ selector({
+ taskDetailMap: mocks.taskDetailMap,
+ useFetchTaskDetail: mocks.useFetchTaskDetail,
+ }),
+}));
+
+vi.mock('./AssigneeAgentSelector', () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock('./AssigneeAvatar', () => ({
+ default: () => <span>assignee</span>,
+}));
+
+vi.mock('./formatTaskItemDate', () => ({
+ formatTaskItemDate: () => 'today',
+}));
+
+vi.mock('./TaskLatestActivity', () => ({
+ default: () => null,
+}));
+
+vi.mock('./TaskPriorityTag', () => ({
+ default: () => <span>priority</span>,
+}));
+
+vi.mock('./TaskStatusTag', () => ({
+ default: () => <span>status</span>,
+}));
+
+vi.mock('./TaskSubtaskProgressTag', () => ({
+ default: ({
+ onSubtaskClick,
+ subtasks,
+ }: {
+ onSubtaskClick?: (identifier: string, assigneeAgentId?: string) => void;
+ subtasks?: any[];
+ }) => {
+ const subtask = subtasks?.[0];
+ if (!subtask) return null;
+
+ return (
+ <span
+ data-testid="subtask-progress"
+ onClick={(event) => {
+ event.stopPropagation();
+ onSubtaskClick?.(subtask.identifier, subtask.assignee?.id ?? undefined);
+ }}
+ >
+ subtask
+ </span>
+ );
+ },
+}));
+
+vi.mock('./TaskTriggerTag', () => ({
+ default: () => <span>trigger</span>,
+}));
+
+vi.mock('./useTaskItemContextMenu', () => ({
+ useTaskItemContextMenu: () => ({ items: [], onContextMenu: vi.fn() }),
+}));
+
+const createTask = (assigneeAgentId?: string | null) =>
+ ({
+ assigneeAgentId,
+ createdAt: new Date('2026-05-18T00:00:00.000Z'),
+ identifier: 'T-22',
+ name: 'Hourly trend update',
+ priority: 2,
+ status: 'scheduled',
+ updatedAt: new Date('2026-05-18T00:00:00.000Z'),
+ }) as any;
+
+describe('AgentTaskItem', () => {
+ beforeEach(() => {
+ mocks.navigate.mockClear();
+ mocks.taskDetailMap = {};
+ mocks.useFetchTaskDetail.mockClear();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('opens an assigned task inside its owning agent route', () => {
+ render(<AgentTaskItem task={createTask('agt_owner')} />);
+
+ fireEvent.click(screen.getByTestId('task-card'));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_owner/task/T-22');
+ });
+
+ it('falls back to the global task detail route when the task has no assignee', () => {
+ render(<AgentTaskItem task={createTask(null)} />);
+
+ fireEvent.click(screen.getByTestId('task-card'));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22');
+ });
+
+ it("opens a subtask inside the clicked subtask's assignee route", () => {
+ mocks.taskDetailMap = {
+ 'T-22': {
+ subtasks: [
+ {
+ assignee: { id: 'agt_child' },
+ identifier: 'T-23',
+ status: 'backlog',
+ },
+ ],
+ },
+ };
+
+ render(<AgentTaskItem task={createTask('agt_parent')} />);
+
+ fireEvent.click(screen.getAllByTestId('subtask-progress')[0]);
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_child/task/T-23');
+ });
+
+ it('falls back to the global route when the clicked subtask has no assignee', () => {
+ mocks.taskDetailMap = {
+ 'T-22': {
+ subtasks: [
+ {
+ identifier: 'T-23',
+ status: 'backlog',
+ },
+ ],
+ },
+ };
+
+ render(<AgentTaskItem task={createTask('agt_parent')} />);
+
+ fireEvent.click(screen.getAllByTestId('subtask-progress')[0]);
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-23');
+ });
+});
diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsx
index 7548adb3848..2a934f2c6af 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx
@@ -7,6 +7,7 @@ import { useNavigate } from 'react-router-dom';
import { useTaskStore } from '@/store/task';
import type { TaskListItem } from '@/store/task/slices/list/initialState';
+import { taskDetailPath } from '../shared/taskDetailPath';
import AssigneeAgentSelector from './AssigneeAgentSelector';
import AssigneeAvatar from './AssigneeAvatar';
import { formatTaskItemDate } from './formatTaskItemDate';
@@ -57,12 +58,12 @@ const AgentTaskItem = memo<TaskItemProps>(({ task, variant = 'default' }) => {
const hasName = Boolean(task.name?.trim());
const handleClick = useCallback(() => {
- navigate(`/task/${task.identifier}`);
- }, [navigate, task.identifier]);
+ navigate(taskDetailPath(task.identifier, task.assigneeAgentId ?? undefined));
+ }, [navigate, task.assigneeAgentId, task.identifier]);
const handleSubtaskClick = useCallback(
- (identifier: string) => {
- navigate(`/task/${identifier}`);
+ (identifier: string, assigneeAgentId?: string) => {
+ navigate(taskDetailPath(identifier, assigneeAgentId));
},
[navigate],
);
diff --git a/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx b/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx
new file mode 100644
index 00000000000..23ca7179d91
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx
@@ -0,0 +1,77 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import TaskSubtaskProgressTag from './TaskSubtaskProgressTag';
+
+vi.mock('@lobehub/ui', () => ({
+ Block: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
+ <div onClick={onClick}>{children}</div>
+ ),
+ DropdownMenu: ({
+ children,
+ items,
+ }: {
+ children: ReactNode;
+ items?: Array<{ key: string; onClick?: () => void }>;
+ }) => (
+ <div>
+ {children}
+ {items?.map((item) => (
+ <button
+ data-testid={`subtask-${item.key}`}
+ key={item.key}
+ type="button"
+ onClick={item.onClick}
+ >
+ {item.key}
+ </button>
+ ))}
+ </div>
+ ),
+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('antd', () => ({
+ Progress: () => <span>progress</span>,
+}));
+
+vi.mock('antd-style', () => ({
+ cssVar: { colorSuccess: 'green' },
+}));
+
+vi.mock('./TaskStatusIcon', () => ({
+ default: () => <span>status</span>,
+}));
+
+describe('TaskSubtaskProgressTag', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("passes the clicked subtask's assignee to the navigation callback", () => {
+ const onSubtaskClick = vi.fn();
+
+ render(
+ <TaskSubtaskProgressTag
+ subtasks={[
+ {
+ assignee: { avatar: null, backgroundColor: null, id: 'agt_child', title: 'Child' },
+ identifier: 'T-2',
+ name: 'Child task',
+ status: 'backlog',
+ },
+ ]}
+ onSubtaskClick={onSubtaskClick}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId('subtask-T-2'));
+
+ expect(onSubtaskClick).toHaveBeenCalledWith('T-2', 'agt_child');
+ });
+});
diff --git a/src/features/AgentTasks/features/TaskSubtaskProgressTag.tsx b/src/features/AgentTasks/features/TaskSubtaskProgressTag.tsx
index 148b1b9e8ee..bdf51c3c12d 100644
--- a/src/features/AgentTasks/features/TaskSubtaskProgressTag.tsx
+++ b/src/features/AgentTasks/features/TaskSubtaskProgressTag.tsx
@@ -75,7 +75,7 @@ const flattenSubtasks = (nodes: TaskDetailSubtask[]) => {
interface TaskSubtaskProgressTagProps {
currentIdentifier?: string;
- onSubtaskClick?: (identifier: string) => void;
+ onSubtaskClick?: (identifier: string, assigneeAgentId?: string) => void;
subtasks?: TaskDetailSubtask[];
}
@@ -116,7 +116,8 @@ const TaskSubtaskProgressTag = memo<TaskSubtaskProgressTagProps>(
</Text>
</Flexbox>
),
- onClick: () => onSubtaskClick?.(subtask.task.identifier),
+ onClick: () =>
+ onSubtaskClick?.(subtask.task.identifier, subtask.task.assignee?.id ?? undefined),
};
}) as DropdownMenuProps['items'];
diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
index ed4aa4794e7..89c248948ee 100644
--- a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx
@@ -25,6 +25,7 @@ import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useTaskStore } from '@/store/task';
+import { taskDetailPath } from '../shared/taskDetailPath';
import { renderMenuExtra } from './menuExtra';
import { PRIORITY_META } from './TaskPriorityTag';
import { STATUS_META, USER_SELECTABLE_STATUSES } from './TaskStatusTag';
@@ -125,7 +126,10 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
} as ContextMenuItem;
});
- const taskUrl = `${appOrigin}/task/${task.identifier}`;
+ const taskUrl = `${appOrigin}${taskDetailPath(
+ task.identifier,
+ task.assigneeAgentId ?? undefined,
+ )}`;
const canRunNow = RUN_NOW_STATUSES.has(currentStatus);
return [
@@ -288,13 +292,10 @@ export const useTaskContextMenuActions = (): TaskContextMenuActions => {
export const useTaskItemContextMenu = (task: TaskContextMenuTarget): TaskItemContextMenu => {
const { buildItems, installKeyboardHandlers } = useTaskContextMenuActions();
- const items = useMemo(
- () => buildItems(task),
- [buildItems, task.identifier, task.status, task.priority, task.assigneeAgentId],
- );
+ const items = useMemo(() => buildItems(task), [buildItems, task]);
const onContextMenu = useCallback(
() => installKeyboardHandlers(task),
- [installKeyboardHandlers, task.identifier, task.status, task.priority],
+ [installKeyboardHandlers, task],
);
return { items, onContextMenu };
};
diff --git a/src/features/AgentTasks/shared/Breadcrumb.test.tsx b/src/features/AgentTasks/shared/Breadcrumb.test.tsx
new file mode 100644
index 00000000000..44db026ffe1
--- /dev/null
+++ b/src/features/AgentTasks/shared/Breadcrumb.test.tsx
@@ -0,0 +1,108 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import Breadcrumb from './Breadcrumb';
+
+const mocks = vi.hoisted(() => ({
+ taskState: {} as any,
+}));
+
+const createState = (taskDetailMap: Record<string, any>) => ({
+ taskDetailMap,
+});
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: () => <span>icon</span>,
+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('antd', () => ({
+ Breadcrumb: ({ items }: { items: Array<{ key?: string; title: ReactNode }> }) => (
+ <nav>
+ {items.map((item, index) => (
+ <span data-testid="crumb" key={item.key ?? index}>
+ {item.title}
+ </span>
+ ))}
+ </nav>
+ ),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('react-router-dom', () => ({
+ Link: ({ children, to }: { children: ReactNode; to: string }) => <a href={to}>{children}</a>,
+}));
+
+vi.mock('zustand/react/shallow', () => ({
+ useShallow: (selector: any) => selector,
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: any) => selector(mocks.taskState),
+}));
+
+vi.mock('./style', () => ({
+ styles: { breadcrumb: 'breadcrumb' },
+}));
+
+describe('Breadcrumb', () => {
+ beforeEach(() => {
+ mocks.taskState = createState({
+ 'T-child': {
+ identifier: 'T-child',
+ instruction: 'Child instruction',
+ name: 'Child task',
+ parent: { agentId: 'agt_parent', identifier: 'T-parent', name: 'Parent task' },
+ status: 'running',
+ },
+ 'T-parent': {
+ agentId: 'agt_parent',
+ identifier: 'T-parent',
+ instruction: 'Parent instruction',
+ name: 'Parent task',
+ parent: { agentId: null, identifier: 'T-root', name: 'Root task' },
+ status: 'running',
+ },
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('uses the ancestor owner agent when building breadcrumb links', () => {
+ render(<Breadcrumb taskId="T-child" />);
+
+ expect(screen.getByRole('link', { name: 'T-parent' })).toHaveAttribute(
+ 'href',
+ '/agent/agt_parent/task/T-parent',
+ );
+ expect(screen.getByRole('link', { name: 'T-root' })).toHaveAttribute('href', '/task/T-root');
+ });
+
+ it('falls back to the global route when an ancestor owner is unknown', () => {
+ mocks.taskState = createState({
+ 'T-child': {
+ identifier: 'T-child',
+ instruction: 'Child instruction',
+ name: 'Child task',
+ parent: { identifier: 'T-parent', name: 'Parent task' },
+ status: 'running',
+ },
+ });
+
+ render(<Breadcrumb taskId="T-child" />);
+
+ expect(screen.getByRole('link', { name: 'T-parent' })).toHaveAttribute(
+ 'href',
+ '/task/T-parent',
+ );
+ });
+});
diff --git a/src/features/AgentTasks/shared/Breadcrumb.tsx b/src/features/AgentTasks/shared/Breadcrumb.tsx
index d0911926de6..4837825aafa 100644
--- a/src/features/AgentTasks/shared/Breadcrumb.tsx
+++ b/src/features/AgentTasks/shared/Breadcrumb.tsx
@@ -9,6 +9,7 @@ import { useShallow } from 'zustand/react/shallow';
import { useTaskStore } from '@/store/task';
import { styles } from './style';
+import { taskDetailPath } from './taskDetailPath';
interface BreadcrumbProps {
taskId?: string;
@@ -23,13 +24,17 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
const ancestors = useTaskStore(
useShallow((s) => {
if (!taskId) return [];
- const chain: string[] = [];
+ const chain: Array<{ agentId?: string | null; identifier: string }> = [];
const visited = new Set<string>([taskId]);
- let cursor = s.taskDetailMap[taskId]?.parent?.identifier;
- while (cursor && !visited.has(cursor)) {
- visited.add(cursor);
- chain.push(cursor);
- cursor = s.taskDetailMap[cursor]?.parent?.identifier;
+ let cursor = s.taskDetailMap[taskId]?.parent;
+ while (cursor?.identifier && !visited.has(cursor.identifier)) {
+ const detail = s.taskDetailMap[cursor.identifier];
+ visited.add(cursor.identifier);
+ chain.push({
+ agentId: cursor.agentId === undefined ? detail?.agentId : cursor.agentId,
+ identifier: cursor.identifier,
+ });
+ cursor = detail?.parent;
}
return chain.reverse();
}),
@@ -41,10 +46,10 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {
</Text>
);
- const ancestorCrumbs = ancestors.map((identifier) => ({
+ const ancestorCrumbs = ancestors.map(({ identifier, agentId }) => ({
key: identifier,
title: (
- <Link to={`/task/${identifier}`}>
+ <Link to={taskDetailPath(identifier, agentId ?? undefined)}>
<Text color={'inherit'} weight={500}>
{identifier}
</Text>
diff --git a/src/features/AgentTasks/shared/taskDetailPath.test.ts b/src/features/AgentTasks/shared/taskDetailPath.test.ts
new file mode 100644
index 00000000000..7262429a075
--- /dev/null
+++ b/src/features/AgentTasks/shared/taskDetailPath.test.ts
@@ -0,0 +1,50 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { taskDetailPath, useNavigateToTaskDetail, useTaskDetailPath } from './taskDetailPath';
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ params: {} as { aid?: string },
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => mocks.navigate,
+ useParams: () => mocks.params,
+}));
+
+describe('taskDetailPath', () => {
+ beforeEach(() => {
+ mocks.navigate.mockClear();
+ mocks.params = {};
+ });
+
+ it('builds an agent-scoped path when an agent id is provided', () => {
+ expect(taskDetailPath('T-1', 'agt_owner')).toBe('/agent/agt_owner/task/T-1');
+ });
+
+ it('falls back to the global task path without an agent id', () => {
+ expect(taskDetailPath('T-1')).toBe('/task/T-1');
+ });
+
+ it('uses the route agent by default and allows explicit assignee override', () => {
+ mocks.params = { aid: 'agt_current' };
+
+ const { result } = renderHook(() => useTaskDetailPath());
+
+ expect(result.current('T-1')).toBe('/agent/agt_current/task/T-1');
+ expect(result.current('T-2', 'agt_child')).toBe('/agent/agt_child/task/T-2');
+ });
+
+ it('navigates to an explicit assignee route when provided', () => {
+ mocks.params = { aid: 'agt_current' };
+
+ const { result } = renderHook(() => useNavigateToTaskDetail());
+ result.current('T-2', 'agt_child');
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_child/task/T-2');
+ });
+});
diff --git a/src/features/AgentTasks/shared/taskDetailPath.ts b/src/features/AgentTasks/shared/taskDetailPath.ts
new file mode 100644
index 00000000000..00013551a07
--- /dev/null
+++ b/src/features/AgentTasks/shared/taskDetailPath.ts
@@ -0,0 +1,26 @@
+import { useCallback } from 'react';
+import { useNavigate, useParams } from 'react-router-dom';
+
+export const taskDetailPath = (taskId: string, agentId?: string) =>
+ agentId ? `/agent/${agentId}/task/${taskId}` : `/task/${taskId}`;
+
+export const useTaskDetailPath = () => {
+ const { aid } = useParams<{ aid?: string }>();
+
+ return useCallback(
+ (taskId: string, agentId?: string) => taskDetailPath(taskId, agentId ?? aid),
+ [aid],
+ );
+};
+
+export const useNavigateToTaskDetail = () => {
+ const navigate = useNavigate();
+ const getTaskDetailPath = useTaskDetailPath();
+
+ return useCallback(
+ (taskId: string, agentId?: string) => {
+ navigate(getTaskDetailPath(taskId, agentId));
+ },
+ [getTaskDetailPath, navigate],
+ );
+};
diff --git a/src/features/DailyBrief/BriefCard.tsx b/src/features/DailyBrief/BriefCard.tsx
index c0bb0df9f6a..5c3d872e183 100644
--- a/src/features/DailyBrief/BriefCard.tsx
+++ b/src/features/DailyBrief/BriefCard.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import Time from '@/routes/(main)/home/features/components/Time';
import BriefCardActions from './BriefCardActions';
@@ -54,6 +55,10 @@ const BriefCard = memo<BriefCardProps>(
const showFull = !isResolved || expanded;
const canNavigate = enableNavigation && Boolean(brief.taskId);
+ const handleNavigate = () => {
+ if (!brief.taskId) return;
+ navigate(taskDetailPath(brief.taskId, brief.agentId ?? undefined));
+ };
return (
<Block
@@ -69,7 +74,7 @@ const BriefCard = memo<BriefCardProps>(
className={canNavigate ? styles.clickableHeader : undefined}
gap={16}
justify={'space-between'}
- onClick={canNavigate ? () => navigate(`/task/${brief.taskId}`) : undefined}
+ onClick={canNavigate ? handleNavigate : undefined}
>
<Flexbox horizontal align={'center'} flex={1} gap={8} style={{ overflow: 'hidden' }}>
<BriefIcon muted={isResolved} type={brief.type} />
diff --git a/src/features/Electron/navigation/routeMetadata.ts b/src/features/Electron/navigation/routeMetadata.ts
index fe5b646a3bd..e1d01296904 100644
--- a/src/features/Electron/navigation/routeMetadata.ts
+++ b/src/features/Electron/navigation/routeMetadata.ts
@@ -58,7 +58,7 @@ const routePatterns: RoutePattern[] = [
},
{
icon: MessageSquare,
- test: (p) => p.startsWith('/agent/'),
+ test: (p) => p.startsWith('/agent/') && !/^\/agent\/[^/]+\/task\//.test(p),
titleKey: 'navigation.chat',
useDynamicTitle: true,
},
@@ -123,7 +123,8 @@ const routePatterns: RoutePattern[] = [
// Tasks routes (cross-agent global view + singular task detail)
{
icon: tasksIcon,
- test: (p) => p.startsWith('/tasks') || p.startsWith('/task/'),
+ test: (p) =>
+ p.startsWith('/tasks') || p.startsWith('/task/') || /^\/agent\/[^/]+\/task\//.test(p),
titleKey: 'navigation.tasks',
},
diff --git a/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts b/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts
index 681aed32222..2342200ff16 100644
--- a/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts
+++ b/src/features/RecommendTaskTemplates/useTaskTemplateCreate.ts
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
+import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import { taskTemplateService } from '@/services/taskTemplate';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
@@ -63,7 +64,9 @@ export const useTaskTemplateCreate = ({
setCreated(true);
onCreated(template.id);
if (createdTask?.identifier) {
- navigate(`/task/${createdTask.identifier}`);
+ navigate(
+ taskDetailPath(createdTask.identifier, createdTask.assigneeAgentId ?? inboxAgentId),
+ );
}
} catch (error) {
console.error('[taskTemplate:create]', error);
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Task/StatusGroup.tsx b/src/routes/(main)/agent/_layout/Sidebar/Task/StatusGroup.tsx
index d21925fbd6a..7173b60f80b 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Task/StatusGroup.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Task/StatusGroup.tsx
@@ -60,7 +60,11 @@ const StatusGroup = memo<StatusGroupProps>(({ group }) => {
>
<Flexbox gap={1} paddingBlock={1}>
{group.tasks.map((task) => (
- <TaskItem active={taskId === task.identifier} key={task.id} task={task} />
+ <TaskItem
+ active={taskId === task.identifier || taskId === task.id}
+ key={task.id}
+ task={task}
+ />
))}
</Flexbox>
</AccordionItem>
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.test.tsx
new file mode 100644
index 00000000000..fc5743a9db5
--- /dev/null
+++ b/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.test.tsx
@@ -0,0 +1,76 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import TaskItem from './TaskItem';
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ params: {} as { aid?: string },
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+}));
+
+vi.mock('@/features/NavPanel/components/NavItem', () => ({
+ default: ({
+ active,
+ onClick,
+ slots,
+ title,
+ }: {
+ active?: boolean;
+ onClick?: () => void;
+ slots?: { titlePrefix?: ReactNode };
+ title: ReactNode;
+ }) => (
+ <button data-active={active ? 'true' : 'false'} onClick={onClick}>
+ {slots?.titlePrefix}
+ {title}
+ </button>
+ ),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => mocks.navigate,
+ useParams: () => mocks.params,
+}));
+
+const task = {
+ id: 'task_1',
+ identifier: 'T-22',
+ name: 'Hourly trend update',
+};
+
+describe('Task sidebar item', () => {
+ beforeEach(() => {
+ mocks.navigate.mockClear();
+ mocks.params = {};
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('opens task detail inside the current agent route when an agent route param exists', () => {
+ mocks.params = { aid: 'agt_current' };
+
+ render(<TaskItem task={task as any} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'T-22 Hourly trend update' }));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_current/task/T-22');
+ });
+
+ it('falls back to the global task detail route outside agent context', () => {
+ render(<TaskItem task={task as any} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'T-22 Hourly trend update' }));
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22');
+ });
+});
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.tsx b/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.tsx
index b5d3eaf4c25..f859f45b48e 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.tsx
@@ -3,8 +3,8 @@
import { Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { memo, useCallback } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { useNavigateToTaskDetail } from '@/features/AgentTasks/shared/taskDetailPath';
import NavItem from '@/features/NavPanel/components/NavItem';
import type { TaskGroupItem } from '@/store/task/slices/list/initialState';
@@ -16,11 +16,11 @@ interface TaskItemProps {
}
const TaskItem = memo<TaskItemProps>(({ task, active }) => {
- const navigate = useNavigate();
+ const navigateToTaskDetail = useNavigateToTaskDetail();
const handleClick = useCallback(() => {
- navigate(`/task/${task.identifier}`);
- }, [navigate, task.identifier]);
+ navigateToTaskDetail(task.identifier);
+ }, [navigateToTaskDetail, task.identifier]);
const hasName = Boolean(task.name?.trim());
const displayTitle = hasName ? task.name : task.identifier;
diff --git a/src/routes/(main)/agent/task/[taskId]/index.tsx b/src/routes/(main)/agent/task/[taskId]/index.tsx
new file mode 100644
index 00000000000..2933d5d7b1b
--- /dev/null
+++ b/src/routes/(main)/agent/task/[taskId]/index.tsx
@@ -0,0 +1,16 @@
+'use client';
+
+import { memo } from 'react';
+import { useParams } from 'react-router-dom';
+
+import { TaskDetailPage } from '@/features/AgentTasks';
+
+const AgentTaskDetailRoute = memo(() => {
+ const { taskId } = useParams<{ taskId?: string }>();
+
+ if (!taskId) return null;
+
+ return <TaskDetailPage showTaskAgentPanelToggle={false} taskId={taskId} />;
+});
+
+export default AgentTaskDetailRoute;
diff --git a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx
index 1e76926902d..76a6dc8bb1f 100644
--- a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx
+++ b/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx
@@ -6,6 +6,7 @@ import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
+import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';
import { useClientDataSWR } from '@/libs/swr';
@@ -40,7 +41,7 @@ const AllRecentsDrawer = memo<AllRecentsDrawerProps>(({ open, onClose }) => {
const taskId = item.id;
if (!taskId) return item.routePath;
- return `/task/${taskId}`;
+ return taskDetailPath(taskId, item.agentId ?? undefined);
}, []);
return (
diff --git a/src/routes/(main)/home/features/Recents/List.tsx b/src/routes/(main)/home/features/Recents/List.tsx
index 2d73df683f4..51ce8248d54 100644
--- a/src/routes/(main)/home/features/Recents/List.tsx
+++ b/src/routes/(main)/home/features/Recents/List.tsx
@@ -4,6 +4,7 @@ import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
+import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useGlobalStore } from '@/store/global';
@@ -33,7 +34,7 @@ const RecentsList = memo(() => {
const taskId = item.id;
if (!taskId) return item.routePath;
- return `/task/${taskId}`;
+ return taskDetailPath(taskId, item.agentId ?? undefined);
}, []);
if (!isInit) {
diff --git a/src/server/routers/lambda/recent.ts b/src/server/routers/lambda/recent.ts
index ddb6fe69cf2..5e666a9ae5f 100644
--- a/src/server/routers/lambda/recent.ts
+++ b/src/server/routers/lambda/recent.ts
@@ -56,7 +56,9 @@ export const recentRouter = router({
break;
}
case 'task': {
- routePath = item.routeId ? `/agent/${item.routeId}` : '/';
+ routePath = item.routeId
+ ? `/agent/${item.routeId}/task/${item.id}`
+ : `/task/${item.id}`;
break;
}
}
diff --git a/src/server/services/task/index.test.ts b/src/server/services/task/index.test.ts
index 7a5dd970d08..59f03fc8ff7 100644
--- a/src/server/services/task/index.test.ts
+++ b/src/server/services/task/index.test.ts
@@ -164,7 +164,12 @@ describe('TaskService', () => {
totalTopics: 0,
};
- const parentTask = { id: 'task_001', identifier: 'TASK-1', name: 'Parent Task' };
+ const parentTask = {
+ assigneeAgentId: 'agt_parent',
+ id: 'task_001',
+ identifier: 'TASK-1',
+ name: 'Parent Task',
+ };
mockTaskModel.resolve.mockResolvedValue(task);
mockTaskModel.findAllDescendants.mockResolvedValue([]);
@@ -181,7 +186,11 @@ describe('TaskService', () => {
const service = new TaskService(db, userId);
const result = await service.getTaskDetail('TASK-2');
- expect(result?.parent).toEqual({ identifier: 'TASK-1', name: 'Parent Task' });
+ expect(result?.parent).toEqual({
+ agentId: 'agt_parent',
+ identifier: 'TASK-1',
+ name: 'Parent Task',
+ });
expect(mockTaskModel.findById).toHaveBeenCalledWith('task_001');
});
diff --git a/src/server/services/task/index.ts b/src/server/services/task/index.ts
index 325be52f60b..ebeb25f0897 100644
--- a/src/server/services/task/index.ts
+++ b/src/server/services/task/index.ts
@@ -487,11 +487,15 @@ export class TaskService {
);
// Resolve parent
- let parent: { identifier: string; name: string | null } | null = null;
+ let parent: { agentId: string | null; identifier: string; name: string | null } | null = null;
if (task.parentTaskId) {
const parentTask = await this.taskModel.findById(task.parentTaskId);
if (parentTask) {
- parent = { identifier: parentTask.identifier, name: parentTask.name };
+ parent = {
+ agentId: parentTask.assigneeAgentId,
+ identifier: parentTask.identifier,
+ name: parentTask.name,
+ };
}
}
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 44997e5ca2b..6a241575cfe 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -23,6 +23,7 @@ import AgentTopicNotebookDocPage from '@/routes/(main)/agent/[topicId]/page/[doc
import AgentChannelPage from '@/routes/(main)/agent/channel';
import AgentPageRedirectPage from '@/routes/(main)/agent/page';
import AgentProfilePage from '@/routes/(main)/agent/profile';
+import AgentTaskDetailRoute from '@/routes/(main)/agent/task/[taskId]';
import CommunityLayout from '@/routes/(main)/community/_layout';
import CommunityDetailLayout from '@/routes/(main)/community/(detail)/_layout';
import CommunityDetailAgentPage from '@/routes/(main)/community/(detail)/agent';
@@ -138,6 +139,10 @@ export const desktopRoutes: RouteObject[] = [
element: <AgentChannelPage />,
path: 'channel',
},
+ {
+ element: <AgentTaskDetailRoute />,
+ path: 'task/:taskId',
+ },
],
element: <DesktopChatLayout />,
errorElement: <ErrorBoundary />,
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index 23d1a686c68..0be1c002d1a 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -84,6 +84,13 @@ export const desktopRoutes: RouteObject[] = [
),
path: 'channel',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/task/[taskId]'),
+ 'Desktop > Chat > Task Detail',
+ ),
+ path: 'task/:taskId',
+ },
],
element: dynamicLayout(
() => import('@/routes/(main)/agent/_layout'),
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index c5b766da686..6e33fd840ab 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -1,5 +1,5 @@
import { readFile } from 'node:fs/promises';
-import { join } from 'node:path';
+import path from 'node:path';
import { describe, expect, it } from 'vitest';
@@ -25,8 +25,8 @@ function normalizePaths(paths: string[]) {
async function readDesktopRouterSources() {
return Promise.all([
- readFile(join(process.cwd(), 'src/spa/router/desktopRouter.config.tsx'), 'utf8'),
- readFile(join(process.cwd(), 'src/spa/router/desktopRouter.config.desktop.tsx'), 'utf8'),
+ readFile(path.join(process.cwd(), 'src/spa/router/desktopRouter.config.tsx'), 'utf8'),
+ readFile(path.join(process.cwd(), 'src/spa/router/desktopRouter.config.desktop.tsx'), 'utf8'),
]);
}
@@ -54,6 +54,8 @@ describe('desktopRouter config sync', () => {
expect(asyncSource).toContain("import('@/routes/(main)/(task-workspace)/_layout')");
expect(syncSource).toContain("from '@/routes/(main)/(task-workspace)/_layout'");
+ expect(asyncSource).toContain("import('@/routes/(main)/agent/task/[taskId]')");
+ expect(syncSource).toContain("from '@/routes/(main)/agent/task/[taskId]'");
expect(asyncSource).not.toContain("import('@/routes/(main)/task-workspace/_layout')");
expect(syncSource).not.toContain("from '@/routes/(main)/task-workspace/_layout'");
expect(asyncSource).not.toContain("import('@/routes/(main)/tasks/_layout')");
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index 3d1a20b00f6..3a8e33ce5b0 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -251,6 +251,19 @@ export const mobileRoutes: RouteObject[] = [
errorElement: <ErrorBoundary resetPath="/tasks" />,
path: 'task',
},
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/task/[taskId]'),
+ 'Mobile > Agent Task Detail',
+ ),
+ path: ':aid/task/:taskId',
+ },
+ ],
+ errorElement: <ErrorBoundary resetPath="/tasks" />,
+ path: 'agent',
+ },
],
element: dynamicLayout(
() => import('@/routes/(main)/(task-workspace)/_layout'),
diff --git a/src/spa/router/mobileRouter.test.tsx b/src/spa/router/mobileRouter.test.tsx
index 71655b652d1..813c0f003cb 100644
--- a/src/spa/router/mobileRouter.test.tsx
+++ b/src/spa/router/mobileRouter.test.tsx
@@ -1,21 +1,23 @@
import { readFile } from 'node:fs/promises';
-import { join } from 'node:path';
+import path from 'node:path';
import { describe, expect, it } from 'vitest';
describe('mobileRouter task routes', () => {
it('registers task list and detail routes under the shared workspace layout', async () => {
const source = await readFile(
- join(process.cwd(), 'src/spa/router/mobileRouter.config.tsx'),
+ path.join(process.cwd(), 'src/spa/router/mobileRouter.config.tsx'),
'utf8',
);
expect(source).toContain("import('@/routes/(main)/(task-workspace)/_layout')");
expect(source).toContain("import('@/routes/(main)/tasks')");
expect(source).toContain("import('@/routes/(main)/task/[taskId]')");
+ expect(source).toContain("import('@/routes/(main)/agent/task/[taskId]')");
expect(source).toContain("path: 'tasks'");
expect(source).toContain("path: 'task'");
expect(source).toContain("path: ':taskId'");
+ expect(source).toContain("path: ':aid/task/:taskId'");
expect(source).not.toContain("import('@/routes/(main)/tasks/_layout')");
});
});
diff --git a/src/store/task/selectors/detailSelectors.test.ts b/src/store/task/selectors/detailSelectors.test.ts
index 44c3d864ed3..a493a29f10f 100644
--- a/src/store/task/selectors/detailSelectors.test.ts
+++ b/src/store/task/selectors/detailSelectors.test.ts
@@ -16,7 +16,7 @@ const mockDetail: TaskDetailData = {
identifier: 'T-1',
instruction: 'Do something',
name: 'Test Task',
- parent: { identifier: 'T-0', name: 'Parent' },
+ parent: { agentId: 'agt_parent', identifier: 'T-0', name: 'Parent' },
priority: 2,
review: { enabled: false },
status: 'running',
@@ -115,6 +115,7 @@ describe('taskDetailSelectors', () => {
it('should return activeTaskParent', () => {
expect(taskDetailSelectors.activeTaskParent(state)?.identifier).toBe('T-0');
+ expect(taskDetailSelectors.activeTaskParent(state)?.agentId).toBe('agt_parent');
});
it('should return activeTaskTopicCount', () => {