π€― 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
β»οΈ refactor(task): move sidebar groups, scheduled and My tasks onto the task replica (#20868)
Arvin Xucb32462eca71
diff --git a/src/features/AgentSidebar/Task/index.tsx b/src/features/AgentSidebar/Task/index.tsxindex e0efd224603..6df7aebaeee 100644--- a/src/features/AgentSidebar/Task/index.tsx+++ b/src/features/AgentSidebar/Task/index.tsx@@ -18,20 +18,10 @@ import { useTranslation } from 'react-i18next';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useClientDataSWR } from '@/libs/swr';-import { taskKeys } from '@/libs/swr/keys';-import { taskService } from '@/services/task';import { useAgentStore } from '@/store/agent';-import type { TaskGroupItem } from '@/store/task/slices/list/initialState';import StatusGroup from './StatusGroup';--const SIDEBAR_GROUPS = [- { key: 'needsInput', statuses: ['paused', 'failed'] },- { key: 'backlog', statuses: ['backlog'] },- { key: 'running', statuses: ['running', 'scheduled'] },-];-const STATUS_ORDER = SIDEBAR_GROUPS.map((g) => g.key);+import { useSidebarTaskGroups } from './useSidebarTaskGroups';interface TaskListProps {itemKey: string;@@ -42,24 +32,7 @@ const TaskList = memo<TaskListProps>(({ itemKey }) => {const navigate = useWorkspaceAwareNavigate();const agentId = useAgentStore((s) => s.activeAgentId);- const enabled = !!agentId;- const { data, isLoading } = useClientDataSWR<{ data: TaskGroupItem[]; success: boolean }>(- enabled ? taskKeys.sidebarGroups(agentId) : null,- async ([, id]: [string, string]) =>- taskService.groupList({ assigneeAgentId: id, groups: SIDEBAR_GROUPS }),- {- fallbackData: { data: [], success: true },- revalidateOnFocus: false,- },- );- const taskGroups = useMemo(() => data?.data ?? [], [data?.data]);-- const orderedGroups = useMemo(() => {- const map = new Map(taskGroups.map((g) => [g.key, g]));- return STATUS_ORDER.map((key) => map.get(key)).filter(- (g): g is NonNullable<typeof g> => !!g && g.tasks.length > 0,- );- }, [taskGroups]);+ const { groups: orderedGroups, isLoading } = useSidebarTaskGroups(agentId);const totalTasks = useMemo(() => orderedGroups.reduce((acc, g) => acc + g.tasks.length, 0),@@ -110,7 +83,7 @@ const TaskList = memo<TaskListProps>(({ itemKey }) => {</AccordionHeader>);- if (isLoading && taskGroups.length === 0) {+ if (isLoading && orderedGroups.length === 0) {return (<AccordionItem value={itemKey}>{header}diff --git a/src/features/AgentSidebar/Task/useSidebarTaskGroups.test.ts b/src/features/AgentSidebar/Task/useSidebarTaskGroups.test.tsnew file mode 100644index 00000000000..1ae68ddfcbe--- /dev/null+++ b/src/features/AgentSidebar/Task/useSidebarTaskGroups.test.ts@@ -0,0 +1,91 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createReplicaState } from '@/libs/replica';+import { useTaskStore } from '@/store/task';+import { taskGroupListQueryKey } from '@/store/task/slices/list/projection';++import { useSidebarTaskGroups } from './useSidebarTaskGroups';++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ isValidating: true, mutate: vi.fn() })),+}));++vi.mock('@/services/task', () => ({+ taskService: { groupList: vi.fn(), list: vi.fn() },+}));++const sidebarQueryKey = taskGroupListQueryKey({+ agentId: 'agt_1',+ excludeStatuses: ['canceled', 'completed'],+ groupBy: 'status',+ visibility: 'all',+});++beforeEach(() => {+ vi.clearAllMocks();+ useTaskStore.setState({+ // A leftover Tasks-page chip must not narrow the panel.+ listVisibility: 'private',+ taskGroupListMap: {},+ taskGroupListReplica: createReplicaState(),+ });+});++describe('useSidebarTaskGroups', () => {+ // Regression: the panel read an SWR-persisted `task:sidebarGroups` key, so a+ // reload showed the skeleton until the whole SWR cache hydrated. It now reads+ // the agent's task-group replica entry, which paints while the refresh runs.+ it('paints the stored groups in panel order while the refresh is in flight', () => {+ const { result } = renderHook(() => useSidebarTaskGroups('agt_1'));+ expect(result.current).toEqual({ groups: [], isLoading: true });++ act(() => {+ useTaskStore.setState({+ taskGroupListMap: {+ [sidebarQueryKey]: {+ excludeStatuses: ['canceled', 'completed'],+ groupBy: 'status',+ groups: [+ { key: 'running', tasks: [{ name: 'Nightly sync' }], total: 1 },+ { key: 'backlog', tasks: [], total: 0 },+ { key: 'needsInput', tasks: [{ name: 'Answer me' }], total: 1 },+ { key: 'done', tasks: [], total: 0 },+ ] as any,+ },+ },+ });+ });++ expect(result.current.groups.map((group) => group.key)).toEqual(['needsInput', 'running']);+ });++ it('syncs the agent board without finished columns, ignoring the visibility chip', async () => {+ const { useClientDataSWR } = await import('@/libs/swr');+ const { taskService } = await import('@/services/task');++ renderHook(() => useSidebarTaskGroups('agt_1'));++ const calls = vi.mocked(useClientDataSWR).mock.calls;+ expect(calls.some(([key]) => Array.isArray(key) && key[0] === 'task:sidebarGroups')).toBe(+ false,+ );+ const [, fetcher] = calls.find(+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === 'taskGroupList',+ )!;+ await (fetcher as () => Promise<unknown>)();+ expect(taskService.groupList).toHaveBeenCalledWith(+ expect.objectContaining({+ assigneeAgentId: 'agt_1',+ excludeStatuses: ['canceled', 'completed'],+ visibility: undefined,+ }),+ );+ });++ it('fetches nothing without an active agent', async () => {+ const { result } = renderHook(() => useSidebarTaskGroups(undefined));+ expect(result.current.groups).toEqual([]);+ });+});diff --git a/src/features/AgentSidebar/Task/useSidebarTaskGroups.ts b/src/features/AgentSidebar/Task/useSidebarTaskGroups.tsnew file mode 100644index 00000000000..a94f9a4057c--- /dev/null+++ b/src/features/AgentSidebar/Task/useSidebarTaskGroups.ts@@ -0,0 +1,33 @@+import { useMemo } from 'react';++import { useTaskStore } from '@/store/task';+import { taskListSelectors } from '@/store/task/selectors';+import type { TaskGroupItem } from '@/store/task/slices/list/initialState';++// The agent's status board (automated work included) without its finished+// columns: a task-group replica entry, so the panel paints from the persisted+// row on reload and follows optimistic status changes like the board does.+const HIDDEN_STATUSES = ['canceled', 'completed'] as const;+const STATUS_ORDER = ['needsInput', 'backlog', 'running'];++/** The agent sidebar's non-empty status groups, in panel order. */+export const useSidebarTaskGroups = (agentId?: string) => {+ const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);+ const { isLoading, queryKey } = useFetchTaskGroupList({+ agentId,+ enabled: !!agentId,+ excludeStatuses: HIDDEN_STATUSES,+ // The panel ignores the Tasks page's visibility chip.+ visibility: 'all',+ });+ const taskGroups = useTaskStore(taskListSelectors.taskGroups(queryKey));++ const groups = useMemo(() => {+ const map = new Map(taskGroups.map((g) => [g.key, g]));+ return STATUS_ORDER.map((key) => map.get(key)).filter(+ (g): g is TaskGroupItem => !!g && g.tasks.length > 0,+ );+ }, [taskGroups]);++ return { groups, isLoading };+};diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsxindex 4ac7620d9b2..c22732e827e 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx@@ -26,6 +26,7 @@ import type { TaskViewMode } from '@/store/global/initialState';import { systemStatusSelectors } from '@/store/global/selectors';import { useTaskStore } from '@/store/task';import { taskListSelectors } from '@/store/task/selectors';+import { TASK_COLLECTION_PAGE_SIZE } from '@/store/task/slices/list/action';import { createTaskModal } from '../CreateTaskModal';import Breadcrumb from '../shared/Breadcrumb';@@ -112,7 +113,7 @@ interface AgentTasksPageProps {export type TaskCollection = 'mine' | 'scheduled' | 'tasks';/** "My tasks" sub-view: assigned to me as a member, or created by me. */export type MyTaskScope = 'assigned' | 'created';-const COLLECTION_PAGE_SIZE = 50;+const COLLECTION_PAGE_SIZE = TASK_COLLECTION_PAGE_SIZE;export const resolveTaskCollection = (searchParams: URLSearchParams,diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex cc1161f9802..1e978a23047 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -8,7 +8,6 @@ import {isAcceptanceListKey,isDocumentCommentKeyForEvent,recentKeys,- taskKeys,verifyKeys,workKeys,} from './keys';@@ -168,17 +167,3 @@ describe('agentBuilderKeys', () => {expect(persisted).toBe(true);});});--describe('taskKeys', () => {- // Regression for sidebar task list cache persists across navigation to skip skeleton: the sidebar task list used a `sidebar:` domain- // key that no CACHE_TIERS pattern matched, so it was memory-only and every- // fresh page load showed a skeleton. The key must route to a persisted tier- // (the provider matches patterns against the serialized SWR key).- it('routes the sidebar task-groups key to a persisted cache tier', () => {- const serialized = unstable_serialize(taskKeys.sidebarGroups('agent-1'));- const persisted = [...CACHE_TIERS.idb, ...CACHE_TIERS.local].some((pattern) =>- serialized.includes(pattern),- );- expect(persisted).toBe(true);- });-});diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 88f3d33c7b0..ff18cbe7593 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -269,13 +269,6 @@ export const recentKeys = {]),};-// ---- task ----------------------------------------------------------------export const isScheduledTaskListKey = (key: unknown): boolean =>- Array.isArray(key) && key[0] === 'task:scheduledList';--export const isMyTaskListKey = (key: unknown): boolean =>- Array.isArray(key) && key[0] === 'task:myList';-/*** Goal reads that have no local-first projection: the pending queues are live* "what needs you" feeds, and the topic link is a discovery poll.@@ -293,51 +286,6 @@ export const goalKeys = {topicGoals: def('goal:topicGoals', (topicId: string) => ['goal:topicGoals', topicId]),};-export const taskKeys = {- /**- * Home's automated-task roll-up: the tasks that fire on a schedule or a- * heartbeat. Kept off `list` because it is a different result set entirely β- * sharing the key would let one section's fetch overwrite the other's.- */- /**- * The Tasks page's "My tasks" tab: work assigned to, or created by, the- * caller. Its own root for the same reason as `scheduledList` β a different- * result set from `list`, so a shared entry would let one tab's fetch- * overwrite the other's.- */- myList: def(- 'task:myList',- (scope: 'assigned' | 'created', statuses?: string[], limit?: number, offset?: number) => [- 'task:myList',- scope,- // Status narrowing is part of the identity: "hide completed" and "show- // all" are different server pages, not a client-side view of one page.- statuses ? [...statuses].sort().join(',') : 'all',- ...(limit === undefined && offset === undefined ? [] : [{ limit, offset }]),- ],- ),- scheduledList: def(- 'task:scheduledList',- (- agentKey: string | undefined,- visibility: 'all' | 'private' | 'workspace' = 'all',- limit?: number,- offset?: number,- ) => [- 'task:scheduledList',- agentKey,- visibility,- ...(limit === undefined && offset === undefined ? [] : [{ limit, offset }]),- ],- ),- /**- * AgentSidebar task panel. Lives in the `task:` domain (not a `sidebar:`- * one) so the tiered cache provider persists it to IndexedDB and the second- * open renders from cache instead of a skeleton.- */- sidebarGroups: def('task:sidebarGroups', (agentId: string) => ['task:sidebarGroups', agentId]),-};-// ---- work ---------------------------------------------------------------export const workKeys = {conversation: def('work:conversation', (topicId: string, threadId?: string | null) => [@@ -1117,7 +1065,6 @@ export const swrKeys = {session: sessionKeys,share: shareKeys,stats: statsKeys,- task: taskKeys,taskTemplate: taskTemplateKeys,thread: threadKeys,tool: toolKeys,diff --git a/src/libs/swr/localStorageProvider.test.ts b/src/libs/swr/localStorageProvider.test.tsindex 064e27076f5..b75273a918b 100644--- a/src/libs/swr/localStorageProvider.test.ts+++ b/src/libs/swr/localStorageProvider.test.ts@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { bootTiming } from '@/libs/bootTiming';-import { taskKeys, taskTemplateKeys } from './keys';+import { taskTemplateKeys } from './keys';import { buildLocalDataKey, localDataCache } from './localDataCache';import {CACHE_TIERS,@@ -65,7 +65,7 @@ describe('createCacheProvider β tiering', () => {const options = { idbPatterns: [...CACHE_TIERS.idb], localPatterns: [...CACHE_TIERS.local] };const { provider } = buildProvider(scope, options);await provider.hydrateScope?.();- const key = JSON.stringify(taskKeys.myList('assigned'));+ const key = JSON.stringify(['task:detail', 'T-1']);const data = { data: [{ id: 'task-1', title: 'Keep me' }] };provider().set(key, data);await until(async () => (await localDataCache.entriesByScope('s1')).length > 0);diff --git a/src/routes/(main)/tasks/scheduledTaskListLoader.test.ts b/src/routes/(main)/tasks/scheduledTaskListLoader.test.tsnew file mode 100644index 00000000000..8f05d33a022--- /dev/null+++ b/src/routes/(main)/tasks/scheduledTaskListLoader.test.ts@@ -0,0 +1,105 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { scheduledTaskListLoader } from './scheduledTaskListLoader';++const preHydrateScheduledTaskList = vi.fn(async () => true);+const activeWorkspace = vi.hoisted(() => ({ slug: null as string | null }));++vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ getActiveWorkspaceSlug: () => activeWorkspace.slug,+}));++vi.mock('@/store/task', () => ({+ getTaskStoreState: () => ({ preHydrateScheduledTaskList }),+}));++vi.mock('@/store/task/slices/list/action', () => ({ TASK_COLLECTION_PAGE_SIZE: 50 }));++const request = (path: string) => new Request(`http://localhost${path}`);++beforeEach(() => {+ preHydrateScheduledTaskList.mockClear();+ activeWorkspace.slug = null;+});++describe('scheduledTaskListLoader', () => {+ it('seeds the first scheduled page of the scope the URL opens', async () => {+ await expect(+ scheduledTaskListLoader({+ params: { aid: 'agt_1' },+ request: request('/agent/agt_1/tasks?collection=scheduled'),+ }),+ ).resolves.toBeNull();++ expect(preHydrateScheduledTaskList).toHaveBeenCalledWith({+ agentId: 'agt_1',+ limit: 50,+ offset: 0,+ projectId: undefined,+ });+ });++ it('passes the project scope through', async () => {+ await scheduledTaskListLoader({+ params: { projectId: 'proj_1' },+ request: request('/project/proj_1/tasks?collection=scheduled'),+ });++ expect(preHydrateScheduledTaskList).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: 'proj_1' }),+ );+ });++ it('reads nothing for the other tabs', async () => {+ await scheduledTaskListLoader({ params: {}, request: request('/tasks') });+ await scheduledTaskListLoader({ params: {}, request: request('/tasks?collection=mine') });++ expect(preHydrateScheduledTaskList).not.toHaveBeenCalled();+ });++ it('seeds the page when the URL opens the workspace already active', async () => {+ activeWorkspace.slug = 'acme';++ await scheduledTaskListLoader({+ params: { workspaceSlug: 'acme' },+ request: request('/acme/tasks?collection=scheduled'),+ });++ expect(preHydrateScheduledTaskList).toHaveBeenCalledOnce();+ });++ // The workspace switch lands after the route commits, so the active cache+ // scope still belongs to the workspace being left.+ it('reads nothing while the URL switches workspace', async () => {+ await scheduledTaskListLoader({+ params: { workspaceSlug: 'acme' },+ request: request('/acme/tasks?collection=scheduled'),+ });++ activeWorkspace.slug = 'acme';+ await scheduledTaskListLoader({+ params: { workspaceSlug: 'globex' },+ request: request('/globex/tasks?collection=scheduled'),+ });+ await scheduledTaskListLoader({+ params: {},+ request: request('/tasks?collection=scheduled'),+ });++ expect(preHydrateScheduledTaskList).not.toHaveBeenCalled();+ });++ it('never holds the route past the pre-paint deadline', async () => {+ vi.useFakeTimers();+ preHydrateScheduledTaskList.mockReturnValueOnce(new Promise(() => {}));++ const settled = scheduledTaskListLoader({+ params: {},+ request: request('/tasks?collection=scheduled'),+ });+ await vi.advanceTimersByTimeAsync(50);++ await expect(settled).resolves.toBeNull();+ vi.useRealTimers();+ });+});diff --git a/src/routes/(main)/tasks/scheduledTaskListLoader.ts b/src/routes/(main)/tasks/scheduledTaskListLoader.tsnew file mode 100644index 00000000000..c693044a349--- /dev/null+++ b/src/routes/(main)/tasks/scheduledTaskListLoader.ts@@ -0,0 +1,33 @@+import type { LoaderFunctionArgs } from 'react-router';++import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaint';+import { getTaskStoreState } from '@/store/task';+import { TASK_COLLECTION_PAGE_SIZE } from '@/store/task/slices/list/action';++// Route loaders run before React commits the route: the only point where the+// persisted scheduled page (an async read) can land before the Tasks page+// paints its loading state. Only the scheduled tab reads it, and a reload+// always opens that tab on its first page.+export const scheduledTaskListLoader = async ({+ params,+ request,+}: Pick<LoaderFunctionArgs, 'params' | 'request'>): Promise<null> => {+ if (new URL(request.url).searchParams.get('collection') !== 'scheduled') return null;+ // The URL β workspace switch runs after the route commits, so while the URL+ // enters another workspace the active scope is still the one being left;+ // reading it would seed the wrong partition. Leave that to the page's sync.+ if ((params.workspaceSlug ?? null) !== getActiveWorkspaceSlug()) return null;++ await settleWithin(+ getTaskStoreState().preHydrateScheduledTaskList({+ agentId: params.aid,+ limit: TASK_COLLECTION_PAGE_SIZE,+ offset: 0,+ projectId: params.projectId,+ }),+ PRE_PAINT_HYDRATE_TIMEOUT,+ );++ return null;+};diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsxindex c8a613b78aa..dcf5d350445 100644--- a/src/spa/router/desktopRouter.shared.tsx+++ b/src/spa/router/desktopRouter.shared.tsx@@ -88,6 +88,7 @@ import { pageListLoader } from '@/spa/router/pageListLoader';import { preferenceListLoader } from '@/spa/router/preferenceListLoader';import { agentAccessLoader, agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';+import { scheduledTaskListLoader } from '@/spa/router/scheduledTaskListLoader';import { withSegmentFallback } from '@/spa/router/withSegmentFallback';import { worksLoader } from '@/spa/router/worksLoader';import { SettingsTabs } from '@/store/global/initialState';@@ -366,6 +367,7 @@ export const sharedMainAreaChildren: RouteObject[] = ['Desktop > Chat > Tasks',),handle: { meta: tasksRouteMeta },+ loader: scheduledTaskListLoader,path: 'tasks',},{@@ -1094,6 +1096,7 @@ export const sharedMainAreaChildren: RouteObject[] = ['Desktop > Project Tasks',),handle: { meta: tasksRouteMeta },+ loader: scheduledTaskListLoader,path: 'tasks',},{@@ -1179,6 +1182,7 @@ export const sharedMainAreaChildren: RouteObject[] = [}),handle: { meta: tasksRouteMeta },index: true,+ loader: scheduledTaskListLoader,},],errorElement: <ErrorBoundary resetPath=".." />,diff --git a/src/spa/router/scheduledTaskListLoader.ts b/src/spa/router/scheduledTaskListLoader.tsnew file mode 100644index 00000000000..c2f15183cbd--- /dev/null+++ b/src/spa/router/scheduledTaskListLoader.ts@@ -0,0 +1,11 @@+import type { LoaderFunctionArgs } from 'react-router';++/**+ * Route-table entry for the Tasks page's scheduled-tab pre-paint hydrate. The+ * route tables sit in the entry chunk's static graph; resolving the real loader+ * on first use keeps the task store in the tasks routes' lazy chunks.+ */+export const scheduledTaskListLoader = (args: LoaderFunctionArgs) =>+ import('@/routes/(main)/tasks/scheduledTaskListLoader').then((module) =>+ module.scheduledTaskListLoader(args),+ );diff --git a/src/spa/router/scheduledTaskListLoader.wiring.test.ts b/src/spa/router/scheduledTaskListLoader.wiring.test.tsnew file mode 100644index 00000000000..e9fe34c4b19--- /dev/null+++ b/src/spa/router/scheduledTaskListLoader.wiring.test.ts@@ -0,0 +1,42 @@+// @vitest-environment happy-dom+import type { RouteObject } from 'react-router';+import { describe, expect, it, vi } from 'vitest';++import { desktopRoutes } from './desktopRouter.config';+import { scheduledTaskListLoader } from './scheduledTaskListLoader';++const loaderModule = vi.hoisted(() => ({ evaluated: false }));++// Evaluating the real loader means the task store reached the entry chunk's+// first-screen graph.+vi.mock('@/routes/(main)/tasks/scheduledTaskListLoader', () => {+ loaderModule.evaluated = true;+ return { scheduledTaskListLoader: vi.fn(async () => null) };+});++const flatten = (routes: RouteObject[]): RouteObject[] =>+ routes.flatMap((route) => [route, ...(route.children ? flatten(route.children) : [])]);++describe('scheduled task list loader wiring', () => {+ it('does not load the store-backed loader while the route tables load', () => {+ expect(loaderModule.evaluated).toBe(false);+ });++ it('pre-hydrates the scheduled page on the global, agent and project Tasks routes', () => {+ const routes = flatten(desktopRoutes).filter((r) => r.loader === scheduledTaskListLoader);++ // Global `/tasks` (its index route) plus `/agent/:aid/tasks` and+ // `/project/:projectId/tasks`, under both the personal and workspace trees.+ expect(routes.filter((r) => r.index).length).toBeGreaterThan(0);+ expect(routes.filter((r) => r.path === 'tasks').length).toBeGreaterThanOrEqual(2);+ });++ it('delegates to the real loader on first use', async () => {+ const { scheduledTaskListLoader: realLoader } =+ await import('@/routes/(main)/tasks/scheduledTaskListLoader');+ const args = { params: {}, request: new Request('http://localhost/tasks') } as any;++ await expect(scheduledTaskListLoader(args)).resolves.toBeNull();+ expect(realLoader).toHaveBeenCalledWith(args);+ });+});diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.tsindex 0b37b7fd2f1..bfe60b6d808 100644--- a/src/store/task/slices/list/action.test.ts+++ b/src/store/task/slices/list/action.test.ts@@ -46,7 +46,7 @@ describe('TaskListSliceAction', () => {// An edit can move a task across every list boundary at once β reorder it// by `updatedAt`, change its visibility, attach a schedule that flips// Home's automation filter β so refresh revalidates every list and board.- it('revalidates every task list and board, plus the scheduled and mine roll-ups', async () => {+ it('revalidates every task list and board, the scheduled and mine pages included', async () => {const { mutate } = await import('@/libs/swr');await useTaskStore.getState().refreshTaskList();@@ -59,8 +59,10 @@ describe('TaskListSliceAction', () => {const scope = (await import('@/libs/replica')).cacheScope.get();expect(matches(['replica:sync', 'taskList', 1, scope, 'any-list', {}])).toBe(true);expect(matches(['replica:sync', 'taskGroupList', 1, scope, 'any-board', {}])).toBe(true);- expect(matches(['task:scheduledList', '__all__', 'all'])).toBe(true);- expect(matches(['task:myList', 'assigned', 'all'])).toBe(true);+ // The scheduled roll-up, "My tasks" and the sidebar panel are replica+ // entries now, so no SWR-persisted `task:` key is left to revalidate.+ expect(matches(['task:scheduledList', '__all__', 'all'])).toBe(false);+ expect(matches(['task:myList', 'assigned', 'all'])).toBe(false);});});@@ -259,7 +261,7 @@ describe('TaskListSliceAction', () => {});describe('useFetchScheduledTaskList', () => {- it('keys and requests the selected scheduled-task page', async () => {+ it('syncs the selected scheduled-task page as a task-list replica entry', async () => {const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');@@ -267,70 +269,185 @@ describe('TaskListSliceAction', () => {useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 }),);- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:scheduledList', '__all__', 'all', { limit: 50, offset: 50 }],- expect.any(Function),- expect.any(Object),- );- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => Promise<unknown>;- await fetcher();+ // No SWR-persisted `task:scheduledList` key any more.+ expect(+ vi+ .mocked(useClientDataSWR)+ .mock.calls.some(([key]) => Array.isArray(key) && key[0] === 'task:scheduledList'),+ ).toBe(false);+ const [page] = await syncCalls('taskList');+ await page.fetcher();expect(taskService.list).toHaveBeenCalledWith(- expect.objectContaining({ automated: true, limit: 50, offset: 50 }),+ expect.objectContaining({ automated: true, limit: 50, offset: 50, orderBy: 'updatedAt' }),);});- it('scopes the scheduled roll-up to one agent, key included', async () => {- const { useClientDataSWR } = await import('@/libs/swr');+ it('scopes the scheduled roll-up to one agent', async () => {const { taskService } = await import('@/services/task');renderHook(() =>useTaskStore.getState().useFetchScheduledTaskList({ agentId: 'agent-1', limit: 50 }),);- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:scheduledList', 'agent-1', 'all', { limit: 50, offset: undefined }],- expect.any(Function),- expect.any(Object),- );- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => Promise<unknown>;- await fetcher();+ const [page] = await syncCalls('taskList');+ await page.fetcher();expect(taskService.list).toHaveBeenCalledWith(- expect.objectContaining({ assigneeAgentId: 'agent-1', automated: true }),+ expect.objectContaining({ assigneeAgentId: 'agent-1', automated: true, limit: 50 }),);});- it('scopes the scheduled roll-up to one project, key included', async () => {- const { useClientDataSWR } = await import('@/libs/swr');+ it('scopes the scheduled roll-up to one project, never to an agent too', async () => {const { taskService } = await import('@/services/task');renderHook(() =>- useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, projectId: 'project-1' }),+ useTaskStore+ .getState()+ .useFetchScheduledTaskList({ agentId: 'agent-1', limit: 50, projectId: 'project-1' }),);- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:scheduledList', '__project__:project-1', 'all', { limit: 50, offset: undefined }],- expect.any(Function),- expect.any(Object),+ const [page] = await syncCalls('taskList');+ await page.fetcher();+ const params = vi.mocked(taskService.list).mock.calls[0][0];+ expect(params).toMatchObject({ automated: true, projectId: 'project-1' });+ expect(params.assigneeAgentId).toBeUndefined();+ });++ it('keeps concurrent consumers and scopes isolated by their query keys', () => {+ const { result } = renderHook(() => [+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 5 }),+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 }),+ useTaskStore.getState().useFetchScheduledTaskList({ agentId: 'agent-1', limit: 5 }),+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 5, projectId: 'project-1' }),+ useTaskStore.getState().useFetchTaskList({ allAgents: true, automated: true }),+ ]);++ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(5);+ });++ // Regression: the roll-up lived in the SWR persistence layer, so a reload+ // only painted it after that layer's whole-cache hydration. As a replica+ // entry it paints from the store row (persisted or fetched) on mount.+ it('paints the page from its replica entry, in the list endpoint shape', () => {+ const { result } = renderHook(() =>+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 5 }),);- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => Promise<unknown>;- await fetcher();- expect(taskService.list).toHaveBeenCalledWith(- expect.objectContaining({ automated: true, projectId: 'project-1' }),+ const queryKey = result.current.queryKey!;+ expect(result.current.data).toBeUndefined();++ const items = [{ id: 'task-1', identifier: 'T-1', status: 'scheduled' }] as any;+ act(() => {+ useTaskStore.setState({ taskListMap: { [queryKey]: { items, total: 7 } } });+ });++ expect(result.current.data).toEqual({ data: items, total: 7 });+ expect(result.current.isLoading).toBe(false);+ });++ it('returns no page and no query key while disabled', () => {+ const { result } = renderHook(() =>+ useTaskStore.getState().useFetchScheduledTaskList({ enabled: false, limit: 5 }),+ );+ expect(result.current.queryKey).toBeUndefined();+ expect(result.current.data).toBeUndefined();+ });+ });++ describe('preHydrateScheduledTaskList', () => {+ // The Tasks route loader seeds the scheduled page before the route+ // commits, so a reload paints it instead of the list's loading state.+ it('seeds the scheduled page from its persisted row before anything mounts', async () => {+ const { scheduledTaskListQuery } = await import('./action');+ const { taskListQueryKey, taskListResource } = await import('./projection');+ const items = [{ id: 'task-1', identifier: 'T-1', status: 'scheduled' }];+ const get = vi+ .spyOn(taskListResource.storage!, 'get')+ .mockResolvedValue({ data: { items, total: 1 } as any, updatedAt: 1 });+ const options = { agentId: 'agent-1', limit: 50, offset: 0 };++ await expect(useTaskStore.getState().preHydrateScheduledTaskList(options)).resolves.toBe(+ true,);++ const queryKey = taskListQueryKey(scheduledTaskListQuery(options));+ expect(useTaskStore.getState().taskListMap[queryKey]).toEqual({ items, total: 1 });+ // The hook asks for exactly the entry the loader seeded.+ const { result } = renderHook(() =>+ useTaskStore.getState().useFetchScheduledTaskList(options),+ );+ expect(result.current.queryKey).toBe(queryKey);+ expect(result.current.data).toEqual({ data: items, total: 1 });+ get.mockRestore();});+ });- it('keeps concurrent consumers isolated by their SWR keys', async () => {+ describe('useFetchMyTaskList', () => {+ it('syncs "My tasks" as a task-list entry narrowed by scope and statuses', async () => {const { useClientDataSWR } = await import('@/libs/swr');+ const { taskService } = await import('@/services/task');- renderHook(() => useTaskStore.getState().useFetchScheduledTaskList({ limit: 5 }));renderHook(() =>- useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 }),+ useTaskStore.getState().useFetchMyTaskList({+ limit: 20,+ offset: 20,+ scope: 'assigned',+ statuses: ['running', 'backlog'],+ }),);- expect(vi.mocked(useClientDataSWR).mock.calls.map(([key]) => key)).toEqual([- ['task:scheduledList', '__all__', 'all', { limit: 5, offset: undefined }],- ['task:scheduledList', '__all__', 'all', { limit: 50, offset: 50 }],+ expect(+ vi+ .mocked(useClientDataSWR)+ .mock.calls.some(([key]) => Array.isArray(key) && key[0] === 'task:myList'),+ ).toBe(false);+ const [page] = await syncCalls('taskList');+ await page.fetcher();+ expect(taskService.list).toHaveBeenCalledWith({+ automated: undefined,+ limit: 20,+ offset: 20,+ orderBy: 'updatedAt',+ projectId: undefined,+ scope: 'assigned',+ statuses: ['backlog', 'running'],+ visibility: undefined,+ });+ });++ it('ignores the visibility chip and keeps each scope and status set apart', () => {+ useTaskStore.setState({ listVisibility: 'private' });+ const { result } = renderHook(() => [+ useTaskStore.getState().useFetchMyTaskList({ scope: 'assigned' }),+ useTaskStore.getState().useFetchMyTaskList({ scope: 'created' }),+ useTaskStore.getState().useFetchMyTaskList({ scope: 'assigned', statuses: ['running'] }),]);++ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(3);+ expect(result.current[0].queryKey).toContain('"visibility":"all"');+ });+ });++ describe('agent sidebar groups', () => {+ it('lets an embedded board override the visibility chip', async () => {+ const { taskService } = await import('@/services/task');+ useTaskStore.setState({ listVisibility: 'private' });++ renderHook(() =>+ useTaskStore.getState().useFetchTaskGroupList({+ agentId: 'agent-1',+ excludeStatuses: ['completed', 'canceled'],+ visibility: 'all',+ }),+ );++ const [board] = await syncCalls('taskGroupList');+ await board.fetcher();+ expect(taskService.groupList).toHaveBeenCalledWith(+ expect.objectContaining({+ assigneeAgentId: 'agent-1',+ excludeStatuses: ['canceled', 'completed'],+ visibility: undefined,+ }),+ );});});diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.tsindex 0e5eb93819c..fe0874a9acd 100644--- a/src/store/task/slices/list/action.ts+++ b/src/store/task/slices/list/action.ts@@ -1,8 +1,7 @@import type { TaskStatus } from '@lobechat/types';+import { useMemo } from 'react';import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { isMyTaskListKey, isScheduledTaskListKey, taskKeys } from '@/libs/swr/keys';import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';@@ -23,13 +22,6 @@ import {type TaskListValue,} from './projection';-/**- * Scope keys of the scheduled roll-up's SWR key: all agents, or one project.- * Kept distinct from per-agent ids so the entries never collide.- */-const ALL_AGENTS_LIST_KEY = '__all__';-const PROJECT_LIST_KEY_PREFIX = '__project__:';-// Default kanban groups: 5 columns// 'scheduled' shares the 'running' column β both represent "automation in// progress" from the user's perspective (one is mid-tick, the other is@@ -64,8 +56,47 @@ const filterToServerVisibility = (* the real `total` so the list can say it is showing a subset.*/export const COMPLETE_TASK_LIST_PAGE_SIZE = 100;++/** Page size of the Tasks page's paginated collections (scheduled, "My tasks"). */+export const TASK_COLLECTION_PAGE_SIZE = 50;++export interface ScheduledTaskListOptions {+ agentId?: string;+ limit?: number;+ offset?: number;+ projectId?: string;+}++/**+ * The task-list query of one scheduled roll-up page. `agentId`/`projectId`+ * narrow it to a scoped Tasks page and are part of the key, so an agent's+ * schedules never render under another scope.+ */+export const scheduledTaskListQuery = ({+ agentId,+ limit,+ offset,+ projectId,+}: ScheduledTaskListOptions): TaskListQuery => ({+ agentId: projectId ? undefined : agentId,+ automated: true,+ limit,+ offset,+ orderBy: 'updatedAt',+ projectId,+ visibility: 'all',+});export const COMPLETE_TASK_LIST_MAX_ITEMS = 1000;+/**+ * A paginated collection (scheduled roll-up, "My tasks"): the task-list sync+ * plus the page in the `{ data, total }` shape of the list endpoint, undefined+ * until the entry is in the store (persisted or fetched) and while disabled.+ */+export interface TaskCollectionPageResult extends TaskCollectionSyncResult {+ data?: { data: TaskListValue['items']; total: number };+}+/** Sync result of a task list / board fetch: replica flags plus the SWR-era aliases. */export interface TaskCollectionSyncResult extends ReplicaSyncResult {/** A request is in flight and there is nothing to show for this query yet. */@@ -128,10 +159,13 @@ export class TaskListSliceActionImpl {includeArchived: query.includeArchived,orderBy: query.orderBy,projectId: query.projectId,+ ...(query.scope && { scope: query.scope }),statuses: query.statuses,visibility: filterToServerVisibility(query.visibility),};- return query.complete ? this.fetchCompleteTaskList(params) : this.fetchTaskList(params);+ return query.complete+ ? this.fetchCompleteTaskList(params)+ : this.fetchTaskList({ ...params, limit: query.limit, offset: query.offset });};#fetchGroups = (query: TaskGroupListQuery) =>@@ -148,6 +182,19 @@ export class TaskListSliceActionImpl {visibility: filterToServerVisibility(query.visibility),});+ /** One page of a paginated collection, read reactively from its replica entry. */+ #useCollectionPage = (query: TaskListQuery, enabled: boolean): TaskCollectionPageResult => {+ const queryKey = taskListQueryKey(query);+ // A collection page is a deliberate view, not a live feed: no refetch on focus.+ const sync = this.#taskList.useSync(query, { enabled, revalidateOnFocus: false });+ const value = useTaskStore((s) => (enabled ? s.taskListMap[queryKey] : undefined));+ const data = useMemo(+ () => (value ? { data: value.items, total: value.total } : undefined),+ [value],+ );+ return { ...this.#toSyncResult(sync, enabled ? queryKey : undefined, !!value), data };+ };+#toSyncResult = (sync: ReplicaSyncResult,queryKey: string | undefined,@@ -256,13 +303,10 @@ export class TaskListSliceActionImpl {// Every loaded list and board of the active scope β an edit can move a// task across any query boundary (touching reorders `updatedAt`,// scheduling flips the automation filter), so none are singled out.+ // That includes the scheduled roll-up and "My tasks" pages (a schedule+ // or an assignee can change on any edit) and the agent sidebar panels.this.#taskList.revalidate(),this.#taskGroupList.revalidate(),- // A schedule can be attached, changed or removed from any task edit, so- // the automated roll-up has to be revalidated alongside the main list.- mutate(isScheduledTaskListKey),- // Assigning or creating moves a task in or out of "My tasks".- mutate(isMyTaskListKey),]);};@@ -287,6 +331,8 @@ export class TaskListSliceActionImpl {* server-side exactly like `useFetchMyTaskList` narrows its list.*/scope?: 'assigned' | 'created';+ /** Override the Task page's persisted filter for embedded consumers (the agent sidebar). */+ visibility?: TaskListVisibilityFilter;} = {},): TaskCollectionSyncResult => {const {@@ -299,6 +345,7 @@ export class TaskListSliceActionImpl {includeArchived,projectId,scope,+ visibility,} = options;// Subscribed, so flipping the visibility chip re-keys the board query.const listVisibility = useTaskStore((s) => s.listVisibility);@@ -316,7 +363,7 @@ export class TaskListSliceActionImpl {// (`useFetchMyTaskList`) sends no visibility at all, so its board// ignores the chip too β otherwise a value left over from the// ordinary tab would change the row set on the list β board switch.- visibility: scope ? 'all' : listVisibility,+ visibility: scope ? 'all' : (visibility ?? listVisibility),}: undefined;const queryKey = query ? taskGroupListQueryKey(query) : undefined;@@ -331,44 +378,32 @@ export class TaskListSliceActionImpl {/*** The automated-task roll-up behind Home's "Scheduled" section and the Tasks- * page's scheduled tab. Each caller consumes its own SWR result because Home- * and the paginated Tasks page can coexist in Electron with different limits- * and offsets. `agentId`/`projectId` narrow the roll-up to the scoped Tasks- * page; they are part of the key so an agent's schedules never render under- * another scope.+ * page's scheduled tab. Each limit / offset is its own task-list entry+ * because Home and the paginated Tasks page can coexist in Electron.*/useFetchScheduledTaskList = (- options: {- agentId?: string;- enabled?: boolean;- limit?: number;- offset?: number;- projectId?: string;- } = {},- ) => {- const { agentId, enabled = true, limit, offset, projectId } = options;- const scopeKey = projectId- ? `${PROJECT_LIST_KEY_PREFIX}${projectId}`- : (agentId ?? ALL_AGENTS_LIST_KEY);- return useClientDataSWR(- enabled ? taskKeys.scheduledList(scopeKey, 'all', limit, offset) : null,- async () =>- this.fetchTaskList({- ...(projectId ? { projectId } : agentId ? { assigneeAgentId: agentId } : {}),- automated: true,- limit,- offset,- orderBy: 'updatedAt',- }),- { revalidateOnFocus: false },- );+ options: ScheduledTaskListOptions & { enabled?: boolean } = {},+ ): TaskCollectionPageResult => {+ const { enabled = true, ...query } = options;+ return this.#useCollectionPage(scheduledTaskListQuery(query), enabled);+ };++ /**+ * Seed the persisted scheduled page before the route commits, so a reload+ * paints the local copy instead of the list's loading state. A later+ * `useSync` hydrate is a no-op once the slot is filled.+ */+ preHydrateScheduledTaskList = (options: ScheduledTaskListOptions): Promise<boolean> => {+ const scope = taskListResource.scope.get();+ this.#taskList.ensureScope(scope);+ return this.#taskList.hydrate(scheduledTaskListQuery(options), scope);};/*** The Tasks page's "My tasks" tab β the caller's own slice of the workspace- * (`assigned` to them as a member, or `created` by them). Consumed like the- * scheduled roll-up: its own SWR result, never the shared `tasks` field, so- * flipping the tab cannot leak one collection into the other.+ * (`assigned` to them as a member, or `created` by them). Its own task-list+ * entries, never the ordinary tab's, so flipping the tab cannot leak one+ * collection into the other.*/useFetchMyTaskList = (options: {enabled?: boolean;@@ -380,29 +415,24 @@ export class TaskListSliceActionImpl {* Server-side status narrowing (the `hideCompleted` display option* translated by `getVisibleTaskStatuses`). Applied before `limit` /* `offset` so a page can never come back empty while older unfinished- * tasks exist; part of the cache key for the same reason as `scope`.+ * tasks exist; part of the query for the same reason as `scope`.*/statuses?: TaskStatus[];- }) => {+ }): TaskCollectionPageResult => {const { enabled = true, includeArchived, limit, offset, scope, statuses } = options;- return useClientDataSWR(- enabled- ? [- ...taskKeys.myList(scope, statuses, limit, offset),- // Archived rows are a different server page, like the status filter.- ...(includeArchived ? ['archived'] : []),- ]- : null,- async () =>- this.fetchTaskList({- includeArchived,- limit,- offset,- orderBy: 'updatedAt',- scope,- statuses,- }),- { revalidateOnFocus: false },+ return this.#useCollectionPage(+ {+ // Archived rows are a different server page, like the status filter.+ includeArchived: includeArchived || undefined,+ limit,+ offset,+ orderBy: 'updatedAt',+ scope,+ statuses: statuses?.length ? [...statuses].sort() : undefined,+ // The tab offers no visibility chip and sends no visibility filter.+ visibility: 'all',+ },+ enabled,);};diff --git a/src/store/task/slices/list/projection.ts b/src/store/task/slices/list/projection.tsindex e34fcc11e3f..dfb35bdffe5 100644--- a/src/store/task/slices/list/projection.ts+++ b/src/store/task/slices/list/projection.ts@@ -30,8 +30,13 @@ export interface TaskListQuery {complete?: boolean;/** Archived tasks are hidden unless the "Show archived" option is on. */includeArchived?: boolean;+ /** One server page of a paginated collection (scheduled / "My tasks"); ignored by `complete`. */+ limit?: number;+ offset?: number;orderBy?: 'createdAt' | 'updatedAt';projectId?: string;+ /** "My tasks": assigned to, or created by, the caller. */+ scope?: 'assigned' | 'created';/** Sorted, so the same status set is one entry. */statuses?: TaskStatus[];visibility: TaskListVisibilityFilter;@@ -70,6 +75,9 @@ export const taskGroupListQueryKey = (query: TaskGroupListQuery) => stableQueryKexport const taskListResource = defineReplica<TaskListQuery, TaskListValue, TaskListResponse>({key: taskListQueryKey,name: 'taskList',+ // Every scope, filter and collection page is its own row, and a `complete`+ // list holds up to 1000 tasks β keep only the recently opened ones.+ persist: { maxEntries: 40 },storage: 'indexedDB',version: 1,});@@ -81,6 +89,8 @@ export const taskGroupListResource = defineReplica<>({key: taskGroupListQueryKey,name: 'taskGroupList',+ // One row per board and per agent sidebar panel.+ persist: { maxEntries: 40 },storage: 'indexedDB',version: 1,});