π€― 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
π fix(task): return breadcrumb to the filtered source list (#23174)
Bryanb09ed5ef7661
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsxindex 9ffd9ff53f7..9c180274b7b 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx@@ -7,6 +7,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import TaskDetailHeaderActions from './TaskDetailHeaderActions';+const locationMock = vi.hoisted(() => ({ state: undefined as unknown }));++// No router is mounted here; the task-list origin reads the history state.+vi.mock('react-router', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useLocation: () => ({ state: locationMock.state }),+}));+interface MenuItem {key?: string;label?: ReactNode;@@ -154,6 +162,7 @@ const setTaskDetailMap = (map: typeof mocks.taskState.taskDetailMap) =>describe('TaskDetailHeaderActions', () => {beforeEach(() => {vi.clearAllMocks();+ locationMock.state = undefined;mocks.dropdownItems = [];mocks.taskState.activeTaskId = 'T-1';mocks.taskState.taskDetailMap = { 'T-1': { visibility: 'private' } };@@ -347,4 +356,32 @@ describe('TaskDetailHeaderActions', () => {await waitFor(() => expect(mocks.archiveTask).toHaveBeenCalledWith('T-1', true));});++ describe('after deleting the task', () => {+ const deleteAndConfirm = async () => {+ render(<TaskDetailHeaderActions />);+ const item = mocks.dropdownItems.find((i) => i?.key === 'delete') as+ { onClick?: () => void } | undefined;+ item?.onClick?.();+ const opts = mocks.confirmModal.mock.calls[0][0] as { onOk: () => Promise<void> };+ await opts.onOk();+ };++ it('returns to the filtered task list the detail was opened from', async () => {+ // The origin is the list's real URL, so it already carries the workspace prefix.+ locationMock.state = { taskListOrigin: '/ws-slug/tasks?collection=mine' };+ await deleteAndConfirm();++ expect(mocks.deleteTask).toHaveBeenCalledWith('T-1');+ expect(mocks.navigate).toHaveBeenCalledWith('/ws-slug/tasks?collection=mine', {+ escape: true,+ });+ });++ it('returns to the bare task list without a carried origin', async () => {+ await deleteAndConfirm();++ expect(mocks.navigate).toHaveBeenCalledWith('/tasks', { escape: false });+ });+ });});diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsxindex abd12055953..60f40c74244 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.tsx@@ -35,6 +35,7 @@ import { userProfileSelectors } from '@/store/user/selectors';import { getArchiveErrorKey } from '../features/archiveErrorKey';import { useTaskArchiveGate } from '../features/useTaskArchiveGate';+import { useTaskListCrumbTarget } from '../shared/taskListOrigin';import { useTaskCopyActions } from './useTaskCopyActions';import { useTaskFavoriteTarget } from './useTaskFavoriteTarget';@@ -42,6 +43,7 @@ const TaskDetailHeaderActions = memo(() => {const { t } = useTranslation(['chat', 'common']);const navigate = useWorkspaceAwareNavigate();+ const allTasksTarget = useTaskListCrumbTarget('/tasks');const activeWorkspaceId = useActiveWorkspaceId();const { allowed: canEditTask } = usePermission('create_content');const { copyContent, copyId, copyLink, hasContent, taskId } = useTaskCopyActions();@@ -70,11 +72,11 @@ const TaskDetailHeaderActions = memo(() => {okText: t('taskDetail.deleteConfirm.ok'),onOk: async () => {await deleteTask(taskId);- navigate('/tasks');+ navigate(allTasksTarget.to, { escape: allTasksTarget.escape });},title: t('taskDetail.deleteConfirm.title'),});- }, [canEditTask, taskId, t, deleteTask, navigate]);+ }, [canEditTask, taskId, t, deleteTask, navigate, allTasksTarget.to, allTasksTarget.escape]);const toggleArchive = useCallback(async () => {if (!taskId) return;diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsxindex e7e5cb3203e..d5e3517ddcc 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx@@ -3,7 +3,6 @@ import { ActionIcon, Button, Flexbox } from '@lobehub/ui';import { SearchIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { Link } from 'react-router';import NotFound from '@/components/404';import AsyncError from '@/components/AsyncError';@@ -12,6 +11,7 @@ import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';import NavHeader from '@/features/NavHeader';import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';import WideScreenContainer from '@/features/WideScreenContainer';+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useTaskStore } from '@/store/task';@@ -20,6 +20,7 @@ import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/selectors';import Breadcrumb from '../shared/Breadcrumb';+import { useTaskListCrumbTarget } from '../shared/taskListOrigin';import TaskDetailCopyActions from './TaskDetailCopyActions';import TaskDetailHeaderActions from './TaskDetailHeaderActions';import { TASK_DETAIL_PAGE_WIDTH } from './taskDetailLayoutStyles';@@ -45,6 +46,7 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelToconst { isInitialLoading, isNotFound, error, onRetry } = useActiveTaskDetail(taskId);const { bar: findBar, openFind, rootRef: findRootRef } = useTaskFindBar();const findHotkey = useUserStore(settingsSelectors.getHotkeyById(HotkeyEnum.FindInTopic));+ const allTasksTarget = useTaskListCrumbTarget('/tasks');// A transient fetch failure (network / 500) is not a 404 β keep the URL and// offer Reload instead of the terminal "task was deleted" dead-end below.@@ -74,9 +76,9 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId, showTaskAgentPanelTodesc={t('taskDetail.notFound.desc')}title={t('taskDetail.notFound.title')}extra={- <Link to={'/tasks'}>+ <WorkspaceLink escape={allTasksTarget.escape} to={allTasksTarget.to}><Button type={'primary'}>{t('taskDetail.notFound.backToTasks')}</Button>- </Link>+ </WorkspaceLink>}/></Flexbox>diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsxindex 2da60d5d3e2..bb9d834595a 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx@@ -25,7 +25,10 @@ const createState = (parent: any) => ({},});+const locationMock = vi.hoisted(() => ({ state: undefined as unknown }));+vi.mock('react-router', () => ({+ useLocation: () => ({ state: locationMock.state }),useNavigate: () => mocks.navigate,}));@@ -68,6 +71,7 @@ vi.mock('../features/TaskSubtaskProgressTag', () => ({describe('TaskParentBar', () => {beforeEach(() => {+ locationMock.state = undefined;mocks.navigate.mockClear();mocks.getDetail.mockReset();mocks.taskState = createState({@@ -97,7 +101,9 @@ describe('TaskParentBar', () => {fireEvent.click(screen.getByText('Parent task').closest('button')!);- expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_parent/task/T-parent/parent-task');+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_parent/task/T-parent/parent-task', {+ state: undefined,+ });await waitFor(() => expect(mocks.getDetail).toHaveBeenCalledWith('T-parent'));});@@ -123,7 +129,7 @@ describe('TaskParentBar', () => {await waitFor(() => expect(mocks.getDetail).toHaveBeenCalledWith('T-parent'));fireEvent.click(screen.getByText('Parent task').closest('button')!);- expect(mocks.navigate).toHaveBeenCalledWith('/task/T-parent/parent-task');+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-parent/parent-task', { state: undefined });});it("opens parent subtasks inside the clicked subtask's owning agent route", async () => {@@ -149,6 +155,20 @@ describe('TaskParentBar', () => {fireEvent.click(await screen.findByTestId('parent-subtask'));- expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_sibling/task/T-sibling');+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_sibling/task/T-sibling', {+ state: undefined,+ });+ });++ it('keeps carrying the source task list into the parent task', async () => {+ locationMock.state = { taskListOrigin: '/tasks?collection=mine' };+ render(<TaskParentBar />);++ fireEvent.click(screen.getByText('Parent task').closest('button')!);++ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_parent/task/T-parent/parent-task', {+ state: { taskListOrigin: '/tasks?collection=mine' },+ });+ await waitFor(() => expect(mocks.getDetail).toHaveBeenCalledWith('T-parent'));});});diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsxindex aab1b8b02fd..93653384abb 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.tsx@@ -11,6 +11,7 @@ import { taskDetailSelectors } from '@/store/task/selectors';import TaskStatusIcon from '../features/TaskStatusIcon';import TaskSubtaskProgressTag from '../features/TaskSubtaskProgressTag';import { taskDetailPath } from '../shared/taskDetailPath';+import { useTaskListOriginState } from '../shared/taskListOrigin';const TASK_STATUS_SET = new Set(['backlog',@@ -29,6 +30,7 @@ const toTaskStatus = (status?: string): TaskStatus =>const TaskParentBar = memo(() => {const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();+ const taskListOriginState = useTaskListOriginState();const parent = useTaskStore(taskDetailSelectors.activeTaskParent);const currentIdentifier = useTaskStore(taskDetailSelectors.activeTaskDetail)?.identifier;@@ -84,7 +86,9 @@ const TaskParentBar = memo(() => {style={{ maxWidth: '100%', minWidth: 0 }}type={'text'}onClick={() =>- navigate(taskDetailPath(parent.identifier, parentAgentId ?? undefined, parent.name))+ navigate(taskDetailPath(parent.identifier, parentAgentId ?? undefined, parent.name), {+ state: taskListOriginState,+ })}><Text ellipsis style={{ minWidth: 0 }} weight={500}>@@ -97,7 +101,9 @@ const TaskParentBar = memo(() => {currentIdentifier={currentIdentifier}subtasks={parentSubtasks}onSubtaskClick={(identifier, assigneeAgentId, name) =>- navigate(taskDetailPath(identifier, assigneeAgentId, name))+ navigate(taskDetailPath(identifier, assigneeAgentId, name), {+ state: taskListOriginState,+ })}/></span>diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsxindex b4ced35d7a3..d68f438da6f 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx@@ -37,6 +37,8 @@ const mocks = vi.hoisted(() => ({} as any,}));+const locationMock = vi.hoisted(() => ({ state: undefined as unknown }));+vi.mock('@/libs/contextMenu', () => ({showContextMenu: mocks.showContextMenu,}));@@ -104,6 +106,7 @@ vi.mock('antd', async (importOriginal) => ({}));vi.mock('react-router', () => ({+ useLocation: () => ({ state: locationMock.state }),useNavigate: () => mocks.navigate,}));@@ -184,6 +187,7 @@ vi.mock('./TopicStatusIcon', () => ({describe('TaskSubtasks', () => {beforeEach(() => {+ locationMock.state = undefined;mocks.activeWorkspaceId = 'workspace-1';mocks.buildContextMenuItems.mockClear();mocks.installKeyboardHandlers.mockClear();@@ -209,7 +213,9 @@ describe('TaskSubtasks', () => {fireEvent.click(screen.getByTestId('subtask-tree-node'));- expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_child/task/T-child/child-task');+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_child/task/T-child/child-task', {+ state: undefined,+ });});it('routes right-click on a subtask through @/libs/contextMenu', () => {@@ -291,7 +297,7 @@ describe('TaskSubtasks', () => {fireEvent.click(screen.getByTestId('subtask-tree-node'));- expect(mocks.navigate).toHaveBeenCalledWith('/task/T-child/child-task');+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-child/child-task', { state: undefined });});it('uses the running topic status icon when a subtask has an active topic run', () => {@@ -310,4 +316,15 @@ describe('TaskSubtasks', () => {expect(screen.getByTestId('topic-status-icon')).toBeTruthy();});++ it('keeps carrying the source task list into a subtask', () => {+ locationMock.state = { taskListOrigin: '/tasks?collection=mine' };+ render(<TaskSubtasks />);++ fireEvent.click(screen.getByTestId('subtask-tree-node'));++ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_child/task/T-child/child-task', {+ state: { taskListOrigin: '/tasks?collection=mine' },+ });+ });});diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsxindex 1c584283fe7..bd17582f71f 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx@@ -40,6 +40,7 @@ import AccordionArrowIcon from '../shared/AccordionArrowIcon';import { shouldShowMemberAssignee } from '../shared/memberAssigneeMode';import { styles } from '../shared/style';import { taskDetailPath } from '../shared/taskDetailPath';+import { useTaskListOriginState } from '../shared/taskListOrigin';import RunSubtasksPreview from './RunSubtasksPreview';import TopicStatusIcon from './TopicStatusIcon';@@ -178,6 +179,7 @@ const TaskSubtasks = memo(() => {const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();+ const taskListOriginState = useTaskListOriginState();const { allowed: canEditTask, reason } = usePermission('create_content');const agentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);// Subtask composers inherit the parent's visibility as their default β a@@ -212,9 +214,10 @@ const TaskSubtasks = memo(() => {if (!subtask?.id) return;navigate(taskDetailPath(subtask.identifier, subtask?.assignee?.id ?? undefined, subtask?.name),+ { state: taskListOriginState },);},- [navigate, subtaskMap],+ [navigate, subtaskMap, taskListOriginState],);const treeData = useMemo(() => {diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsxindex 1d1826030d1..987d226498b 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx@@ -11,7 +11,7 @@ import {import { Plus } from 'lucide-react';import { memo, type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useSearchParams } from 'react-router';+import { useLocation, useSearchParams } from 'react-router';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';@@ -33,6 +33,7 @@ import { createTaskModal } from '../CreateTaskModal';import { useTaskProjectList } from '../features/useTaskProjectList';import Breadcrumb from '../shared/Breadcrumb';import { taskDetailPath } from '../shared/taskDetailPath';+import { TaskListOriginContext } from '../shared/taskListOrigin';import CreateTaskInlineEntry from './CreateTaskInlineEntry';import EmptyState from './EmptyState';import {@@ -239,6 +240,10 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, projconst { allowed: canCreateTask, reason } = usePermission('create_content');const viewMode = useGlobalStore(systemStatusSelectors.taskListViewMode);const [searchParams, setSearchParams] = useSearchParams();+ // This list's own URL, filters included: task details opened from here carry+ // it so their breadcrumb returns to this exact view.+ const { pathname, search } = useLocation();+ const taskListOrigin = `${pathname}${search}`;const [collectionPage, setCollectionPage] = useState(1);const activeWorkspaceId = useActiveWorkspaceId();// Member assignment is a workspace concept (a task now carries a member@@ -451,10 +456,20 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, projlockAssignee: !!agentId,projectId,onCreated: (task) => {- navigate(taskDetailPath(task.identifier, agentId ? task.agentId : undefined, task.name));+ navigate(taskDetailPath(task.identifier, agentId ? task.agentId : undefined, task.name), {+ state: { taskListOrigin },+ });},});- }, [agentId, canCreateTask, createActionBehavior.mode, navigate, projectId, updateSystemStatus]);+ }, [+ agentId,+ canCreateTask,+ createActionBehavior.mode,+ navigate,+ projectId,+ taskListOrigin,+ updateSystemStatus,+ ]);const handleCreateScheduledTask = useCallback(() => {if (!canCreateTask) return;@@ -466,10 +481,12 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj// The scheduled tab has no inline entry to dock into.showInlineToggle: false,onCreated: (task) => {- navigate(taskDetailPath(task.identifier, agentId ? task.agentId : undefined, task.name));+ navigate(taskDetailPath(task.identifier, agentId ? task.agentId : undefined, task.name), {+ state: { taskListOrigin },+ });},});- }, [agentId, canCreateTask, navigate, projectId]);+ }, [agentId, canCreateTask, navigate, projectId, taskListOrigin]);const handleClearFilter = useCallback(() => setFilter(() => undefined), [setFilter]);const handleFindChange = useCallback(@@ -554,188 +571,190 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj);return (- <Flexbox flex={1} height={'100%'}>- <NavHeader- left={headerLeft}- right={- <Flexbox horizontal align={'center'} gap={4}>- {showFind && <TaskListFind content={filter?.content} onChange={handleFindChange} />}- {(headerVisibility.showViewOptions || hasFilter) && (- <TaskFilterButton fields={filterFields} filter={filter} setFilter={setFilter} />- )}- {isOrdinaryCollection && !agentId && !projectId && <TaskListVisibilityFilter />}- {isOrdinaryCollection && headerActions}- {isOrdinaryCollection && (inlineCollapsed || viewMode === 'kanban') && (- <ActionIcon- disabled={createActionBehavior.disabled}- icon={Plus}- size={DESKTOP_HEADER_ICON_SMALL_SIZE}- title={createActionBehavior.disabled ? reason : undefined}- onClick={handleCreateTask}- />- )}- {isScheduledCollection && !showScheduledEmptyCreate && (- <ActionIcon- disabled={!canCreateTask}- icon={Plus}- size={DESKTOP_HEADER_ICON_SMALL_SIZE}- title={canCreateTask ? t('createTask.submitScheduled') : reason}- onClick={handleCreateScheduledTask}- />- )}- {!isScheduledCollection && headerVisibility.showViewOptions && (- <TasksGroupConfig- canGroupByProject={canGroupByProject}- options={viewOptions}- pinnedOptions={isMineCollection ? PAGINATED_COLLECTION_PINNED_OPTIONS : undefined}- setOptions={setViewOptions}- />- )}- {headerVisibility.showTaskAgentPanelToggle && (- <ToggleRightPanelButton- hideWhenExpanded- expand={showTaskAgentPanel}- onToggle={() => toggleTaskAgentPanel()}- />- )}- </Flexbox>- }- styles={{- left: {- paddingLeft: 4,- gap: 8,- },- }}- />- <TaskFilterBar- fields={filterFields}- filter={filter}- hideContent={showFind}- setFilter={setFilter}- />- {isMineBoard ? (- <Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>- <KanbanBoard- filter={filter}- myTaskScope={myTaskScope}- options={viewOptions}- routeScope={routeScope}- emptyDescription={- filterEmptyDescription ??- t(- myTaskScope === 'created'- ? 'taskList.mine.emptyCreated'- : 'taskList.mine.emptyAssigned',- )- }- />- </Flexbox>- ) : !isOrdinaryCollection ? (- <WideScreenContainer- fullWidth- gap={16}- paddingBlock={16}- paddingInline={16}- wrapperStyle={{ flex: 1, overflowY: 'auto' }}- >- <TaskList- data={isCollectionListInit || undefined}- error={collectionSWR.error ?? projectListError}- filter={filter}- hideProject={!!projectId}- items={collectionTasks}- options={isMineCollection ? myTaskViewOptions : scheduledViewOptions}- routeScope={routeScope}- emptyAction={- filterEmptyAction ??- (showScheduledEmptyCreate ? (- <Button icon={Plus} onClick={handleCreateScheduledTask}>- {t('createTask.submitScheduled')}- </Button>- ) : undefined)- }- emptyDescription={- filterEmptyDescription ??- (isMineCollection- ? t(- myTaskScope === 'created'- ? 'taskList.mine.emptyCreated'- : 'taskList.mine.emptyAssigned',- )- : t('taskList.scheduled.empty'))- }- isLoading={- collectionSWR.isLoading ||- isProjectListPending ||- (!isCollectionListInit && !collectionSWR.error)- }- selectionScope={[- collection,- isMineCollection ? myTaskScope : '',- collectionPage,- agentId ?? '',- projectId ?? '',- ].join(':')}- onRetry={() => (projectListError ? retryProjects() : collectionSWR.mutate())}- />- {(collectionTasksTotal > COLLECTION_PAGE_SIZE || collectionPage > 1) && (- <Flexbox horizontal justify={'center'} paddingBlock={8}>- <Pagination- current={collectionPage}- pageSize={COLLECTION_PAGE_SIZE}- showSizeChanger={false}- total={collectionTasksTotal}- onChange={setCollectionPage}- />+ <TaskListOriginContext value={taskListOrigin}>+ <Flexbox flex={1} height={'100%'}>+ <NavHeader+ left={headerLeft}+ right={+ <Flexbox horizontal align={'center'} gap={4}>+ {showFind && <TaskListFind content={filter?.content} onChange={handleFindChange} />}+ {(headerVisibility.showViewOptions || hasFilter) && (+ <TaskFilterButton fields={filterFields} filter={filter} setFilter={setFilter} />+ )}+ {isOrdinaryCollection && !agentId && !projectId && <TaskListVisibilityFilter />}+ {isOrdinaryCollection && headerActions}+ {isOrdinaryCollection && (inlineCollapsed || viewMode === 'kanban') && (+ <ActionIcon+ disabled={createActionBehavior.disabled}+ icon={Plus}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={createActionBehavior.disabled ? reason : undefined}+ onClick={handleCreateTask}+ />+ )}+ {isScheduledCollection && !showScheduledEmptyCreate && (+ <ActionIcon+ disabled={!canCreateTask}+ icon={Plus}+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}+ title={canCreateTask ? t('createTask.submitScheduled') : reason}+ onClick={handleCreateScheduledTask}+ />+ )}+ {!isScheduledCollection && headerVisibility.showViewOptions && (+ <TasksGroupConfig+ canGroupByProject={canGroupByProject}+ options={viewOptions}+ pinnedOptions={isMineCollection ? PAGINATED_COLLECTION_PINNED_OPTIONS : undefined}+ setOptions={setViewOptions}+ />+ )}+ {headerVisibility.showTaskAgentPanelToggle && (+ <ToggleRightPanelButton+ hideWhenExpanded+ expand={showTaskAgentPanel}+ onToggle={() => toggleTaskAgentPanel()}+ />+ )}</Flexbox>- )}- </WideScreenContainer>- ) : isEmptyHero ? (- <EmptyState agentId={agentId} projectId={projectId} />- ) : isBoardView ? (- <Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>- <KanbanBoard- agentId={agentId}- emptyDescription={filterEmptyDescription}- filter={filter}- options={viewOptions}- projectId={projectId}- routeScope={routeScope}- />- </Flexbox>- ) : (- <WideScreenContainer- fullWidth- gap={16}- paddingBlock={16}- paddingInline={16}- wrapperStyle={{ flex: 1, overflowY: 'auto' }}- >- {!inlineCollapsed && (- <CreateTaskInlineEntry+ }+ styles={{+ left: {+ paddingLeft: 4,+ gap: 8,+ },+ }}+ />+ <TaskFilterBar+ fields={filterFields}+ filter={filter}+ hideContent={showFind}+ setFilter={setFilter}+ />+ {isMineBoard ? (+ <Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>+ <KanbanBoard+ filter={filter}+ myTaskScope={myTaskScope}+ options={viewOptions}+ routeScope={routeScope}+ emptyDescription={+ filterEmptyDescription ??+ t(+ myTaskScope === 'created'+ ? 'taskList.mine.emptyCreated'+ : 'taskList.mine.emptyAssigned',+ )+ }+ />+ </Flexbox>+ ) : !isOrdinaryCollection ? (+ <WideScreenContainer+ fullWidth+ gap={16}+ paddingBlock={16}+ paddingInline={16}+ wrapperStyle={{ flex: 1, overflowY: 'auto' }}+ >+ <TaskList+ data={isCollectionListInit || undefined}+ error={collectionSWR.error ?? projectListError}+ filter={filter}+ hideProject={!!projectId}+ items={collectionTasks}+ options={isMineCollection ? myTaskViewOptions : scheduledViewOptions}+ routeScope={routeScope}+ emptyAction={+ filterEmptyAction ??+ (showScheduledEmptyCreate ? (+ <Button icon={Plus} onClick={handleCreateScheduledTask}>+ {t('createTask.submitScheduled')}+ </Button>+ ) : undefined)+ }+ emptyDescription={+ filterEmptyDescription ??+ (isMineCollection+ ? t(+ myTaskScope === 'created'+ ? 'taskList.mine.emptyCreated'+ : 'taskList.mine.emptyAssigned',+ )+ : t('taskList.scheduled.empty'))+ }+ isLoading={+ collectionSWR.isLoading ||+ isProjectListPending ||+ (!isCollectionListInit && !collectionSWR.error)+ }+ selectionScope={[+ collection,+ isMineCollection ? myTaskScope : '',+ collectionPage,+ agentId ?? '',+ projectId ?? '',+ ].join(':')}+ onRetry={() => (projectListError ? retryProjects() : collectionSWR.mutate())}+ />+ {(collectionTasksTotal > COLLECTION_PAGE_SIZE || collectionPage > 1) && (+ <Flexbox horizontal justify={'center'} paddingBlock={8}>+ <Pagination+ current={collectionPage}+ pageSize={COLLECTION_PAGE_SIZE}+ showSizeChanger={false}+ total={collectionTasksTotal}+ onChange={setCollectionPage}+ />+ </Flexbox>+ )}+ </WideScreenContainer>+ ) : isEmptyHero ? (+ <EmptyState agentId={agentId} projectId={projectId} />+ ) : isBoardView ? (+ <Flexbox flex={1} style={{ overflowX: 'auto', overflowY: 'hidden' }}>+ <KanbanBoardagentId={agentId}- lockAssignee={!!agentId}+ emptyDescription={filterEmptyDescription}+ filter={filter}+ options={viewOptions}projectId={projectId}+ routeScope={routeScope}/>- )}- <TaskList- createScope={groupCreateScope}- data={isTaskListInit || undefined}- emptyAction={filterEmptyAction}- emptyDescription={filterEmptyDescription}- error={error ?? projectListError}- filter={filter}- hideProject={!!projectId}- isLoading={isLoading || isProjectListPending || (!isTaskListInit && !error)}- options={viewOptions}- queryKey={queryKey}- routeScope={routeScope}- onRetry={() => (projectListError ? retryProjects() : mutate())}- onShowHiddenCompleted={handleShowHiddenCompleted}- />- </WideScreenContainer>- )}- </Flexbox>+ </Flexbox>+ ) : (+ <WideScreenContainer+ fullWidth+ gap={16}+ paddingBlock={16}+ paddingInline={16}+ wrapperStyle={{ flex: 1, overflowY: 'auto' }}+ >+ {!inlineCollapsed && (+ <CreateTaskInlineEntry+ agentId={agentId}+ lockAssignee={!!agentId}+ projectId={projectId}+ />+ )}+ <TaskList+ createScope={groupCreateScope}+ data={isTaskListInit || undefined}+ emptyAction={filterEmptyAction}+ emptyDescription={filterEmptyDescription}+ error={error ?? projectListError}+ filter={filter}+ hideProject={!!projectId}+ isLoading={isLoading || isProjectListPending || (!isTaskListInit && !error)}+ options={viewOptions}+ queryKey={queryKey}+ routeScope={routeScope}+ onRetry={() => (projectListError ? retryProjects() : mutate())}+ onShowHiddenCompleted={handleShowHiddenCompleted}+ />+ </WideScreenContainer>+ )}+ </Flexbox>+ </TaskListOriginContext>);});diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.project.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.project.test.tsxindex e01921975c7..fa6564a1299 100644--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.project.test.tsx+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.project.test.tsx@@ -7,6 +7,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import CreateTaskInlineEntry from './CreateTaskInlineEntry';+const locationMock = vi.hoisted(() => ({ state: undefined as unknown }));++// No router is mounted here; the task-list origin reads the history state.+vi.mock('react-router', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useLocation: () => ({ state: locationMock.state }),+}));+const state = vi.hoisted(() => ({createTask: vi.fn(async () => ({ id: 't1', identifier: 'T-1' })),markdown: 'Ship it',diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsxindex 1a3e77f11c9..c4dda2025c6 100644--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx@@ -5,8 +5,17 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type { CSSProperties, ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { TaskListOriginContext } from '../shared/taskListOrigin';import CreateTaskInlineEntry from './CreateTaskInlineEntry';+const locationMock = vi.hoisted(() => ({ state: undefined as unknown }));++// No router is mounted here; the task-list origin reads the history state.+vi.mock('react-router', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useLocation: () => ({ state: locationMock.state }),+}));+const permissionMock = vi.hoisted(() => ({allowed: true,}));@@ -314,6 +323,7 @@ describe('CreateTaskInlineEntry', () => {title: 'Write the Q3 project plan',});navigateMock.mockReset();+ locationMock.state = undefined;toastSuccessMock.mockReset();createGoalModalMock.mockReset();activeWorkspaceMock.id = 'workspace-1';@@ -673,7 +683,35 @@ describe('CreateTaskInlineEntry', () => {render(description as ReactNode);fireEvent.click(screen.getByText('taskIntent.openCreated'));- expect(navigateMock).toHaveBeenCalledWith(expect.stringContaining('/task/TASK-9/'));+ expect(navigateMock).toHaveBeenCalledWith(expect.stringContaining('/task/TASK-9/'), {+ state: undefined,+ });+ });++ it('opens the created task with the list it was created from as its origin', async () => {+ editorMarkdownMock.value = 'Write a project plan';+ analyzeIntentMock.mockResolvedValue(clearReading);+ createTaskMock.mockResolvedValue({+ id: 'task_9',+ identifier: 'TASK-9',+ name: 'Write the Q3 project plan',+ });++ render(+ <TaskListOriginContext value={'/tasks?collection=mine'}>+ <CreateTaskInlineEntry variant="hero" />+ </TaskListOriginContext>,+ );+ fireEvent.keyDown(screen.getByTestId('task-editor'), { key: 'Enter', metaKey: true });+ await waitFor(() => expect(toastSuccessMock).toHaveBeenCalledTimes(1));++ // The toast renders outside the list, so the origin rides in the closure.+ const { description } = toastSuccessMock.mock.calls[0][0];+ render(description as ReactNode);+ fireEvent.click(screen.getByText('taskIntent.openCreated'));+ expect(navigateMock).toHaveBeenCalledWith(expect.stringContaining('/task/TASK-9/'), {+ state: { taskListOrigin: '/tasks?collection=mine' },+ });});it('confirms every creation path, not only the straight-through one', async () => {diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsxindex b1c7395a979..606a08aa3e8 100644--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.tsx@@ -53,6 +53,7 @@ import { UnassignedAssigneeIcon } from '../features/UnassignedAssigneeIcon';import { useTaskProjectChoice } from '../features/useTaskProjectChoice';import { resolveMemberAssignee } from '../shared/memberAssigneeMode';import { taskDetailPath } from '../shared/taskDetailPath';+import { useTaskListOriginState } from '../shared/taskListOrigin';import { useAgentDisplayMeta } from '../shared/useAgentDisplayMeta';import { useAgentVisibility } from '../shared/useAgentVisibility';import { useDefaultMemberAssignee } from '../shared/useDefaultMemberAssignee';@@ -124,6 +125,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {const { assignableMemberIds, defaultMemberAssignee, isDefaultMemberPending, isMembersLoading } =useDefaultMemberAssignee();const navigate = useWorkspaceAwareNavigate();+ const taskListOriginState = useTaskListOriginState();const [priority, setPriority] = useState(0);const [labels, setLabels] = useState<TaskLabelRef[]>([]);const isLabelsInit = useTaskStore(taskLabelSelectors.isLabelsInit);@@ -516,6 +518,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {result.assigneeAgentId ?? undefined,result.name || draft.name,),+ { state: taskListOriginState },)}>@@ -558,6 +561,7 @@ const CreateTaskInlineEntry = memo<CreateTaskInlineEntryProps>((props) => {onCreated,parentTaskId,priority,+ taskListOriginState,resetComposer,visibility,],diff --git a/src/features/AgentTasks/features/AgentTaskItem.test.tsx b/src/features/AgentTasks/features/AgentTaskItem.test.tsxindex e890dcf73ac..cd9c6b843ae 100644--- a/src/features/AgentTasks/features/AgentTaskItem.test.tsx+++ b/src/features/AgentTasks/features/AgentTaskItem.test.tsx@@ -5,6 +5,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/reimport type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { TaskListOriginContext } from '../shared/taskListOrigin';import AgentTaskItem from './AgentTaskItem';const mocks = vi.hoisted(() => ({@@ -17,6 +18,8 @@ const mocks = vi.hoisted(() => ({taskDetailMap: {} as Record<string, unknown>,}));+const locationMock = vi.hoisted(() => ({ state: undefined as unknown }));+vi.mock('react-i18next', () => ({useTranslation: () => ({i18n: { language: 'en-US' },@@ -25,6 +28,7 @@ vi.mock('react-i18next', () => ({}));vi.mock('react-router', () => ({+ useLocation: () => ({ state: locationMock.state }),useNavigate: () => mocks.navigate,}));@@ -165,6 +169,7 @@ const createTask = (assigneeAgentId?: string | null) =>describe('AgentTaskItem', () => {beforeEach(() => {+ locationMock.state = undefined;mocks.activeWorkspaceId = 'workspace-1';mocks.memberDirectory = [];mocks.fetchTaskDetail.mockReset();@@ -183,7 +188,9 @@ describe('AgentTaskItem', () => {fireEvent.click(screen.getByText('Hourly trend update'));- expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_owner/task/T-22/hourly-trend-update');+ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_owner/task/T-22/hourly-trend-update', {+ state: undefined,+ });});it('opens an assigned task on the global detail route in global scope', () => {@@ -191,7 +198,9 @@ describe('AgentTaskItem', () => {fireEvent.click(screen.getByText('Hourly trend update'));- expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22/hourly-trend-update');+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22/hourly-trend-update', {+ state: undefined,+ });});it('falls back to the global task detail route when the task has no assignee', () => {@@ -199,7 +208,9 @@ describe('AgentTaskItem', () => {fireEvent.click(screen.getByText('Hourly trend update'));- expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22/hourly-trend-update');+ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22/hourly-trend-update', {+ state: undefined,+ });});describe('project badge', () => {@@ -373,4 +384,30 @@ describe('AgentTaskItem', () => {await waitFor(() => expect(mocks.fetchTaskDetail).toHaveBeenCalledWith('task_22'));});++ it('carries the list it was opened from into the task detail', () => {+ locationMock.state = { taskListOrigin: '/tasks?collection=mine' };+ render(<AgentTaskItem routeScope="global" task={createTask('agt_owner')} />);++ fireEvent.click(screen.getByText('Hourly trend update'));++ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22/hourly-trend-update', {+ state: { taskListOrigin: '/tasks?collection=mine' },+ });+ });++ it('prefers the surrounding task list URL over a carried origin', () => {+ locationMock.state = { taskListOrigin: '/tasks?collection=mine' };+ render(+ <TaskListOriginContext value={'/agent/agt_owner/tasks?scope=created'}>+ <AgentTaskItem task={createTask('agt_owner')} />+ </TaskListOriginContext>,+ );++ fireEvent.click(screen.getByText('Hourly trend update'));++ expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_owner/task/T-22/hourly-trend-update', {+ state: { taskListOrigin: '/agent/agt_owner/tasks?scope=created' },+ });+ });});diff --git a/src/features/AgentTasks/features/AgentTaskItem.tsx b/src/features/AgentTasks/features/AgentTaskItem.tsxindex 8fc2e2cb557..72fc247f00f 100644--- a/src/features/AgentTasks/features/AgentTaskItem.tsx+++ b/src/features/AgentTasks/features/AgentTaskItem.tsx@@ -12,6 +12,7 @@ import type { TaskListItem } from '@/store/task/slices/list/initialState';import { shouldShowMemberAssignee } from '../shared/memberAssigneeMode';import { taskDetailPath } from '../shared/taskDetailPath';+import { useTaskListOriginState } from '../shared/taskListOrigin';import AssigneeAgentSelector from './AssigneeAgentSelector';import AssigneeAvatar from './AssigneeAvatar';import AssigneeMemberSelector from './AssigneeMemberSelector';@@ -63,6 +64,7 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {routeScope,);const navigate = useWorkspaceAwareNavigate();+ const taskListOriginState = useTaskListOriginState();const activeWorkspaceId = useActiveWorkspaceId();const time = formatTaskItemDate(task.updatedAt || task.createdAt, {@@ -80,8 +82,9 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {routeScope === 'agent' ? (task.assigneeAgentId ?? undefined) : undefined,task.name,),+ { state: taskListOriginState },);- }, [navigate, routeScope, task.assigneeAgentId, task.identifier, task.name]);+ }, [navigate, routeScope, task.assigneeAgentId, task.identifier, task.name, taskListOriginState]);const handleRequestSubtasks = useCallback(async () => {const detail = await fetchTaskDetail(task.id);@@ -92,9 +95,10 @@ const AgentTaskItem = memo<TaskItemProps>((props) => {(identifier: string, assigneeAgentId?: string, name?: string) => {navigate(taskDetailPath(identifier, routeScope === 'agent' ? assigneeAgentId : undefined, name),+ { state: taskListOriginState },);},- [navigate, routeScope],+ [navigate, routeScope, taskListOriginState],);const scheduledBadge =diff --git a/src/features/AgentTasks/shared/Breadcrumb.test.tsx b/src/features/AgentTasks/shared/Breadcrumb.test.tsxindex 59ed556b205..047704b70b5 100644--- a/src/features/AgentTasks/shared/Breadcrumb.test.tsx+++ b/src/features/AgentTasks/shared/Breadcrumb.test.tsx@@ -3,11 +3,14 @@*/import { cleanup, render, screen } from '@testing-library/react';import type { ReactNode } from 'react';+import { MemoryRouter } from 'react-router';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import Breadcrumb from './Breadcrumb';const mocks = vi.hoisted(() => ({+ agentMeta: undefined as any,+ params: {} as { aid?: string },taskState: {} as any,}));@@ -15,9 +18,9 @@ const createState = (taskDetailMap: Record<string, any>) => ({taskDetailMap,});-vi.mock('react-router', () => ({- Link: ({ children, to }: { children: ReactNode; to: string }) => <a href={to}>{children}</a>,- useParams: () => ({}),+vi.mock('react-router', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useParams: () => mocks.params,}));// Render the workspace-aware link as a plain anchor so the asserted hrefs stay@@ -26,9 +29,8 @@ vi.mock('@/features/Workspace/WorkspaceLink', () => ({default: ({ children, to }: { children: ReactNode; to: string }) => <a href={to}>{children}</a>,}));-// Agent crumb metadata isn't under test here; the agent store isn't mocked.vi.mock('./useAgentDisplayMeta', () => ({- useAgentDisplayMeta: () => undefined,+ useAgentDisplayMeta: () => mocks.agentMeta,}));vi.mock('zustand/react/shallow', () => ({@@ -43,8 +45,13 @@ vi.mock('./style', () => ({styles: { breadcrumb: 'breadcrumb' },}));+const renderAt = (ui: ReactNode, state?: unknown) =>+ render(<MemoryRouter initialEntries={[{ pathname: '/task/T-child', state }]}>{ui}</MemoryRouter>);+describe('Breadcrumb', () => {beforeEach(() => {+ mocks.agentMeta = undefined;+ mocks.params = {};mocks.taskState = createState({'T-child': {id: 'T-child',@@ -77,21 +84,21 @@ describe('Breadcrumb', () => {});it('keeps the all-tasks root crumb on desktop', () => {- render(<Breadcrumb taskId="T-child" />);+ renderAt(<Breadcrumb taskId="T-child" />);expect(screen.getByRole('link', { name: 'taskList.all' })).toHaveAttribute('href', '/tasks');});it('drops the all-tasks root crumb on mobile, where the back button leads up', () => {vi.stubGlobal('__MOBILE__', true);- render(<Breadcrumb taskId="T-child" />);+ renderAt(<Breadcrumb taskId="T-child" />);expect(screen.queryByText('taskList.all')).not.toBeInTheDocument();expect(screen.getByRole('link', { name: 'T-parent' })).toBeInTheDocument();});it('uses the ancestor owner agent when building breadcrumb links', () => {- render(<Breadcrumb taskId="T-child" />);+ renderAt(<Breadcrumb taskId="T-child" />);expect(screen.getByRole('link', { name: 'T-parent' })).toHaveAttribute('href',@@ -115,11 +122,42 @@ describe('Breadcrumb', () => {},});- render(<Breadcrumb taskId="T-child" />);+ renderAt(<Breadcrumb taskId="T-child" />);expect(screen.getByRole('link', { name: 'T-parent' })).toHaveAttribute('href','/task/T-parent/parent-task',);});++ describe('returning to the source task list', () => {+ it('leads the all-tasks crumb back to the filtered list the detail was opened from', () => {+ renderAt(<Breadcrumb taskId="T-child" />, { taskListOrigin: '/tasks?collection=mine' });++ expect(screen.getByRole('link', { name: 'taskList.all' })).toHaveAttribute(+ 'href',+ '/tasks?collection=mine',+ );+ });++ it('falls back to the bare list without a carried origin', () => {+ renderAt(<Breadcrumb taskId="T-child" />);++ expect(screen.getByRole('link', { name: 'taskList.all' })).toHaveAttribute('href', '/tasks');+ });++ it('keeps the agent list filters on the agent crumb only', () => {+ mocks.params = { aid: 'a1' };+ mocks.agentMeta = { backgroundColor: '', title: 'Agent One' };+ renderAt(<Breadcrumb taskId="T-child" />, {+ taskListOrigin: '/agent/a1/tasks?collection=mine&scope=created',+ });++ expect(screen.getByRole('link', { name: 'taskList.all' })).toHaveAttribute('href', '/tasks');+ expect(screen.getByRole('link', { name: 'Agent One' })).toHaveAttribute(+ 'href',+ '/agent/a1/tasks?collection=mine&scope=created',+ );+ });+ });});diff --git a/src/features/AgentTasks/shared/Breadcrumb.tsx b/src/features/AgentTasks/shared/Breadcrumb.tsxindex 347f635e6af..79051bf237f 100644--- a/src/features/AgentTasks/shared/Breadcrumb.tsx+++ b/src/features/AgentTasks/shared/Breadcrumb.tsx@@ -12,6 +12,7 @@ import { isMobileSurface } from '@/utils/mobileSurface';import { styles } from './style';import { taskDetailPath } from './taskDetailPath';+import { useTaskListCrumbTarget, useTaskListOriginState } from './taskListOrigin';import { useAgentDisplayMeta } from './useAgentDisplayMeta';interface BreadcrumbProps {@@ -22,6 +23,11 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {const { t } = useTranslation('chat');const { aid } = useParams<{ aid?: string }>();const agentMeta = useAgentDisplayMeta(aid);+ // Crumbs lead back to the list the detail was opened from, filters included,+ // when that list is the crumb's own list; otherwise to the bare list.+ const allTasksTarget = useTaskListCrumbTarget('/tasks');+ const agentTasksTarget = useTaskListCrumbTarget(aid ? `/agent/${aid}/tasks` : '/tasks');+ const taskListOriginState = useTaskListOriginState();const taskTitle = useTaskStore((s) =>taskId ? s.taskDetailMap[s.taskRefIndex?.[taskId] ?? taskId]?.name : undefined,);@@ -84,14 +90,21 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {agentCrumb && taskId? {...agentCrumb,- title: <WorkspaceLink to={`/agent/${aid}/tasks`}>{agentCrumb.title}</WorkspaceLink>,+ title: (+ <WorkspaceLink escape={agentTasksTarget.escape} to={agentTasksTarget.to}>+ {agentCrumb.title}+ </WorkspaceLink>+ ),}: agentCrumb;const ancestorCrumbs = ancestors.map(({ id, identifier, agentId, name }) => ({key: id,title: (- <WorkspaceLink to={taskDetailPath(identifier, agentId ?? undefined, name)}>+ <WorkspaceLink+ state={taskListOriginState}+ to={taskDetailPath(identifier, agentId ?? undefined, name)}+ ><Text color={'inherit'} weight={500}>{identifier}</Text>@@ -149,7 +162,9 @@ const Breadcrumb = memo<BreadcrumbProps>(({ taskId }) => {{title:taskId || agentCrumbNode ? (- <WorkspaceLink to={'/tasks'}>{allTasksLabel}</WorkspaceLink>+ <WorkspaceLink escape={allTasksTarget.escape} to={allTasksTarget.to}>+ {allTasksLabel}+ </WorkspaceLink>) : (allTasksLabel),diff --git a/src/features/AgentTasks/shared/taskListOrigin.test.ts b/src/features/AgentTasks/shared/taskListOrigin.test.tsnew file mode 100644index 00000000000..63727781744--- /dev/null+++ b/src/features/AgentTasks/shared/taskListOrigin.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';++import { resolveTaskListCrumbTarget } from './taskListOrigin';++describe('resolveTaskListCrumbTarget', () => {+ it('returns the origin, filters included, when it is the crumb list', () => {+ expect(resolveTaskListCrumbTarget('/tasks?collection=mine', '/tasks', null)).toBe(+ '/tasks?collection=mine',+ );+ });++ it('returns the bare list when the origin is another list', () => {+ expect(resolveTaskListCrumbTarget('/agent/a1/tasks?collection=mine', '/tasks', null)).toBe(+ '/tasks',+ );+ expect(resolveTaskListCrumbTarget('/tasks?collection=mine', '/agent/a1/tasks', null)).toBe(+ '/agent/a1/tasks',+ );+ });++ it('returns the bare list without an origin', () => {+ expect(resolveTaskListCrumbTarget(undefined, '/tasks', null)).toBe('/tasks');+ });++ it('matches the workspace-prefixed list path', () => {+ expect(resolveTaskListCrumbTarget('/acme/tasks?collection=mine', '/tasks', 'acme')).toBe(+ '/acme/tasks?collection=mine',+ );+ expect(+ resolveTaskListCrumbTarget('/acme/agent/a1/tasks?scope=created', '/agent/a1/tasks', 'acme'),+ ).toBe('/acme/agent/a1/tasks?scope=created');+ });++ it('ignores an origin from another workspace', () => {+ expect(resolveTaskListCrumbTarget('/other/tasks?collection=mine', '/tasks', 'acme')).toBe(+ '/tasks',+ );+ expect(resolveTaskListCrumbTarget('/acme/tasks?collection=mine', '/tasks', null)).toBe(+ '/tasks',+ );+ });++ it('does not treat a longer path as the list', () => {+ expect(resolveTaskListCrumbTarget('/tasks/archive?x=1', '/tasks', null)).toBe('/tasks');+ });++ it('never leads off the app, whatever the history state holds', () => {+ for (const origin of [+ '//evil.example/tasks?collection=mine',+ '/\\evil.example/tasks',+ 'https://evil.example/tasks',+ 'javascript:alert(1)//tasks',+ '/tasks/../\\evil.example/tasks',+ ]) {+ expect(resolveTaskListCrumbTarget(origin, '/tasks', null)).toBe('/tasks');+ }+ });++ it('keeps the hash along with the filters', () => {+ expect(resolveTaskListCrumbTarget('/tasks?collection=mine#top', '/tasks', null)).toBe(+ '/tasks?collection=mine#top',+ );+ });+});diff --git a/src/features/AgentTasks/shared/taskListOrigin.ts b/src/features/AgentTasks/shared/taskListOrigin.tsnew file mode 100644index 00000000000..50ece98e079--- /dev/null+++ b/src/features/AgentTasks/shared/taskListOrigin.ts@@ -0,0 +1,86 @@+import { createContext, useContext, useMemo } from 'react';+import { useLocation } from 'react-router';++import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';++/**+ * The task list a task detail was opened from, as the full in-app URL of that+ * list (`pathname + search`, workspace prefix included, e.g.+ * `/lobehub/tasks?collection=mine`). It rides on the history entry's+ * `location.state`, so the breadcrumb can return to the filtered list instead+ * of the bare `/tasks`. Entries opened from anywhere else (home, command menu,+ * chat, deep links, new tabs) carry no origin and fall back to the plain list.+ */+export interface TaskListOriginState {+ taskListOrigin: string;+}++/** Provided by the task list page with its own current URL. */+export const TaskListOriginContext = createContext<string | undefined>(undefined);++const readOriginFromState = (state: unknown): string | undefined => {+ if (!state || typeof state !== 'object') return undefined;+ const origin = (state as Partial<TaskListOriginState>).taskListOrigin;+ return typeof origin === 'string' ? origin : undefined;+};++/** The source list URL: the list page's own URL inside a list, else the one carried in history. */+export const useTaskListOrigin = (): string | undefined => {+ const contextOrigin = useContext(TaskListOriginContext);+ const location = useLocation();+ return contextOrigin ?? readOriginFromState(location.state);+};++/**+ * Navigation state to attach when opening a task detail, so the origin follows+ * the user from the list into the detail and on to related details.+ */+export const useTaskListOriginState = (): TaskListOriginState | undefined => {+ const origin = useTaskListOrigin();+ return useMemo(() => (origin ? { taskListOrigin: origin } : undefined), [origin]);+};++// A fixed base only for parsing: the origin is an in-app path, never a full URL.+const PARSE_BASE = 'https://task-list-origin.invalid';++/**+ * Where a crumb for `listPath` should lead: the carried origin when it is that+ * very list (so its filters survive), otherwise the bare `listPath`.+ *+ * History state is page-writable, so the origin is parsed rather than prefix+ * matched: anything that resolves off the parse base (`//host/β¦`, `/\host/β¦`,+ * `https://β¦`) or to another path falls back, and the returned target is+ * rebuilt from the parsed path, query and hash only.+ */+export const resolveTaskListCrumbTarget = (+ origin: string | undefined,+ listPath: string,+ slug: string | null | undefined,+): string => {+ if (!origin?.startsWith('/')) return listPath;++ let parsed: URL;+ try {+ parsed = new URL(origin, PARSE_BASE);+ } catch {+ return listPath;+ }+ if (parsed.origin !== PARSE_BASE) return listPath;+ if (parsed.pathname !== buildWorkspaceAwarePath(listPath, slug)) return listPath;++ return `${parsed.pathname}${parsed.search}${parsed.hash}`;+};++export interface TaskListCrumbTarget {+ /** Already workspace-prefixed: pass to `WorkspaceLink` / `navigate` with `escape`. */+ escape: boolean;+ to: string;+}++export const useTaskListCrumbTarget = (listPath: string): TaskListCrumbTarget => {+ const origin = useTaskListOrigin();+ const slug = useActiveWorkspaceSlug();+ const to = resolveTaskListCrumbTarget(origin, listPath, slug);+ return { escape: to !== listPath, to };+};diff --git a/src/features/AgentTasks/shared/useCanonicalTaskSlug.test.ts b/src/features/AgentTasks/shared/useCanonicalTaskSlug.test.tsindex ac95a791f48..88ac354d2a4 100644--- a/src/features/AgentTasks/shared/useCanonicalTaskSlug.test.ts+++ b/src/features/AgentTasks/shared/useCanonicalTaskSlug.test.ts@@ -9,7 +9,7 @@ import { useTaskStore } from '@/store/task';import { useCanonicalTaskSlug } from './useCanonicalTaskSlug';const mocks = vi.hoisted(() => ({- location: { hash: '', search: '' } as { hash: string; search: string },+ location: { hash: '', search: '' } as { hash: string; search: string; state?: unknown },navigate: vi.fn(),params: {} as { aid?: string; slug?: string; workspaceSlug?: string },}));@@ -76,6 +76,23 @@ describe('useCanonicalTaskSlug', () => {);});+ it('keeps the history state, so the task list origin survives a slug repair', () => {+ mocks.params = { slug: 'old-title' };+ mocks.location = {+ hash: '',+ search: '',+ state: { taskListOrigin: '/tasks?collection=mine' },+ };+ setTaskName('Ship the Thing');++ renderHook(() => useCanonicalTaskSlug('T-1'));++ expect(mocks.navigate).toHaveBeenCalledWith('/task/T-1/ship-the-thing', {+ replace: true,+ state: { taskListOrigin: '/tasks?collection=mine' },+ });+ });+it('preserves the query string and hash', () => {mocks.location = { hash: '#activity', search: '?tab=runs' };setTaskName('Ship the Thing');diff --git a/src/features/AgentTasks/shared/useCanonicalTaskSlug.ts b/src/features/AgentTasks/shared/useCanonicalTaskSlug.tsindex 56e529e5fca..97977aa4494 100644--- a/src/features/AgentTasks/shared/useCanonicalTaskSlug.ts+++ b/src/features/AgentTasks/shared/useCanonicalTaskSlug.ts@@ -24,14 +24,15 @@ type CanonicalTaskSlugParams = {* pasted the link. Identifier and stable-id URLs both keep their reference.* A cached display alias must never redirect a stable-id URL to another task.* The slug is cosmetic, so this never gates rendering or re-fetches; `replace` keeps the- * correction out of the back stack.+ * correction out of the back stack, and the entry's history state (such as the+ * task list it was opened from) rides along so the breadcrumb still leads back there.** Only route components may call this: the same detail body also renders inside* the chat Portal, which must not rewrite the address bar.*/export const useCanonicalTaskSlug = (taskId?: string) => {const { aid, slug, workspaceSlug } = useActiveRouteParams<CanonicalTaskSlugParams>();- const { hash, search } = useLocation();+ const { hash, search, state } = useLocation();const navigate = useWorkspaceAwareNavigate();// Loaded-ness and the title are read separately: an empty title is a real,// resolved state (clearing the input persists `name: ''`), and folding it in@@ -60,6 +61,7 @@ export const useCanonicalTaskSlug = (taskId?: string) => {navigate(canonicalTaskPath({ taskRef: taskId, aid, title, workspaceSlug, search, hash }), {escape: true,replace: true,+ state,});- }, [aid, hash, isLoaded, navigate, search, slug, taskId, title, workspaceSlug]);+ }, [aid, hash, isLoaded, navigate, search, slug, state, taskId, title, workspaceSlug]);};