π€― 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 task lists, kanban boards and task details onto @lobechat/replica (#20391)
Arvin Xu0cb5fc24bb17
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.tsindex 3ee18d566ef..88fc9e7bf74 100644--- a/packages/replica/src/zustand/createReplicaSlice.test.ts+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts@@ -141,6 +141,38 @@ describe('createReplicaSlice', () => {expect(failing.store.getState().lists.b).toBeUndefined();});+ it('hands its schedule (polling, focus revalidation β¦) to the driver', () => {+ const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'scheduled',+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ renderHook(() =>+ slice.useSync({ id: 'a' }, { refreshInterval: 10_000, revalidateOnFocus: false }),+ );++ expect(useQuery).toHaveBeenCalledWith(+ expect.arrayContaining(['replica:sync', 'scheduled']),+ expect.any(Function),+ expect.objectContaining({ refreshInterval: 10_000, revalidateOnFocus: false }),+ );+ });+it('does not let a slow hydration overwrite a faster server response', async () => {const storage = createMemoryStorage();storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.tsindex b9f330751d8..2f13b1c2fff 100644--- a/packages/replica/src/zustand/createReplicaSlice.ts+++ b/packages/replica/src/zustand/createReplicaSlice.ts@@ -4,7 +4,7 @@ import { createReplicaEngine, type ReplicaEngineOptions } from '../core/engine';import { isReplicaSyncKey, replicaKeys } from '../core/keys';import type { ReplicaViewWrite } from '../core/reducer';import type { ReplicaResource, ReplicaState } from '../core/types';-import type { ReplicaSyncDriver } from './driver';+import type { ReplicaSyncDriver, ReplicaSyncSchedule } from './driver';/** Zustand `setState`, with the devtools action label. */type Setter<TStore> = (partial: Partial<TStore>, replace?: false, action?: any) => void;@@ -35,7 +35,7 @@ export interface CreateReplicaSliceOptions<TStore, TParams, TData, TFetched> extview: ReplicaLens<TStore, TData>;}-export interface ReplicaSyncOptions<TFetched = unknown> {+export interface ReplicaSyncOptions<TFetched = unknown> extends ReplicaSyncSchedule {enabled?: boolean;/** Side effects of a failed fetch (error side-maps); the store view is left as is. */onError?: (error: unknown) => void;@@ -111,7 +111,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(*/const useSync = (params: TParams | null | undefined,- { enabled = true, onError, onSuccess }: ReplicaSyncOptions<TFetched> = {},+ { enabled = true, onError, onSuccess, ...schedule }: ReplicaSyncOptions<TFetched> = {},): ReplicaSyncResult => {const scope = resource.scope.use();const key = params ? resource.key(params) : undefined;@@ -140,6 +140,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(: null,() => fetcher!(params!, undefined),{+ ...schedule,onError,onSuccess: (data) => {replace(params!, data, scope);diff --git a/packages/replica/src/zustand/driver.ts b/packages/replica/src/zustand/driver.tsindex ae4f46cb434..4f78a244676 100644--- a/packages/replica/src/zustand/driver.ts+++ b/packages/replica/src/zustand/driver.ts@@ -1,4 +1,20 @@-export interface ReplicaQueryOptions<T> {+/**+ * Scheduling knobs a sync can ask its driver for. Named after SWR's options;+ * a driver maps them onto its own cache (or ignores what it cannot honor).+ */+export interface ReplicaSyncSchedule {+ /** Collapse identical requests within this window (ms). */+ dedupingInterval?: number;+ /** Poll every N ms while mounted (0 = off). */+ refreshInterval?: number;+ /** Keep polling while the page is hidden. */+ refreshWhenHidden?: boolean;+ revalidateIfStale?: boolean;+ revalidateOnFocus?: boolean;+ revalidateOnReconnect?: boolean;+}++export interface ReplicaQueryOptions<T> extends ReplicaSyncSchedule {/** Run once per key: no refetch on focus, reconnect or remount (hydration reads). */once?: boolean;onError?: (error: unknown) => void;@@ -46,8 +62,9 @@ export const createSWRDriver = ({useSWR: SWRLikeHook;}): ReplicaSyncDriver => ({revalidate: (match) => mutate(match),- useQuery: (key, fetcher, { once, onError, onSuccess }) =>+ useQuery: (key, fetcher, { once, onError, onSuccess, ...schedule }) =>useSWR(key, fetcher, {+ ...Object.fromEntries(Object.entries(schedule).filter(([, value]) => value !== undefined)),...(once && {revalidateIfStale: false,revalidateOnFocus: false,diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsxindex 43ae62a026e..f127d532275 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx@@ -196,8 +196,8 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {const isBoardView = resolveTaskCollectionView(collection, viewMode) === 'board';const isMineBoard = isMineCollection && isBoardView;const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);- // Keep the SWR handle only for `error` + `mutate` (the error/Retry state).- // Every scope splits automated work out of the ordinary tab β it is the+ // Keep the sync handle for `error` + `mutate` (the error/Retry state) and the+ // `queryKey` the rows are read by. Every scope splits automated work out of the ordinary tab β it is the// scheduled tab's content, and listing it twice makes the split meaningless.// `complete`: this tab groups and sorts client-side with no pagination, so// it needs the whole list β one server page would drop every task older@@ -206,7 +206,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {// gated to the ordinary tab; and the kanban view fetches its own server// groups, so there only the single page behind the empty-hero decision runs.const isListView = !isBoardView;- const { error, isLoading, mutate } = useFetchTaskList(+ const { error, isLoading, mutate, queryKey } = useFetchTaskList(projectId? {automated: false,@@ -224,17 +224,17 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {enabled: isOrdinaryCollection,},);- // Drive the loading/empty boundary off the store's own init flag, NOT SWR's- // per-key `data`. On a scope (agent β all) or visibility switch the store- // resets `tasks` + `isTaskListInit` together (`scopeChangeResetState`), but- // SWR still holds cached `data` for the target key β so keying `hasSettled`- // off SWR `data` made it `true` while `tasks` was empty and flashed the "no- // tasks" empty during the refetch. `isTaskListInit` flips true only on the- // current scope's success and resets in lockstep with `tasks`, so the settled- // signal never disagrees with the emptiness signal. Still resets to false on a- // failed first load, so we surface loading only while there's no error (below).- const isTaskListInit = useTaskStore(taskListSelectors.isTaskListInit);- const isEmptyHero = useTaskStore(taskListSelectors.isListEmpty);+ // Drive the loading/empty boundary off the store entry of this exact query:+ // each scope / visibility is its own entry, so the settled signal and the+ // rows always describe the same list (a persisted entry paints at once).+ const isTaskListInit = useTaskStore(taskListSelectors.isTaskListInit(queryKey));+ const setActiveTaskListKey = useTaskStore((s) => s.setActiveTaskListKey);+ // The task manager agent reads this page's list as "the viewed list".+ useEffect(() => {+ setActiveTaskListKey(queryKey);+ return () => setActiveTaskListKey(undefined);+ }, [queryKey, setActiveTaskListKey]);+ const isEmptyHero = useTaskStore(taskListSelectors.isListEmpty(queryKey));const useFetchScheduledTaskList = useTaskStore((s) => s.useFetchScheduledTaskList);const scheduledSWR = useFetchScheduledTaskList({agentId,@@ -501,6 +501,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {error={error}isLoading={isLoading || (!isTaskListInit && !error)}options={viewOptions}+ queryKey={queryKey}routeScope={routeScope}onRetry={() => mutate()}onShowHiddenCompleted={handleShowHiddenCompleted}diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsxindex 63ec9a7fda4..5c11f9aa783 100644--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx@@ -84,24 +84,15 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {const excludeStatuses = options.hideCompleted ? HIDDEN_WHEN_COMPLETED_STATUSES : undefined;const useFetchTaskGroupList = useTaskStore((s) => s.useFetchTaskGroupList);- // Keep the SWR handle only for `error` + `mutate` (the error/Retry state).- const { error, isLoading, isQueryScopeCurrent, mutate } = useFetchTaskGroupList(+ // Keep the sync handle for `error` + `mutate` (the error/Retry state) and the+ // `queryKey` the groups are read by.+ const { error, isLoading, mutate, queryKey } = useFetchTaskGroupList(buildKanbanGroupQuery({ agentId, excludeStatuses, groupBy, myTaskScope, projectId }),);- // Drive the loading/empty boundary off the store's own init flag, NOT SWR's- // per-key `data`. On a scope or visibility switch the store resets- // `taskGroups` + `isTaskGroupListInit` together (`scopeChangeResetState`)- // while SWR still holds cached `data` for the target key β keying `hasSettled`- // off SWR `data` flashed the "no tasks" empty board during the refetch.- // `isTaskGroupListInit` resets in lockstep with `taskGroups`, so the settled- // signal never disagrees with the emptiness signal.- const isTaskGroupListInit = useTaskStore(taskListSelectors.isTaskGroupListInit);-- const taskGroups = useTaskStore(taskListSelectors.taskGroups);- const currentTaskGroups = useMemo(- () => (isQueryScopeCurrent ? taskGroups : []),- [isQueryScopeCurrent, taskGroups],- );+ // Each board query (scope, dimension, filters) is its own store entry, so the+ // settled signal and the groups always describe the same board.+ const isTaskGroupListInit = useTaskStore(taskListSelectors.isTaskGroupListInit(queryKey));+ const currentTaskGroups = useTaskStore(taskListSelectors.taskGroups(queryKey));const updateTask = useTaskStore((s) => s.updateTask);const runTask = useTaskStore((s) => s.runTask);const refreshTaskList = useTaskStore((s) => s.refreshTaskList);@@ -142,7 +133,11 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {const retry = () => {start().catch(() => {});};- const current = findKanbanTask(useTaskStore.getState().taskGroups, task.identifier) ?? task;+ const current =+ findKanbanTask(+ taskListSelectors.taskGroups(queryKey)(useTaskStore.getState()),+ task.identifier,+ ) ?? task;if (!current.assigneeAgentId && !current.assigneeUserId && inboxAgentId) {await updateTask(current.identifier, { assigneeAgentId: inboxAgentId }, { retry });afterAssign?.();@@ -156,7 +151,7 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {};return start(onAssigned);},- [inboxAgentId, runTask, t, updateTask],+ [inboxAgentId, queryKey, runTask, t, updateTask],);const handleDragEnd = useCallback(@@ -184,47 +179,49 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {if ((groupBy === 'assignee' || groupBy === 'member') && !assigneeUpdate) return;if (groupBy === 'priority' && (task.priority ?? 0) === (patch.priority ?? 0)) return;- const prevGroups = useTaskStore.getState().taskGroups;- const nextGroups = moveTaskBetweenKanbanGroups(prevGroups, task, targetColumnKey, patch);- useTaskStore.setState({ taskGroups: nextGroups }, false, 'kanban/optimisticMove');+ if (!queryKey) return;+ // The move is idempotent, so the overlay stays correct when the status+ // change also patches the card underneath it.+ const move = useTaskStore.getState().internal_beginTaskGroupOptimistic(queryKey, (value) => ({+ ...value,+ groups: moveTaskBetweenKanbanGroups(value.groups, task, targetColumnKey, patch),+ }));try {if (groupBy === 'status' && column.targetStatus === 'running') {- // Dropping into "In progress" starts the task, same as "Run now".- await startTask(task, () => {- // The assignment refetches the groups, where the task is still in- // backlog until the run starts β keep the card in "In progress".- const refreshedGroups = useTaskStore.getState().taskGroups;- useTaskStore.setState(- {- taskGroups: moveTaskBetweenKanbanGroups(- refreshedGroups,- findKanbanTask(refreshedGroups, task.identifier) ?? task,- targetColumnKey,- patch,- ),- },- false,- 'kanban/optimisticMove',- );- });+ // Dropping into "In progress" starts the task, same as "Run now". The+ // assignment refetches the groups (still backlog until the run+ // starts); the overlay is rebased onto that refetch, so the card+ // stays in "In progress".+ await startTask(task);} else if (groupBy === 'status' && column.targetStatus) {const changed = await changeTaskStatus(task.identifier, column.targetStatus);if (!changed) {- useTaskStore.setState({ taskGroups: prevGroups }, false, 'kanban/cancelMove');+ move.rollback();+ return;}} else if ((groupBy === 'assignee' || groupBy === 'member') && assigneeUpdate) {await updateTask(task.identifier, assigneeUpdate);} else if (groupBy === 'priority') {await updateTask(task.identifier, { priority: patch.priority ?? 0 });}+ move.commit();} catch {- useTaskStore.setState({ taskGroups: prevGroups }, false, 'kanban/revertMove');+ move.rollback();// A failed start may already have persisted the fallback assignee.if (column.targetStatus === 'running') void refreshTaskList();}},- [canEditTask, changeTaskStatus, columns, groupBy, refreshTaskList, startTask, updateTask],+ [+ canEditTask,+ changeTaskStatus,+ columns,+ groupBy,+ queryKey,+ refreshTaskList,+ startTask,+ updateTask,+ ],);const handleDragCancel = useCallback(() => {@@ -393,12 +390,12 @@ const KanbanBoard = memo<KanbanBoardProps>((props) => {// undefined until the first fetch settles.return (<AsyncBoundary- data={(isQueryScopeCurrent && isTaskGroupListInit) || undefined}+ data={isTaskGroupListInit || undefined}empty={emptyState}error={error}errorVariant={'block'}isEmpty={totalTasks === 0}- isLoading={isLoading || (!isQueryScopeCurrent && !error) || (!isTaskGroupListInit && !error)}+ isLoading={isLoading || (!isTaskGroupListInit && !error)}loading={skeletonBoard}onRetry={() => mutate()}>diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsxindex ccbdb949b56..0cf0b694d07 100644--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx@@ -40,10 +40,9 @@ import { useClosestScrollParent } from './useClosestScrollParent';interface TaskListProps {/**- * Settled signal β truthy once the current scope's list has loaded into the- * store, `undefined` while unsettled. Derived from the store's- * `isTaskListInit` (not raw SWR `data`) so it resets in lockstep with `tasks`- * on a scope/visibility switch and never disagrees with the empty signal.+ * Settled signal β truthy once the list behind `queryKey` has a value in the+ * store, `undefined` while unsettled. Derived from the same entry as the rows,+ * so it never disagrees with the empty signal.*/data?: unknown;emptyDescription?: string;@@ -56,6 +55,8 @@ interface TaskListProps {onRetry?: () => void;onShowHiddenCompleted?: () => void;options: TaskListViewOptions;+ /** Store entry of the list to render (`useFetchTaskList().queryKey`) when `items` is absent. */+ queryKey?: string;routeScope?: TaskItemRouteScope;}@@ -131,11 +132,20 @@ const VIRTUAL_LIST_COMPONENTS: Components<TaskListVirtualItem, TaskListVirtualCo};const TaskList = memo<TaskListProps>((props) => {- const { data, error, isLoading, items, onRetry, onShowHiddenCompleted, options, routeScope } =- props;+ const {+ data,+ error,+ isLoading,+ items,+ onRetry,+ onShowHiddenCompleted,+ options,+ queryKey,+ routeScope,+ } = props;const { t } = useTranslation('chat');- const storeTasks = useTaskStore(taskListSelectors.taskList);- const storeTasksTotal = useTaskStore(taskListSelectors.taskListTotal);+ const storeTasks = useTaskStore(taskListSelectors.taskList(queryKey));+ const storeTasksTotal = useTaskStore(taskListSelectors.taskListTotal(queryKey));const tasks = items ?? storeTasks;// The store list is fetched in full up to a ceiling; past it the server's// `total` still counts every task, so say the list is a subset rather thandiff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsxindex 94bc5ea90e9..0827761cbd9 100644--- a/src/features/Home/HomeModeContent.tsx+++ b/src/features/Home/HomeModeContent.tsx@@ -367,9 +367,9 @@ const TaskContent = memo(() => {statuses: RECENT_TASK_STATUSES,visibility: 'all',});- const tasks = useTaskStore(taskListSelectors.taskList);- const tasksTotal = useTaskStore(taskListSelectors.taskListTotal);- const tasksInit = useTaskStore(taskListSelectors.isTaskListInit);+ const tasks = useTaskStore(taskListSelectors.taskList(tasksSWR.queryKey));+ const tasksTotal = useTaskStore(taskListSelectors.taskListTotal(tasksSWR.queryKey));+ const tasksInit = useTaskStore(taskListSelectors.isTaskListInit(tasksSWR.queryKey));const taskCount = useGlobalStore(systemStatusSelectors.homeTaskCount);const shown = tasks.slice(0, taskCount);diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex a8295908257..e89303aba30 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -315,16 +315,6 @@ export const recentKeys = {};// ---- task ----------------------------------------------------------------/**- * SWR `mutate` matcher for every cached `task:list` variant β any agent scope,- * visibility chip, ordering, or automation filter. A task edit can move a row- * across each of those boundaries at once (reassigning, sharing, touching its- * `updatedAt`, attaching a schedule), so refresh invalidates by key root- * instead of enumerating variants.- */-export const isTaskListKey = (key: unknown): boolean =>- Array.isArray(key) && key[0] === 'task:list';-export const isScheduledTaskListKey = (key: unknown): boolean =>Array.isArray(key) && key[0] === 'task:scheduledList';@@ -345,74 +335,12 @@ export const goalKeys = {};export const taskKeys = {- detail: def('task:detail', (taskId: string) => ['task:detail', taskId]),- groupList: def(- 'task:groupList',- (- agentKey: string | undefined,- visibility: 'all' | 'private' | 'workspace' = 'all',- groupBy: 'assignee' | 'member' | 'priority' | 'status' = 'status',- excludeStatuses?: string,- projectId?: string,- automated?: boolean,- ) => {- const hasBoardFilter = groupBy !== 'status' || excludeStatuses !== undefined;- const key = hasBoardFilter- ? projectId- ? ['task:groupList', agentKey, visibility, groupBy, excludeStatuses, projectId]- : ['task:groupList', agentKey, visibility, groupBy, excludeStatuses]- : projectId- ? ['task:groupList', agentKey, visibility, projectId]- : ['task:groupList', agentKey, visibility];-- return automated === undefined ? key : [...key, { automated }];- },- ),/*** The home rail's cross-agent goal roll-up. Scoped by cache scope like the* other home feeds β goals are workspace rows, so a list left over from the* previous workspace holds ids this one cannot open.*/homeGoals: def('task:homeGoals', (scope: string) => ['task:homeGoals', scope]),- list: def(- 'task:list',- (- agentKey: string | undefined,- visibility: 'all' | 'private' | 'workspace' = 'all',- // Part of the key, not a detail: Home orders by activity while the Tasks- // page orders by creation, and they read the same store field.- orderBy: 'createdAt' | 'updatedAt' = 'createdAt',- projectId?: string,- // Same reasoning as `orderBy`: Home's recent block excludes live- // automation and finished statuses server-side while the Tasks page- // fetches everything, and a shared entry would serve one surface the- // other's filter. Folded into one trailing slot (appended only when a- // filter is actually set) so unfiltered keys keep their shape.- // `complete` marks the every-page walk the Tasks list view does; the- // kanban view and Home read a single page and must not be served (or- // serve) the walked list from a shared entry.- filters?: { automated?: boolean; complete?: boolean; statuses?: readonly string[] },- ) => {- const key = projectId- ? ['task:list', agentKey, visibility, orderBy, projectId]- : ['task:list', agentKey, visibility, orderBy];- const automated = filters?.automated;- const complete = filters?.complete ? true : undefined;- // Order-insensitive: the same status set must hash to the same key.- const statuses = filters?.statuses?.length- ? [...filters.statuses].sort().join(',')- : undefined;- if (automated === undefined && complete === undefined && statuses === undefined) return key;- return [- ...key,- {- ...(automated === undefined ? {} : { automated }),- ...(complete === undefined ? {} : { complete }),- ...(statuses === undefined ? {} : { statuses }),- },- ];- },- ),/*** 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 βdiff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex d92e42f25e7..132249938b5 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -423,10 +423,14 @@ export class StreamingExecutorActionImpl {let contextPrompt: string | undefined;if (viewedTask.type === 'list') {+ const viewedList = taskState.activeTaskListKey+ ? taskState.taskListMap[taskState.activeTaskListKey]+ : undefined;+ const tasks = viewedList?.items ?? [];contextPrompt = buildTaskListPrompt({defaultAssigneeAgentId: operation.context.defaultTaskAssigneeAgentId,- tasks: taskState.tasks,- total: taskState.tasksTotal || taskState.tasks.length,+ tasks,+ total: viewedList?.total || tasks.length,});} else {const detail = taskState.taskDetailMap[viewedTask.taskId];diff --git a/src/store/task/selectors/listSelectors.test.ts b/src/store/task/selectors/listSelectors.test.tsindex d7dc71f15a4..5778220b2a0 100644--- a/src/store/task/selectors/listSelectors.test.ts+++ b/src/store/task/selectors/listSelectors.test.ts@@ -25,119 +25,35 @@ describe('taskListSelectors', () => {});});- describe('kanban column selectors (from taskGroups)', () => {- const taskGroups = [- {- hasMore: false,- key: 'backlog',- limit: 50,- offset: 0,- tasks: [{ identifier: 'T-1', status: 'backlog' }],- total: 1,+ describe('keyed collections', () => {+ const groups = [{ key: 'backlog', tasks: [{ identifier: 'T-1' }], total: 1 }] as any[];+ const state = createState({+ taskGroupListMap: { board: { groupBy: 'status', groups } },+ taskListMap: {+ empty: { items: [], total: 0 },+ home: { items: [{ identifier: 'T-1' }] as any[], total: 42 },},- {- hasMore: false,- key: 'running',- limit: 50,- offset: 0,- tasks: [- { identifier: 'T-2', status: 'running' },- { identifier: 'T-7', status: 'running' },- ],- total: 2,- },- {- hasMore: false,- key: 'needsInput',- limit: 50,- offset: 0,- tasks: [- { identifier: 'T-3', status: 'paused' },- { identifier: 'T-4', status: 'failed' },- ],- total: 2,- },- {- hasMore: false,- key: 'done',- limit: 50,- offset: 0,- tasks: [{ identifier: 'T-5', status: 'completed' }],- total: 1,- },- ] as any[];-- const state = createState({ taskGroups });-- it('should return backlog tasks from group', () => {- const result = taskListSelectors.backlogTasks(state);- expect(result).toHaveLength(1);- expect(result[0].identifier).toBe('T-1');- });-- it('should return running tasks from group', () => {- const result = taskListSelectors.runningTasks(state);- expect(result).toHaveLength(2);- });-- it('should return needsInput tasks from group', () => {- const result = taskListSelectors.needsInputTasks(state);- expect(result).toHaveLength(2);- expect(result.map((t: any) => t.identifier)).toEqual(['T-3', 'T-4']);});- it('should return done tasks from group', () => {- const result = taskListSelectors.doneTasks(state);- expect(result).toHaveLength(1);- expect(result[0].identifier).toBe('T-5');- });-- it('should return empty array for missing group', () => {- const emptyState = createState({ taskGroups: [] });- expect(taskListSelectors.backlogTasks(emptyState)).toEqual([]);- expect(taskListSelectors.runningTasks(emptyState)).toEqual([]);- });-- it('should return group by key', () => {- const group = taskListSelectors.taskGroupByKey('running')(state);- expect(group?.total).toBe(2);- expect(group?.hasMore).toBe(false);- });- });-- describe('isListEmpty', () => {- it('should return false when not initialized', () => {- expect(taskListSelectors.isListEmpty(createState())).toBe(false);- });-- it('should return true when initialized with empty list', () => {- expect(taskListSelectors.isListEmpty(createState({ isTaskListInit: true, tasks: [] }))).toBe(- true,- );- });-- it('should return false when initialized with tasks', () => {- expect(- taskListSelectors.isListEmpty(- createState({ isTaskListInit: true, tasks: [{ identifier: 'T-1' }] as any[] }),- ),- ).toBe(false);- });- });-- describe('basic selectors', () => {- it('should return isTaskListInit', () => {- expect(taskListSelectors.isTaskListInit(createState({ isTaskListInit: true }))).toBe(true);+ it("reads one list by its query key, never another surface's rows", () => {+ expect(taskListSelectors.taskList('home')(state)).toHaveLength(1);+ expect(taskListSelectors.taskListTotal('home')(state)).toBe(42);+ expect(taskListSelectors.taskList('tasks-page')(state)).toEqual([]);+ expect(taskListSelectors.taskList(undefined)(state)).toEqual([]);});- it('should return taskListTotal', () => {- expect(taskListSelectors.taskListTotal(createState({ tasksTotal: 42 }))).toBe(42);+ it('settles per query key', () => {+ expect(taskListSelectors.isTaskListInit('home')(state)).toBe(true);+ expect(taskListSelectors.isTaskListInit('tasks-page')(state)).toBe(false);+ expect(taskListSelectors.isTaskGroupListInit('board')(state)).toBe(true);+ expect(taskListSelectors.taskGroups('board')(state)).toBe(groups);+ expect(taskListSelectors.taskGroups('other')(state)).toEqual([]);});- it('should return isTaskGroupListInit', () => {- expect(- taskListSelectors.isTaskGroupListInit(createState({ isTaskGroupListInit: true })),- ).toBe(true);+ it('is empty only for a settled list without rows', () => {+ expect(taskListSelectors.isListEmpty('empty')(state)).toBe(true);+ expect(taskListSelectors.isListEmpty('home')(state)).toBe(false);+ expect(taskListSelectors.isListEmpty('tasks-page')(state)).toBe(false);});});});diff --git a/src/store/task/selectors/listSelectors.ts b/src/store/task/selectors/listSelectors.tsindex 2bcc9cd4282..8e3206f6fcc 100644--- a/src/store/task/selectors/listSelectors.ts+++ b/src/store/task/selectors/listSelectors.ts@@ -1,11 +1,24 @@import type { TaskStoreState } from '../initialState';import type { TaskGroupItem, TaskListItem } from '../slices/list/initialState';-const taskList = (s: TaskStoreState): TaskListItem[] => s.tasks;+const EMPTY_TASKS: TaskListItem[] = [];+const EMPTY_GROUPS: TaskGroupItem[] = [];-const taskListTotal = (s: TaskStoreState) => s.tasksTotal;+/**+ * Lists are keyed by their query (`queryKey` from `useFetchTaskList`), so two+ * surfaces fetching different lists never read each other's rows.+ */+const taskList =+ (queryKey?: string) =>+ (s: TaskStoreState): TaskListItem[] =>+ (queryKey && s.taskListMap[queryKey]?.items) || EMPTY_TASKS;-const isTaskListInit = (s: TaskStoreState) => s.isTaskListInit;+const taskListTotal = (queryKey?: string) => (s: TaskStoreState) =>+ (queryKey && s.taskListMap[queryKey]?.total) || 0;++/** The list has a value to show (from storage or the server). */+const isTaskListInit = (queryKey?: string) => (s: TaskStoreState) =>+ !!queryKey && !!s.taskListMap[queryKey];const listVisibility = (s: TaskStoreState) => s.listVisibility;@@ -21,36 +34,25 @@ const statusDisplayMap: Record<string, string> = {const getDisplayStatus = (status: string): string => statusDisplayMap[status] ?? status;-// ββ Kanban selectors (read from taskGroups, populated by groupList API) ββ--const taskGroups = (s: TaskStoreState): TaskGroupItem[] => s.taskGroups;--const isTaskGroupListInit = (s: TaskStoreState) => s.isTaskGroupListInit;--const taskGroupByKey = (key: string) => (s: TaskStoreState) =>- s.taskGroups.find((g) => g.key === key);--const backlogTasks = (s: TaskStoreState) => taskGroupByKey('backlog')(s)?.tasks ?? [];--const runningTasks = (s: TaskStoreState) => taskGroupByKey('running')(s)?.tasks ?? [];+// ββ Kanban selectors (keyed by `queryKey` from `useFetchTaskGroupList`) ββ-const needsInputTasks = (s: TaskStoreState) => taskGroupByKey('needsInput')(s)?.tasks ?? [];+const taskGroups =+ (queryKey?: string) =>+ (s: TaskStoreState): TaskGroupItem[] =>+ (queryKey && s.taskGroupListMap[queryKey]?.groups) || EMPTY_GROUPS;-const doneTasks = (s: TaskStoreState) => taskGroupByKey('done')(s)?.tasks ?? [];+const isTaskGroupListInit = (queryKey?: string) => (s: TaskStoreState) =>+ !!queryKey && !!s.taskGroupListMap[queryKey];-const isListEmpty = (s: TaskStoreState) => s.isTaskListInit && s.tasks.length === 0;+const isListEmpty = (queryKey?: string) => (s: TaskStoreState) =>+ isTaskListInit(queryKey)(s) && taskList(queryKey)(s).length === 0;export const taskListSelectors = {- backlogTasks,- doneTasks,getDisplayStatus,isListEmpty,isTaskGroupListInit,isTaskListInit,listVisibility,- needsInputTasks,- runningTasks,- taskGroupByKey,taskGroups,taskList,taskListTotal,diff --git a/src/store/task/slices/config/action.test.ts b/src/store/task/slices/config/action.test.tsindex 955e8e70446..f6fa1f8524a 100644--- a/src/store/task/slices/config/action.test.ts+++ b/src/store/task/slices/config/action.test.ts@@ -1,9 +1,12 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { cacheScope } from '@/libs/replica';import { taskService } from '@/services/task';import { useUserStore } from '@/store/user';import { useTaskStore } from '../../store';+import { taskDetailResource } from '../detail/projection';+import { taskDetailRefreshes } from '../detail/testUtils';vi.mock('@/services/task', () => ({taskService: {@@ -44,6 +47,42 @@ beforeEach(() => {});describe('TaskConfigSliceAction', () => {+ describe('persisting config-only saves', () => {+ const persisted = async (scope: string) =>+ (await taskDetailResource.storage!.get({ queryKey: 'T-1', scope }))?.data;++ const useScope = () => {+ const scope = `task-config-${crypto.randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ return scope;+ };++ it('persists a saved model change so a reload paints it', async () => {+ const scope = useScope();+ vi.mocked(taskService.updateConfig).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().updateTaskModelConfig('T-1', { model: 'gpt-x' });++ await vi.waitFor(async () =>+ expect((await persisted(scope))?.config).toMatchObject({ model: 'gpt-x' }),+ );+ vi.restoreAllMocks();+ });++ it('persists the automation mode once the toggle is saved', async () => {+ const scope = useScope();+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().setAutomationMode('T-1', 'heartbeat');++ await vi.waitFor(async () =>+ expect((await persisted(scope))?.automationMode).toBe('heartbeat'),+ );+ vi.restoreAllMocks();+ });+ });+describe('updateCheckpoint', () => {it('should optimistically update and call service', async () => {vi.mocked(taskService.updateCheckpoint).mockResolvedValue({ success: true } as any);@@ -84,7 +123,6 @@ describe('TaskConfigSliceAction', () => {});it('rolls back and marks the save failed when the PUT rejects', async () => {- const { mutate } = await import('@/libs/swr');const { toast } = await import('@lobehub/ui/base-ui');vi.mocked(taskService.updateCheckpoint).mockRejectedValue(new Error('fail'));@@ -97,23 +135,20 @@ describe('TaskConfigSliceAction', () => {});expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');expect(toast.error).toHaveBeenCalled();- const refreshes = vi- .mocked(mutate)- .mock.calls.filter((call) => Array.isArray(call[0]) && call[0][0] === 'task:detail');+ const refreshes = taskDetailRefreshes('T-1');expect(refreshes).toHaveLength(0);});});describe('updateReview', () => {it('should call service and refresh detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.updateReview).mockResolvedValue({ success: true } as any);const review = { enabled: true, rubrics: [] };await useTaskStore.getState().updateReview('T-1', review as any);expect(taskService.updateReview).toHaveBeenCalledWith({ id: 'T-1', review });- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});});@@ -205,7 +240,6 @@ describe('TaskConfigSliceAction', () => {describe('runReview', () => {it('should call service and refresh detail', async () => {- const { mutate } = await import('@/libs/swr');const mockResult = { overallScore: 85, passed: true };vi.mocked(taskService.runReview).mockResolvedValue({data: mockResult,@@ -215,7 +249,7 @@ describe('TaskConfigSliceAction', () => {const result = await useTaskStore.getState().runReview('T-1', { content: 'Test output' });expect(taskService.runReview).toHaveBeenCalledWith('T-1', { content: 'Test output' });- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);expect(result).toEqual({ data: mockResult, success: true });});@@ -230,7 +264,6 @@ describe('TaskConfigSliceAction', () => {describe('updateTaskModelConfig', () => {it('should call updateConfig with model/provider and never refetch', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.updateConfig).mockResolvedValue({ success: true } as any);await useTaskStore@@ -248,9 +281,7 @@ describe('TaskConfigSliceAction', () => {expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('saved');// A refresh here is an async write that could land after the user's next// run-location pick and replace it.- const refreshes = vi- .mocked(mutate)- .mock.calls.filter((call) => Array.isArray(call[0]) && call[0][0] === 'task:detail');+ const refreshes = taskDetailRefreshes('T-1');expect(refreshes).toHaveLength(0);});@@ -309,7 +340,6 @@ describe('TaskConfigSliceAction', () => {useTaskStore.getState().taskDetailMap[id].config?.execution as Record<string, unknown>;it('serializes rapid device + directory edits, keeps the last one, and never refetches', async () => {- const { mutate } = await import('@/libs/swr');const settlers: Array<() => void> = [];vi.mocked(taskService.updateConfig).mockImplementation(() =>@@ -365,9 +395,7 @@ describe('TaskConfigSliceAction', () => {workingDirectoryConfig: null,});- const refreshes = vi- .mocked(mutate)- .mock.calls.filter((call) => Array.isArray(call[0]) && call[0][0] === 'task:detail');+ const refreshes = taskDetailRefreshes('T-1');expect(refreshes).toHaveLength(0);});@@ -419,13 +447,12 @@ describe('TaskConfigSliceAction', () => {describe('updatePeriodicInterval', () => {it('should call update with heartbeatInterval and refresh detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);await useTaskStore.getState().updatePeriodicInterval('T-1', 600);expect(taskService.update).toHaveBeenCalledWith('T-1', { heartbeatInterval: 600 });- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});it('should send 0 when null to disable interval (automationMode untouched)', async () => {@@ -562,7 +589,6 @@ describe('TaskConfigSliceAction', () => {});it('serializes rapid toggles, applies optimistic state immediately, and never refreshes', async () => {- const { mutate } = await import('@/libs/swr');// Macrotask flush β drains the microtask queue, enough for// OptimisticEngine to resolve the previous PUT, run its post-await// steps, and synchronously kick off the next mutation's PUT.@@ -609,9 +635,7 @@ describe('TaskConfigSliceAction', () => {// Final store still matches the last click β no stale SWR refresh can// race-overwrite it back to schedule/heartbeat mid-stream.expect(useTaskStore.getState().taskDetailMap['T-1'].automationMode).toBe('schedule');- const refreshCalls = vi- .mocked(mutate)- .mock.calls.filter((c) => Array.isArray(c[0]) && c[0][0] === 'task:detail');+ const refreshCalls = taskDetailRefreshes('T-1');expect(refreshCalls).toHaveLength(0);});@@ -772,7 +796,6 @@ describe('TaskConfigSliceAction', () => {describe('updateSchedule', () => {it('mirrors pattern, timezone, and maxExecutions into the local detail and PUTs the flat shape', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);await useTaskStore.getState().updateSchedule('T-1', {@@ -794,9 +817,7 @@ describe('TaskConfigSliceAction', () => {scheduleTimezone: 'Asia/Shanghai',});// No SWR refresh β optimistic patch is the source of truth.- const refreshCalls = vi- .mocked(mutate)- .mock.calls.filter((c) => Array.isArray(c[0]) && c[0][0] === 'task:detail');+ const refreshCalls = taskDetailRefreshes('T-1');expect(refreshCalls).toHaveLength(0);});@@ -893,25 +914,23 @@ describe('TaskConfigSliceAction', () => {describe('resolveBrief', () => {it('should call service and refresh active detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.resolveBrief).mockResolvedValue({ success: true } as any);await useTaskStore.getState().resolveBrief('brief_1', { action: 'approve' });expect(taskService.resolveBrief).toHaveBeenCalledWith('brief_1', { action: 'approve' });- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});});describe('markBriefRead', () => {it('should call service and refresh active detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.markBriefRead).mockResolvedValue({ success: true } as any);await useTaskStore.getState().markBriefRead('brief_1');expect(taskService.markBriefRead).toHaveBeenCalledWith('brief_1');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});});});diff --git a/src/store/task/slices/config/action.ts b/src/store/task/slices/config/action.tsindex 06aa6ea7789..6610833c8f1 100644--- a/src/store/task/slices/config/action.ts+++ b/src/store/task/slices/config/action.ts@@ -136,6 +136,10 @@ export class TaskConfigSliceActionImpl {// failure β never leave the write looking idle.this.#get().internal_setTaskSaveStatus(id, 'failed');if (write.rethrow) throw error;+ } finally {+ // The engine patches `taskDetailMap` directly; settle what is shown+ // (saved value, or the rollback) into the persisted detail.+ this.#get().internal_persistTaskDetail(id);}};@@ -409,6 +413,8 @@ export class TaskConfigSliceActionImpl {} catch (error) {// engine already rolled the optimistic patches back; just log.console.error('[TaskStore] Failed to update automation mode:', error);+ } finally {+ this.#get().internal_persistTaskDetail(id);}};@@ -498,6 +504,8 @@ export class TaskConfigSliceActionImpl {} catch (error) {// engine already rolled the optimistic patches back; just log.console.error('[TaskStore] Failed to update schedule:', error);+ } finally {+ this.#get().internal_persistTaskDetail(id);}};}diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex f079404deff..6a87b79391c 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -4,14 +4,19 @@ import {toTaskExecutionConfigPatch,} from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cacheScope, createReplicaState } from '@/libs/replica';+import { useClientDataSWR } from '@/libs/swr';import { taskService } from '@/services/task';import { workService } from '@/services/work';import { taskDetailSelectors } from '@/store/task/selectors';import { useUserStore } from '@/store/user';import { useTaskStore } from '../../store';+import { taskDetailResource } from './projection';+import { taskDetailRefreshes } from './testUtils';vi.mock('@/services/task', () => ({taskService: {@@ -51,12 +56,148 @@ beforeEach(() => {isCreatingTask: false,isDeletingTask: false,taskDetailMap: {},+ taskDetailReplica: createReplicaState(),taskInstructionRevisionMap: {},taskSaveStatusMap: {},});});describe('TaskDetailSliceAction', () => {+ describe('task detail replica', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ const syncCall = () =>+ vi+ .mocked(useClientDataSWR)+ .mock.calls.find(([key]) => Array.isArray(key) && key[0] === 'replica:sync');++ it('polls while the task is in flight and stops once it settles', () => {+ vi.mocked(useClientDataSWR).mockReturnValue({ isValidating: false, mutate: vi.fn() } as any);+ useTaskStore.setState({+ taskDetailMap: { 'T-1': { identifier: 'T-1', status: 'running' } as any },+ });++ const { rerender } = renderHook(() => useTaskStore.getState().useFetchTaskDetail('T-1'));+ expect(syncCall()?.[2]).toMatchObject({ refreshInterval: 10_000 });++ vi.mocked(useClientDataSWR).mockClear();+ useTaskStore.setState({+ taskDetailMap: { 'T-1': { identifier: 'T-1', status: 'completed' } as any },+ });+ rerender();+ expect(syncCall()?.[2]).toMatchObject({ refreshInterval: 0 });+ });++ it('drops a cached detail once the server confirms the task is gone', () => {+ vi.mocked(useClientDataSWR).mockReturnValue({ isValidating: false, mutate: vi.fn() } as any);+ useTaskStore.setState({+ taskDetailMap: {+ 'T-1': { identifier: 'T-1', status: 'backlog' } as any,+ 'T-2': { identifier: 'T-2', status: 'backlog' } as any,+ },+ });+ renderHook(() => {+ useTaskStore.getState().useFetchTaskDetail('T-1');+ useTaskStore.getState().useFetchTaskDetail('T-2');+ });+ const onErrorFor = (id: string) =>+ (+ vi+ .mocked(useClientDataSWR)+ .mock.calls.find(+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[4] === id,+ )?.[2] as {+ onError: (error: unknown) => void;+ }+ ).onError;++ onErrorFor('T-1')(+ Object.assign(new Error('Task not found: T-1'), { code: 'TASK_NOT_FOUND' }),+ );+ onErrorFor('T-2')(new Error('Failed to fetch'));++ // Deleted elsewhere β the cached copy goes; a transient failure keeps it.+ expect(useTaskStore.getState().taskDetailMap['T-1']).toBeUndefined();+ expect(useTaskStore.getState().taskDetailMap['T-2']).toBeDefined();+ });++ it('stores a raw-id lookup under both the raw id and the identifier', async () => {+ vi.mocked(taskService.getDetail).mockResolvedValue({+ data: { identifier: 'T-7', instruction: 'x' },+ } as any);++ await useTaskStore.getState().fetchTaskDetail('task_raw');++ const { taskDetailMap } = useTaskStore.getState();+ expect(taskDetailMap.task_raw).toMatchObject({ identifier: 'T-7' });+ expect(taskDetailMap['T-7']).toMatchObject({ identifier: 'T-7' });+ });++ it('restores the persisted row when a delete fails', async () => {+ const scope = `task-delete-${crypto.randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ const detail = { identifier: 'T-9', name: 'Keep me' } as any;+ useTaskStore.getState().internal_dispatchTaskDetail({+ id: 'T-9',+ type: 'setTaskDetail',+ value: detail,+ });+ await taskDetailResource.storage!.set(+ { queryKey: 'T-9', scope },+ { data: detail, updatedAt: 1 },+ );+ vi.mocked(taskService.delete).mockRejectedValue(new Error('offline'));++ await expect(useTaskStore.getState().deleteTask('T-9')).rejects.toThrow('offline');++ expect(useTaskStore.getState().taskDetailMap['T-9']).toMatchObject({ name: 'Keep me' });+ // Storage writes are queued; wait for the restored row to land.+ await vi.waitFor(async () =>+ expect(+ (await taskDetailResource.storage!.get({ queryKey: 'T-9', scope }))?.data,+ ).toMatchObject({ name: 'Keep me' }),+ );+ });++ it('persists a detail edit once the server saved it', async () => {+ const scope = `task-update-${crypto.randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ useTaskStore.getState().internal_dispatchTaskDetail({+ id: 'T-3',+ type: 'setTaskDetail',+ value: { identifier: 'T-3', name: 'Before' } as any,+ });+ vi.mocked(taskService.update).mockResolvedValue({} as any);++ await useTaskStore.getState().updateTask('T-3', { name: 'After' });++ await vi.waitFor(async () =>+ expect(+ (await taskDetailResource.storage!.get({ queryKey: 'T-3', scope }))?.data,+ ).toMatchObject({ name: 'After' }),+ );+ });++ it('keeps optimistic detail edits out of the persisted row', async () => {+ const scope = `task-detail-${crypto.randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);++ useTaskStore.getState().internal_dispatchTaskDetail({+ id: 'T-1',+ type: 'setTaskDetail',+ value: { identifier: 'T-1', name: 'Draft' } as any,+ });++ expect(useTaskStore.getState().taskDetailMap['T-1']).toMatchObject({ name: 'Draft' });+ expect(await taskDetailResource.storage!.get({ queryKey: 'T-1', scope })).toBeUndefined();+ });+ });+describe('setActiveTaskId', () => {it('should set activeTaskId', () => {useTaskStore.getState().setActiveTaskId('T-1');@@ -489,7 +630,6 @@ describe('TaskDetailSliceAction', () => {});it('should propagate error, mark saveStatus failed, refresh, and toast on failure', async () => {- const { mutate } = await import('@/libs/swr');const { toast } = await import('@lobehub/ui/base-ui');useTaskStore.setState({taskDetailMap: {@@ -506,7 +646,7 @@ describe('TaskDetailSliceAction', () => {// The failure must surface as `failed` (never `idle`) so the save hint// shows an error + Retry instead of masquerading as a clean state.expect(useTaskStore.getState().taskSaveStatusMap['T-1']).toBe('failed');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);expect(toast.error).toHaveBeenCalled();});@@ -588,7 +728,6 @@ describe('TaskDetailSliceAction', () => {});it('should refresh the cached parent on failure when updating from a subtask detail page', async () => {- const { mutate } = await import('@/libs/swr');useTaskStore.setState({activeTaskId: 'T-sub',taskDetailMap: {@@ -608,8 +747,8 @@ describe('TaskDetailSliceAction', () => {useTaskStore.getState().updateTask('T-sub', { assigneeAgentId: 'agent-x' }),).rejects.toThrow('fail');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-sub']);- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-parent']);+ expect(taskDetailRefreshes('T-sub')).not.toHaveLength(0);+ expect(taskDetailRefreshes('T-parent')).not.toHaveLength(0);});it('should not show error when update succeeds but cache refresh fails', async () => {@@ -631,7 +770,6 @@ describe('TaskDetailSliceAction', () => {});it('should refresh list and affected details when reparenting', async () => {- const { mutate } = await import('@/libs/swr');useTaskStore.setState({activeTaskId: 'T-sub',taskDetailMap: {@@ -654,9 +792,9 @@ describe('TaskDetailSliceAction', () => {expect(taskService.update).toHaveBeenCalledWith('T-sub', { parentTaskId: 'T-new-parent' });expect(useTaskStore.getState().taskDetailMap['T-sub']).not.toHaveProperty('parentTaskId');expect(refreshTaskList).toHaveBeenCalled();- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-sub']);- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-parent']);- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-new-parent']);+ expect(taskDetailRefreshes('T-sub')).not.toHaveLength(0);+ expect(taskDetailRefreshes('T-parent')).not.toHaveLength(0);+ expect(taskDetailRefreshes('T-new-parent')).not.toHaveLength(0);});it('should refresh the list after changing priority', async () => {@@ -670,7 +808,6 @@ describe('TaskDetailSliceAction', () => {});it('should refresh the parent that was patched even if activeTaskId changes mid-flight', async () => {- const { mutate } = await import('@/libs/swr');useTaskStore.setState({activeTaskId: 'T-parent',taskDetailMap: {@@ -692,8 +829,8 @@ describe('TaskDetailSliceAction', () => {useTaskStore.getState().updateTask('T-sub', { assigneeAgentId: 'agent-x' }),).rejects.toThrow('fail');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-sub']);- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-parent']);+ expect(taskDetailRefreshes('T-sub')).not.toHaveLength(0);+ expect(taskDetailRefreshes('T-parent')).not.toHaveLength(0);});it('should scope save status per task so a failure does not leak across navigation', async () => {@@ -803,25 +940,23 @@ describe('TaskDetailSliceAction', () => {describe('addComment', () => {it('should call service and refresh detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.addComment).mockResolvedValue({ success: true } as any);await useTaskStore.getState().addComment('T-1', 'Nice work');expect(taskService.addComment).toHaveBeenCalledWith('T-1', 'Nice work', undefined);- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});});describe('addDependency', () => {it('should call service and refresh detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.addDependency).mockResolvedValue({ success: true } as any);await useTaskStore.getState().addDependency('T-1', 'T-2', 'blocks');expect(taskService.addDependency).toHaveBeenCalledWith('T-1', 'T-2', 'blocks');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});it('should propagate error from service', async () => {@@ -835,19 +970,17 @@ describe('TaskDetailSliceAction', () => {describe('removeDependency', () => {it('should call service and refresh detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.removeDependency).mockResolvedValue({ success: true } as any);await useTaskStore.getState().removeDependency('T-1', 'T-2');expect(taskService.removeDependency).toHaveBeenCalledWith('T-1', 'T-2');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});});describe('unpinDocument', () => {it('should refresh source task and active task when they differ', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.unpinDocument).mockResolvedValue({ success: true } as any);// Detail page is open at parent identifier; doc is owned by a child DB id.@@ -856,8 +989,8 @@ describe('TaskDetailSliceAction', () => {await useTaskStore.getState().unpinDocument('task_child', 'doc_1');expect(taskService.unpinDocument).toHaveBeenCalledWith('task_child', 'doc_1');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'task_child']);- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('task_child')).not.toHaveLength(0);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});it('should not double-refresh when source task equals active task', async () => {@@ -869,7 +1002,7 @@ describe('TaskDetailSliceAction', () => {await useTaskStore.getState().unpinDocument('T-1', 'doc_1');expect(mutate).toHaveBeenCalledTimes(1);- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});});diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 829942b5b48..a66467b0047 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -8,8 +8,9 @@ import { toast } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';import { t } from 'i18next';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { goalKeys, taskKeys } from '@/libs/swr/keys';+import { createReplicaSlice, recordLens } from '@/libs/replica';+import { mutate } from '@/libs/swr';+import { goalKeys } from '@/libs/swr/keys';import { taskService } from '@/services/task';import { workService } from '@/services/work';import type { StoreSetter } from '@/store/types';@@ -27,6 +28,7 @@ import {buildOptimisticCommentActivity,buildOptimisticPropertyActivity,} from './optimisticActivity';+import { taskDetailResource } from './projection';import type { TaskDetailDispatch } from './reducer';import { findSubtaskParentId, taskDetailReducer } from './reducer';@@ -119,11 +121,24 @@ export const createTaskDetailSlice = (set: Setter, get: () => TaskStore, _api?:export class TaskDetailSliceActionImpl {readonly #get: () => TaskStore;readonly #set: Setter;+ readonly #detail;constructor(set: Setter, get: () => TaskStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#detail = createReplicaSlice(taskDetailResource, {+ actionPrefix: 'taskDetail',+ // Writes the entry (and its identifier alias) through+ // `internal_dispatchTaskDetail`, which also tracks instruction revisions;+ // the sync then confirms and persists the same value.+ fetcher: (id) => this.fetchTaskDetail(id),+ get,+ merge: (incoming, confirmed) => (isEqual(incoming, confirmed) ? undefined : incoming),+ set,+ stateKey: 'taskDetailReplica',+ view: recordLens<TaskStore, TaskDetailData>('taskDetailMap'),+ });}// ββ Public Actions ββ@@ -320,13 +335,9 @@ export class TaskDetailSliceActionImpl {}return result.data ?? null;} catch (error) {- if (snapshot) {- this.internal_dispatchTaskDetail({- id: identifier,- type: 'setTaskDetail',- value: snapshot,- });- }+ // The optimistic delete also dropped the persisted row; restore the+ // confirmed snapshot through `replace` so it is persisted again.+ if (snapshot) this.#detail.replace(identifier, snapshot);throw error;} finally {this.#set({ isDeletingTask: false }, false, 'deleteTask/end');@@ -556,6 +567,11 @@ export class TaskDetailSliceActionImpl {setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),});+ // Saved: the edited detail is now the server's value, so a reload must+ // paint it rather than the pre-edit snapshot.+ this.internal_persistTaskDetail(id);+ if (patchedParentId) this.internal_persistTaskDetail(patchedParentId);+if (assigneeAgentId !== undefined ||assigneeUserId !== undefined ||@@ -586,11 +602,17 @@ export class TaskDetailSliceActionImpl {return hasInFlightActivity(detail);});- return useClientDataSWR(- taskId ? taskKeys.detail(taskId) : null,- async ([, id]: [string, string]) => this.fetchTaskDetail(id),- { refreshInterval: shouldPoll ? TASK_DETAIL_POLL_INTERVAL : 0 },- );+ const sync = this.#detail.useSync(taskId, {+ // A resolved not-found is definitive (the task was deleted elsewhere):+ // drop the cached copy so the page can settle on its 404. Transient+ // failures keep the cached detail on screen.+ onError: (error) => {+ if (taskId && (error as { code?: string } | undefined)?.code === 'TASK_NOT_FOUND')+ this.internal_dispatchTaskDetail({ id: taskId, type: 'deleteTaskDetail' });+ },+ refreshInterval: shouldPoll ? TASK_DETAIL_POLL_INTERVAL : 0,+ });+ return { ...sync, mutate: sync.revalidate };};// ββ Internal Actions ββ@@ -606,6 +628,11 @@ export class TaskDetailSliceActionImpl {);};+ /**+ * Apply a detail change (subtasks are patched inside their parent's entry+ * too) and write every changed entry through the replica. In memory only:+ * the confirmed server value is persisted by the detail sync.+ */internal_dispatchTaskDetail = (payload: TaskDetailDispatch,options?: { instructionSource?: 'external' },@@ -620,18 +647,18 @@ export class TaskDetailSliceActionImpl {payload.type === 'deleteTaskDetail' &&state.taskInstructionRevisionMap[payload.id] !== undefined;- if (- isEqual(nextMap, currentMap) &&- !shouldIncrementInstructionRevision &&- !shouldDeleteInstructionRevision- ) {- return;+ if (payload.type === 'deleteTaskDetail') {+ if (currentMap[payload.id]) this.#detail.remove(payload.id);+ } else {+ for (const id of new Set([...Object.keys(currentMap), ...Object.keys(nextMap)])) {+ if (currentMap[id] === nextMap[id] || isEqual(currentMap[id], nextMap[id])) continue;+ this.#detail.update(id, () => nextMap[id], { persist: false });+ }}if (shouldIncrementInstructionRevision) {this.#set({- taskDetailMap: nextMap,taskInstructionRevisionMap: {...state.taskInstructionRevisionMap,[payload.id]: (state.taskInstructionRevisionMap[payload.id] ?? 0) + 1,@@ -640,25 +667,27 @@ export class TaskDetailSliceActionImpl {false,`internal_dispatchTaskDetail/${payload.type}`,);- return;- }-- if (shouldDeleteInstructionRevision) {+ } else if (shouldDeleteInstructionRevision) {const taskInstructionRevisionMap = { ...state.taskInstructionRevisionMap };delete taskInstructionRevisionMap[payload.id];this.#set(- { taskDetailMap: nextMap, taskInstructionRevisionMap },+ { taskInstructionRevisionMap },false,`internal_dispatchTaskDetail/${payload.type}`,);- return;}+ };- this.#set({ taskDetailMap: nextMap }, false, `internal_dispatchTaskDetail/${payload.type}`);+ /**+ * Persist a task's detail as it is shown now β called once a save settles+ * (committed, or rolled back), since edits stay in memory while in flight.+ */+ internal_persistTaskDetail = (id: string): void => {+ this.#detail.update(id, (detail) => detail && { ...detail });};internal_refreshTaskDetail = async (id: string): Promise<void> => {- await mutate(taskKeys.detail(id));+ await this.#detail.revalidate(id);};}diff --git a/src/store/task/slices/detail/initialState.ts b/src/store/task/slices/detail/initialState.tsindex 19cb05b4558..f7484eaa51e 100644--- a/src/store/task/slices/detail/initialState.ts+++ b/src/store/task/slices/detail/initialState.ts@@ -1,5 +1,6 @@import type { TaskDetailData } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';import { type SaveStatus } from '@/types/saveState';export interface TaskDetailSliceState {@@ -15,6 +16,8 @@ export interface TaskDetailSliceState {isCreatingTask: boolean;isDeletingTask: boolean;taskDetailMap: Record<string, TaskDetailData>;+ /** Replica bookkeeping of `taskDetailMap` (its view). */+ taskDetailReplica: ReplicaState<TaskDetailData>;/*** Increments only when an authoritative source outside the mounted task editor* changes its persisted instruction snapshot. The editor uses this as an@@ -31,6 +34,7 @@ export const initialTaskDetailSliceState: TaskDetailSliceState = {isCreatingTask: false,isDeletingTask: false,taskDetailMap: {},+ taskDetailReplica: createReplicaState(),taskInstructionRevisionMap: {},taskSaveStatusMap: {},};diff --git a/src/store/task/slices/detail/projection.ts b/src/store/task/slices/detail/projection.tsnew file mode 100644index 00000000000..45c0784048c--- /dev/null+++ b/src/store/task/slices/detail/projection.ts@@ -0,0 +1,15 @@+import type { TaskDetailData } from '@lobechat/types';++import { defineReplica } from '@/libs/replica';++/**+ * One task detail per entry, keyed by the id it was opened with β the+ * identifier (`T-12`) or a raw row id (`task_xxx`); a raw-id fetch also writes+ * the identifier entry.+ */+export const taskDetailResource = defineReplica<string, TaskDetailData>({+ key: (id) => id,+ name: 'taskDetail',+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/task/slices/detail/testUtils.ts b/src/store/task/slices/detail/testUtils.tsnew file mode 100644index 00000000000..456b9e58f21--- /dev/null+++ b/src/store/task/slices/detail/testUtils.ts@@ -0,0 +1,23 @@+import { vi } from 'vitest';++import { cacheScope, replicaKeys } from '@/libs/replica';+import { mutate } from '@/libs/swr';++import { taskDetailResource } from './projection';++/**+ * Revalidations of one task detail's sync, as seen by a test that mocks+ * `@/libs/swr`'s `mutate` (the replica driver revalidates through it).+ */+export const taskDetailRefreshes = (id: string) => {+ const key = replicaKeys.sync(+ taskDetailResource.name,+ taskDetailResource.version,+ cacheScope.get(),+ id,+ id,+ );+ return vi+ .mocked(mutate)+ .mock.calls.filter(([match]) => typeof match === 'function' && (match as any)(key));+};diff --git a/src/store/task/slices/lifecycle/action.test.ts b/src/store/task/slices/lifecycle/action.test.tsindex 9897fdbf7bc..ecc36fb8f98 100644--- a/src/store/task/slices/lifecycle/action.test.ts+++ b/src/store/task/slices/lifecycle/action.test.ts@@ -1,9 +1,17 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { cacheScope, createReplicaState, REPLICA_INDEX_KEY } from '@/libs/replica';import { taskService } from '@/services/task';import { useUserStore } from '@/store/user';import { useTaskStore } from '../../store';+import { taskDetailRefreshes } from '../detail/testUtils';+import {+ taskGroupListQueryKey,+ taskGroupListResource,+ taskListQueryKey,+ taskListResource,+} from '../list/projection';vi.mock('@/services/task', () => ({taskService: {@@ -25,14 +33,23 @@ beforeEach(() => {vi.clearAllMocks();useTaskStore.setState({activeTaskId: 'T-1',- listGroupBy: 'status',- listGroupExcludeStatuses: undefined,taskDetailMap: { 'T-1': { ...mockDetail } },- taskGroups: [],- tasks: [],+ taskGroupListMap: {},+ taskGroupListReplica: createReplicaState(),+ taskListMap: {},+ taskListReplica: createReplicaState(),});});+/** One loaded list (`list`) and one loaded board (`board`) holding the task. */+const seedCollections = (groups: any[], tasks: any[], groupBy = 'status') =>+ useTaskStore.setState({+ taskGroupListMap: { board: { groupBy: groupBy as any, groups } },+ taskListMap: { list: { items: tasks, total: tasks.length } },+ });+const listTasks = (state = useTaskStore.getState()) => state.taskListMap.list.items;+const boardGroups = (state = useTaskStore.getState()) => state.taskGroupListMap.board.groups;+describe('TaskLifecycleSliceAction', () => {describe('runTask', () => {it('should optimistically set status to running and call service', async () => {@@ -59,12 +76,11 @@ describe('TaskLifecycleSliceAction', () => {});it('should refresh detail on error', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.run).mockRejectedValue(new Error('fail'));await useTaskStore.getState().runTask('T-1');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});it('should surface the run failure when the caller requires it', async () => {@@ -132,22 +148,24 @@ describe('TaskLifecycleSliceAction', () => {});it('should immediately synchronize list and kanban collections', async () => {- useTaskStore.setState({- taskGroups: [+ seedCollections(+ [{ key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },{ key: 'done', tasks: [], total: 0 },- ] as any,- tasks: [{ identifier: 'T-1', status: 'backlog' }] as any,- });+ ],+ [{ identifier: 'T-1', status: 'backlog' }],+ );vi.mocked(taskService.updateStatus).mockImplementation(async () => {const state = useTaskStore.getState();- expect(state.tasks.find((task) => task.identifier === 'T-1')?.status).toBe('completed');- expect(state.taskGroups.find((group) => group.key === 'backlog')).toMatchObject({+ expect(listTasks(state).find((task) => task.identifier === 'T-1')?.status).toBe(+ 'completed',+ );+ expect(boardGroups(state).find((group) => group.key === 'backlog')).toMatchObject({tasks: [],total: 0,});- expect(state.taskGroups.find((group) => group.key === 'done')).toMatchObject({+ expect(boardGroups(state).find((group) => group.key === 'done')).toMatchObject({tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],total: 1,});@@ -159,20 +177,20 @@ describe('TaskLifecycleSliceAction', () => {});it('should preserve assignee grouping when a task status changes', async () => {- useTaskStore.setState({- listGroupBy: 'assignee',- taskGroups: [+ seedCollections(+ [{assigneeAgentId: 'agent-1',key: 'assignee:agent-1',tasks: [{ assigneeAgentId: 'agent-1', identifier: 'T-1', status: 'backlog' }],total: 1,},- ] as any,- tasks: [{ assigneeAgentId: 'agent-1', identifier: 'T-1', status: 'backlog' }] as any,- });+ ],+ [{ assigneeAgentId: 'agent-1', identifier: 'T-1', status: 'backlog' }],+ 'assignee',+ );vi.mocked(taskService.updateStatus).mockImplementation(async () => {- expect(useTaskStore.getState().taskGroups[0]).toMatchObject({+ expect(boardGroups()[0]).toMatchObject({key: 'assignee:agent-1',tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],total: 1,@@ -184,13 +202,13 @@ describe('TaskLifecycleSliceAction', () => {});it('should roll list and kanban collections back when the status update fails', async () => {- useTaskStore.setState({- taskGroups: [+ seedCollections(+ [{ key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },{ key: 'done', tasks: [], total: 0 },- ] as any,- tasks: [{ identifier: 'T-1', status: 'backlog' }] as any,- });+ ],+ [{ identifier: 'T-1', status: 'backlog' }],+ );vi.mocked(taskService.updateStatus).mockRejectedValue(new Error('fail'));await expect(useTaskStore.getState().updateTaskStatus('T-1', 'completed')).rejects.toThrow(@@ -198,26 +216,55 @@ describe('TaskLifecycleSliceAction', () => {);const state = useTaskStore.getState();- expect(state.tasks.find((task) => task.identifier === 'T-1')?.status).toBe('backlog');- expect(state.taskGroups.find((group) => group.key === 'backlog')).toMatchObject({+ expect(listTasks(state).find((task) => task.identifier === 'T-1')?.status).toBe('backlog');+ expect(boardGroups(state).find((group) => group.key === 'backlog')).toMatchObject({tasks: [expect.objectContaining({ identifier: 'T-1', status: 'backlog' })],total: 1,});- expect(state.taskGroups.find((group) => group.key === 'done')).toMatchObject({+ expect(boardGroups(state).find((group) => group.key === 'done')).toMatchObject({tasks: [],total: 0,});});+ it('should put a card back in its original slot when the status update fails', async () => {+ seedCollections(+ [+ {+ key: 'backlog',+ tasks: [+ { identifier: 'T-4', status: 'backlog' },+ { identifier: 'T-1', status: 'backlog' },+ { identifier: 'T-2', status: 'backlog' },+ ],+ total: 3,+ },+ { key: 'done', tasks: [], total: 0 },+ ],+ [{ identifier: 'T-1', status: 'backlog' }],+ );+ vi.mocked(taskService.updateStatus).mockRejectedValue(new Error('fail'));++ await expect(useTaskStore.getState().updateTaskStatus('T-1', 'completed')).rejects.toThrow(+ 'fail',+ );++ expect(boardGroups()[0].tasks.map((task: any) => task.identifier)).toEqual([+ 'T-4',+ 'T-1',+ 'T-2',+ ]);+ });+it('should preserve the committed status when cache refreshes fail', async () => {const { mutate } = await import('@/libs/swr');- useTaskStore.setState({- taskGroups: [+ seedCollections(+ [{ key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },{ key: 'done', tasks: [], total: 0 },- ] as any,- tasks: [{ identifier: 'T-1', status: 'backlog' }] as any,- });+ ],+ [{ identifier: 'T-1', status: 'backlog' }],+ );vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);vi.mocked(mutate).mockRejectedValueOnce(new Error('detail refresh failed'))@@ -229,23 +276,117 @@ describe('TaskLifecycleSliceAction', () => {);const state = useTaskStore.getState();- expect(state.tasks.find((task) => task.identifier === 'T-1')?.status).toBe('completed');- expect(state.taskGroups.find((group) => group.key === 'done')).toMatchObject({+ expect(listTasks(state).find((task) => task.identifier === 'T-1')?.status).toBe('completed');+ expect(boardGroups(state).find((group) => group.key === 'done')).toMatchObject({tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],total: 1,});});+ it('drops a task from a status-filtered list once it no longer matches, even if refresh fails', async () => {+ const { mutate } = await import('@/libs/swr');+ useTaskStore.setState({+ taskListMap: {+ recent: {+ items: [+ { identifier: 'T-1', status: 'running' },+ { identifier: 'T-2', status: 'running' },+ ] as any,+ statuses: ['running', 'paused'],+ total: 2,+ },+ },+ });+ vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);+ vi.mocked(mutate).mockRejectedValue(new Error('refresh failed'));++ await useTaskStore.getState().updateTaskStatus('T-1', 'completed');++ expect(useTaskStore.getState().taskListMap.recent).toMatchObject({+ items: [{ identifier: 'T-2' }],+ total: 1,+ });+ vi.mocked(mutate).mockReset();+ });++ it('drops a card that moves into a status the board hides, even if refresh fails', async () => {+ const { mutate } = await import('@/libs/swr');+ useTaskStore.setState({+ taskGroupListMap: {+ board: {+ excludeStatuses: ['canceled', 'completed'],+ groupBy: 'status',+ groups: [+ { key: 'running', tasks: [{ identifier: 'T-1', status: 'running' }], total: 1 },+ // The server still returns the hidden status's empty column.+ { key: 'done', tasks: [], total: 0 },+ ] as any,+ },+ },+ });+ vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);+ vi.mocked(mutate).mockRejectedValue(new Error('refresh failed'));++ await useTaskStore.getState().updateTaskStatus('T-1', 'completed');++ expect(useTaskStore.getState().taskGroupListMap.board.groups).toMatchObject([+ { key: 'running', tasks: [], total: 0 },+ { key: 'done', tasks: [], total: 0 },+ ]);+ vi.mocked(mutate).mockReset();+ });++ it('carries a committed status into persisted lists and boards that are not loaded', async () => {+ const scope = `task-status-${crypto.randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockReturnValue(scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ const listKey = taskListQueryKey({ visibility: 'all' });+ const boardKey = taskGroupListQueryKey({ groupBy: 'status', visibility: 'all' });+ const seed = async (resource: any, queryKey: string, data: unknown) => {+ await resource.storage.set({ queryKey, scope }, { data, updatedAt: 1 });+ await resource.storage.set(+ { queryKey: REPLICA_INDEX_KEY, scope },+ { data: [queryKey], updatedAt: 1 },+ );+ };+ await seed(taskListResource, listKey, {+ items: [{ identifier: 'T-1', status: 'backlog' }],+ total: 1,+ });+ await seed(taskGroupListResource, boardKey, {+ groupBy: 'status',+ groups: [+ { key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },+ { key: 'done', tasks: [], total: 0 },+ ],+ });+ vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);++ // Changed from the detail page: neither collection is in memory.+ await useTaskStore.getState().updateTaskStatus('T-1', 'completed');++ await vi.waitFor(async () => {+ const list = await taskListResource.storage!.get({ queryKey: listKey, scope });+ expect(list?.data.items[0].status).toBe('completed');+ const board = await taskGroupListResource.storage!.get({ queryKey: boardKey, scope });+ expect(board?.data.groups).toMatchObject([+ { key: 'backlog', tasks: [], total: 0 },+ { key: 'done', tasks: [{ identifier: 'T-1', status: 'completed' }], total: 1 },+ ]);+ });+ vi.restoreAllMocks();+ });+it('should not let an older failed request roll back a newer status', async () => {let rejectFirstRequest: (reason: Error) => void = () => {};- useTaskStore.setState({- taskGroups: [+ seedCollections(+ [{ key: 'backlog', tasks: [{ identifier: 'T-1', status: 'backlog' }], total: 1 },{ key: 'done', tasks: [], total: 0 },{ key: 'canceled', tasks: [], total: 0 },- ] as any,- tasks: [{ identifier: 'T-1', status: 'backlog' }] as any,- });+ ],+ [{ identifier: 'T-1', status: 'backlog' }],+ );vi.mocked(taskService.updateStatus).mockImplementationOnce(async () =>@@ -263,12 +404,12 @@ describe('TaskLifecycleSliceAction', () => {await expect(firstRequest).rejects.toThrow('first request failed');const state = useTaskStore.getState();- expect(state.tasks.find((task) => task.identifier === 'T-1')?.status).toBe('canceled');- expect(state.taskGroups.find((group) => group.key === 'canceled')).toMatchObject({+ expect(listTasks(state).find((task) => task.identifier === 'T-1')?.status).toBe('canceled');+ expect(boardGroups(state).find((group) => group.key === 'canceled')).toMatchObject({tasks: [expect.objectContaining({ identifier: 'T-1', status: 'canceled' })],total: 1,});- expect(state.taskGroups.find((group) => group.key === 'done')).toMatchObject({+ expect(boardGroups(state).find((group) => group.key === 'done')).toMatchObject({tasks: [],total: 0,});@@ -301,13 +442,12 @@ describe('TaskLifecycleSliceAction', () => {describe('cancelTopic', () => {it('should call service and refresh active detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.cancelTopic).mockResolvedValue({ success: true } as any);await useTaskStore.getState().cancelTopic('tpc_1');expect(taskService.cancelTopic).toHaveBeenCalledWith('tpc_1');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});it('should not refresh if no activeTaskId', async () => {@@ -324,13 +464,12 @@ describe('TaskLifecycleSliceAction', () => {describe('deleteTopic', () => {it('should call service and refresh active detail', async () => {- const { mutate } = await import('@/libs/swr');vi.mocked(taskService.deleteTopic).mockResolvedValue({ success: true } as any);await useTaskStore.getState().deleteTopic('tpc_1');expect(taskService.deleteTopic).toHaveBeenCalledWith('tpc_1');- expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);+ expect(taskDetailRefreshes('T-1')).not.toHaveLength(0);});});});diff --git a/src/store/task/slices/lifecycle/action.ts b/src/store/task/slices/lifecycle/action.tsindex 8112d046660..4ff7b76cef4 100644--- a/src/store/task/slices/lifecycle/action.ts+++ b/src/store/task/slices/lifecycle/action.ts@@ -13,21 +13,12 @@ import {appendOptimisticPropertyActivity,buildOptimisticPropertyActivity,} from '../detail/optimisticActivity';+import { taskGroupKeyByStatus } from '../list/projection';const log = debug('lobe-store:task-lifecycle');type Setter = StoreSetter<TaskStore>;-const taskGroupKeyByStatus: Record<TaskStatus, string> = {- backlog: 'backlog',- canceled: 'canceled',- completed: 'done',- failed: 'needsInput',- paused: 'needsInput',- running: 'running',- scheduled: 'running',-};-const isTaskStatus = (status: string | undefined): status is TaskStatus =>status !== undefined && status in taskGroupKeyByStatus;@@ -142,11 +133,7 @@ export class TaskLifecycleSliceActionImpl {this.#statusTransitionVersions.set(id, transitionVersion);const previousStatusCandidate =- this.#get().taskDetailMap[id]?.status ??- this.#get().tasks.find((task) => task.identifier === id)?.status ??- this.#get()- .taskGroups.flatMap((group) => group.tasks)- .find((task) => task.identifier === id)?.status;+ this.#get().taskDetailMap[id]?.status ?? this.#get().internal_findCollectionTask(id)?.status;const previousStatus = isTaskStatus(previousStatusCandidate)? previousStatusCandidate: undefined;@@ -183,7 +170,18 @@ export class TaskLifecycleSliceActionImpl {: {}),},});- this.#patchTaskCollectionsStatus(id, status);+ // Every loaded list and board shows the new status now (a status board+ // moves the card). A failed transition rolls them back exactly.+ const collections = this.#get().internal_beginCollectionTaskOptimistic(id, (task) => ({+ ...task,+ status,+ }));+ let collectionsSettled = false;+ const settleCollections = (action: 'commit' | 'rollback') => {+ if (collectionsSettled) return;+ collectionsSettled = true;+ collections[action]();+ };try {await runMutation(this.#set, this.#get, {@@ -194,9 +192,10 @@ export class TaskLifecycleSliceActionImpl {name: 'transitionStatus',onError: async (err) => {console.error(`[TaskStore] Failed to transition task to ${status}:`, err);+ // Only this transition's overlay goes: a newer one stays on top.+ settleCollections('rollback');if (this.#statusTransitionVersions.get(id) !== transitionVersion) return;- if (previousStatus) this.#patchTaskCollectionsStatus(id, previousStatus);// The transition did not happen, so its row must go even when the// server-truth refetch below cannot run (offline).if (statusRow) {@@ -227,6 +226,7 @@ export class TaskLifecycleSliceActionImpl {}},});+ settleCollections('commit');if (this.#statusTransitionVersions.get(id) !== transitionVersion) return;@@ -244,50 +244,12 @@ export class TaskLifecycleSliceActionImpl {}}} finally {+ settleCollections('rollback');if (this.#statusTransitionVersions.get(id) === transitionVersion) {this.#statusTransitionVersions.delete(id);}}};-- #patchTaskCollectionsStatus = (id: string, status: TaskStatus): void => {- const { listGroupBy, taskGroups, tasks } = this.#get();- const listTask = tasks.find((task) => task.identifier === id);- const groupedTask = taskGroups- .flatMap((group) => group.tasks)- .find((task) => task.identifier === id);- if (!listTask && !groupedTask) return;-- const nextTasks = listTask- ? tasks.map((item) => (item.identifier === id ? { ...item, status } : item))- : tasks;- const nextTaskGroups = groupedTask- ? listGroupBy === 'status'- ? taskGroups.map((group) => {- const targetGroupKey = taskGroupKeyByStatus[status];- const containsTask = group.tasks.some((item) => item.identifier === id);- const belongsToTarget = group.key === targetGroupKey;- const filteredTasks = group.tasks.filter((item) => item.identifier !== id);- const patchedGroupedTask = { ...groupedTask, status };-- return {- ...group,- tasks: belongsToTarget ? [...filteredTasks, patchedGroupedTask] : filteredTasks,- total: group.total - (containsTask ? 1 : 0) + (belongsToTarget ? 1 : 0),- };- })- : taskGroups.map((group) => ({- ...group,- tasks: group.tasks.map((item) => (item.identifier === id ? { ...item, status } : item)),- }))- : taskGroups;-- this.#set(- { taskGroups: nextTaskGroups, tasks: nextTasks },- false,- 'transitionStatus/patchTaskCollections',- );- };}export type TaskLifecycleSliceAction = Pick<diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.tsindex ad616ac011c..0b37b7fd2f1 100644--- a/src/store/task/slices/list/action.test.ts+++ b/src/store/task/slices/list/action.test.ts@@ -1,6 +1,8 @@-import { renderHook } from '@testing-library/react';+import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createReplicaState } from '@/libs/replica';+import { useTaskStore } from '../../store';// Mock task service@@ -14,206 +16,172 @@ vi.mock('@/services/task', () => ({// Mock SWRvi.mock('@/libs/swr', () => ({mutate: vi.fn(),- useClientDataSWR: vi.fn(),+ useClientDataSWR: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),}));beforeEach(() => {vi.clearAllMocks();useTaskStore.setState({- groupListQueryAutomated: undefined,- isTaskGroupListInit: false,- isTaskListInit: false,- listAgentId: undefined,- listGroupBy: 'status',- listGroupExcludeStatuses: undefined,- listQueryAutomated: undefined,- listQueryComplete: false,- listQueryVisibility: 'all',listVisibility: 'all',- taskGroups: [],- tasks: [],- tasksTotal: 0,+ taskGroupListMap: {},+ taskGroupListReplica: createReplicaState(),+ taskListMap: {},+ taskListReplica: createReplicaState(),});});-describe('TaskListSliceAction', () => {- describe('setListAgentId', () => {- it('should update listAgentId', () => {- useTaskStore.getState().setListAgentId('agt_1');- expect(useTaskStore.getState().listAgentId).toBe('agt_1');- });-- it('should clear listAgentId with undefined', () => {- useTaskStore.getState().setListAgentId('agt_1');- useTaskStore.getState().setListAgentId(undefined);- expect(useTaskStore.getState().listAgentId).toBeUndefined();- });- });+/** The replica network sync of a resource, as registered with the SWR driver. */+const syncCalls = async (name: 'taskGroupList' | 'taskList') => {+ const { useClientDataSWR } = await import('@/libs/swr');+ return vi+ .mocked(useClientDataSWR)+ .mock.calls.filter(+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === name,+ )+ .map(([key, fetcher]) => ({ fetcher: fetcher as () => Promise<any>, key: key as unknown[] }));+};+describe('TaskListSliceAction', () => {describe('refreshTaskList', () => {// 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 matches every `task:list` variant- // by key root instead of enumerating them.- it('invalidates every cached list variant by key root', async () => {+ // 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 () => {const { mutate } = await import('@/libs/swr');- useTaskStore.setState({- listAgentId: 'agt_1',- listQueryVisibility: 'private',- listVisibility: 'private',- });await useTaskStore.getState().refreshTaskList();- const matcher = vi+ const matchers = vi.mocked(mutate).mock.calls.map(([arg]) => arg)- .find((arg): arg is (key: unknown) => boolean => typeof arg === 'function');- expect(matcher).toBeDefined();- // The Tasks page's entry, Home's activity-ordered filtered entry, and a- // project-scoped entry all matchβ¦- expect(matcher!(['task:list', 'agt_1', 'private', 'createdAt'])).toBe(true);- expect(matcher!(['task:list', '__all__', 'all', 'updatedAt', { automated: false }])).toBe(- true,- );- expect(matcher!(['task:list', '__project__:p1', 'all', 'createdAt', 'p1'])).toBe(true);- // β¦while other task caches are refreshed through their own keys.- expect(matcher!(['task:groupList', 'agt_1', 'private'])).toBe(false);+ .filter((arg): arg is (key: unknown) => boolean => typeof arg === 'function');+ const matches = (key: unknown[]) => matchers.some((matcher) => matcher(key));+ 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);});});describe('useFetchTaskGroupList', () => {it('keys and requests assignee groups independently from status groups', async () => {- const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');- renderHook(() =>+ const { result } = renderHook(() => [useTaskStore.getState().useFetchTaskGroupList({allAgents: true,automated: false,excludeStatuses: ['completed', 'canceled'],groupBy: 'assignee',}),- );+ useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, automated: false }),+ ]);- expect(useClientDataSWR).toHaveBeenCalledWith(- [- 'task:groupList',- '__all__',- 'all',- 'assignee',- 'canceled,completed',- { automated: false },- ],- expect.any(Function),- expect.any(Object),- );- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => unknown;- await fetcher();+ expect(result.current[0].queryKey).not.toBe(result.current[1].queryKey);+ const [assignee] = await syncCalls('taskGroupList');+ await assignee.fetcher();expect(taskService.groupList).toHaveBeenCalledWith({assigneeAgentId: undefined,automated: false,- excludeStatuses: ['completed', 'canceled'],+ excludeStatuses: ['canceled', 'completed'],groupBy: 'assignee',projectId: undefined,+ scope: undefined,visibility: undefined,});});it('keys and requests the "My tasks" board apart from the all-agents board', async () => {- const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');- renderHook(() =>- useTaskStore.getState().useFetchTaskGroupList({- automated: false,- groupBy: 'status',- scope: 'assigned',- }),- );-- // Its own scope key, so the `assigned` / `created` sub-views and the- // all-agents board can never serve each other's groups.- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:groupList', '__mine__:assigned', 'all', { automated: false }],- expect.any(Function),- expect.any(Object),- );- expect(useTaskStore.getState().listAgentId).toBe('__mine__:assigned');+ const { result } = renderHook(() => [+ useTaskStore.getState().useFetchTaskGroupList({ automated: false, scope: 'assigned' }),+ useTaskStore.getState().useFetchTaskGroupList({ automated: false, scope: 'created' }),+ useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, automated: false }),+ ]);- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => unknown;- await fetcher();+ // The `assigned` / `created` sub-views and the all-agents board can never+ // serve each other's groups.+ expect(new Set(result.current.map((sync) => sync.queryKey)).size).toBe(3);+ const [assigned] = await syncCalls('taskGroupList');+ await assigned.fetcher();expect(taskService.groupList).toHaveBeenCalledWith(expect.objectContaining({ assigneeAgentId: undefined, scope: 'assigned' }),);});it('ignores the visibility chip on the "My tasks" board, like its list view does', async () => {- const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');// The chip is not offered inside "My tasks"; a value left over from the// ordinary tab must not narrow the board, or the list β board switch// would silently change the row set.useTaskStore.setState({ listVisibility: 'private' });- renderHook(() =>- useTaskStore.getState().useFetchTaskGroupList({ groupBy: 'status', scope: 'created' }),+ renderHook(() => useTaskStore.getState().useFetchTaskGroupList({ scope: 'created' }));++ const [board] = await syncCalls('taskGroupList');+ await board.fetcher();+ expect(taskService.groupList).toHaveBeenCalledWith(+ expect.objectContaining({ scope: 'created', visibility: undefined }),);+ });- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:groupList', '__mine__:created', 'all'],- expect.any(Function),- expect.any(Object),+ it('passes the ordinary-task automation filter through the kanban query', async () => {+ const { taskService } = await import('@/services/task');++ renderHook(() =>+ useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, automated: false }),);- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => unknown;- await fetcher();++ const [board] = await syncCalls('taskGroupList');+ await board.fetcher();expect(taskService.groupList).toHaveBeenCalledWith(- expect.objectContaining({ scope: 'created', visibility: undefined }),+ expect.objectContaining({ automated: false }),);});- it('resets a changed group query scope after render and gates stale data meanwhile', () => {- useTaskStore.setState({- isTaskGroupListInit: true,- listAgentId: '__all__',- listGroupBy: 'status',- listGroupExcludeStatuses: undefined,- taskGroups: [{ key: 'backlog', tasks: [{ identifier: 'T-1' }], total: 1 }] as any,+ it("never shows another board query's groups while its own loads", () => {+ const { result } = renderHook(() =>+ useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, groupBy: 'status' }),+ );+ act(() => {+ useTaskStore.setState({+ taskGroupListMap: {+ [result.current.queryKey!]: {+ groupBy: 'status',+ groups: [{ key: 'backlog', tasks: [{ identifier: 'T-1' }], total: 1 }] as any,+ },+ },+ });});- let groupByObservedDuringRender: string | undefined;- const { result } = renderHook(() => {- const swr = useTaskStore- .getState()- .useFetchTaskGroupList({ allAgents: true, groupBy: 'assignee' });- groupByObservedDuringRender = useTaskStore.getState().listGroupBy;- return swr;- });+ const assignee = renderHook(() =>+ useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, groupBy: 'assignee' }),+ );- expect(groupByObservedDuringRender).toBe('status');- expect(result.current.isQueryScopeCurrent).toBe(false);- expect(useTaskStore.getState()).toMatchObject({- isTaskGroupListInit: false,- listGroupBy: 'assignee',- taskGroups: [],- });+ const { taskGroupListMap } = useTaskStore.getState();+ expect(taskGroupListMap[assignee.result.current.queryKey!]).toBeUndefined();+ // Switching back paints the status board from memory at once.+ expect(taskGroupListMap[result.current.queryKey!].groups).toHaveLength(1);});});describe('useFetchTaskList', () => {+ const listKey = (+ options: Parameters<ReturnType<typeof useTaskStore.getState>['useFetchTaskList']>[0],+ ) =>+ renderHook(() => useTaskStore.getState().useFetchTaskList(options)).result.current.queryKey;+it('requests only tasks from the selected project', async () => {- const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');- useTaskStore.getState().useFetchTaskList({ projectId: 'project-1', visibility: 'all' });-- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:list', '__project__:project-1', 'all', 'createdAt', 'project-1'],- expect.any(Function),- expect.any(Object),+ renderHook(() =>+ useTaskStore.getState().useFetchTaskList({ projectId: 'project-1', visibility: 'all' }),);- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as (key: string[]) => unknown;- await fetcher(['task:list', '__project__:project-1', 'all', 'project-1']);++ const [list] = await syncCalls('taskList');+ await list.fetcher();expect(taskService.list).toHaveBeenCalledWith(expect.objectContaining({ projectId: 'project-1' }),);@@ -223,205 +191,70 @@ describe('TaskListSliceAction', () => {});it('allows embedded overviews to ignore the Task page visibility filter', async () => {- const { useClientDataSWR } = await import('@/libs/swr');+ const { taskService } = await import('@/services/task');useTaskStore.setState({ listVisibility: 'private' });- useTaskStore.getState().useFetchTaskList({ allAgents: true, visibility: 'all' });-- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:list', '__all__', 'all', 'createdAt'],- expect.any(Function),- expect.any(Object),- );- });-- // Without the ordering in the key, Home and the Tasks page share one cache- // entry and whichever mounts first decides the other's order.- it('keys the cache by ordering so two surfaces cannot serve each other stale order', async () => {- const { useClientDataSWR } = await import('@/libs/swr');-- useTaskStore- .getState()- .useFetchTaskList({ allAgents: true, orderBy: 'updatedAt', visibility: 'all' });-- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:list', '__all__', 'all', 'updatedAt'],- expect.any(Function),- expect.any(Object),+ renderHook(() =>+ useTaskStore.getState().useFetchTaskList({ allAgents: true, visibility: 'all' }),);- });-- // Home's recent block excludes live schedules and finished statuses- // server-side. Both filters have to reach the request and the cache key, or- // Home and the Tasks page would serve each other's list from one shared- // entry.- it('passes the automation and status filters to the server and keys the cache by them', async () => {- const { useClientDataSWR } = await import('@/libs/swr');- const { taskService } = await import('@/services/task');-- useTaskStore.getState().useFetchTaskList({- allAgents: true,- automated: false,- orderBy: 'updatedAt',- statuses: ['running', 'backlog'],- visibility: 'all',- });- expect(useClientDataSWR).toHaveBeenCalledWith(- // The key's status signature is order-insensitive.- [- 'task:list',- '__all__',- 'all',- 'updatedAt',- { automated: false, statuses: 'backlog,running' },- ],- expect.any(Function),- expect.any(Object),- );- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as (- key: unknown[],- ) => Promise<unknown>;- await fetcher(['task:list', '__all__', 'all', 'updatedAt', {}]);+ const [list] = await syncCalls('taskList');+ await list.fetcher();expect(taskService.list).toHaveBeenCalledWith(- expect.objectContaining({ automated: false, statuses: ['running', 'backlog'] }),- );- });-- it('resets stale task data when the automation filter changes the query scope', () => {- useTaskStore.setState({- isTaskListInit: true,- listAgentId: '__all__',- listQueryAutomated: undefined,- listQueryVisibility: 'all',- listVisibility: 'all',- tasks: [{ id: 'cron-task' }] as any,- tasksTotal: 1,- });-- useTaskStore- .getState()- .useFetchTaskList({ allAgents: true, automated: false, visibility: 'all' });-- const state = useTaskStore.getState();- expect(state.listQueryAutomated).toBe(false);- expect(state.tasks).toEqual([]);- expect(state.tasksTotal).toBe(0);- expect(state.isTaskListInit).toBe(false);- });-- // The list view walks every page while the kanban view (which fetches its- // own server groups) only needs one page for the empty decision. Neither- // may be served the other's rows from a shared cache entry or the shared- // store field.- it('keys the complete walk apart from the single page and resets when it flips', async () => {- const { useClientDataSWR } = await import('@/libs/swr');- useTaskStore.setState({- isTaskListInit: true,- listAgentId: '__all__',- listQueryComplete: false,- tasks: [{ id: 'first-page-only' }] as any,- tasksTotal: 230,- });-- useTaskStore- .getState()- .useFetchTaskList({ allAgents: true, complete: true, visibility: 'all' });-- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:list', '__all__', 'all', 'createdAt', { complete: true }],- expect.any(Function),- expect.any(Object),+ expect.objectContaining({ visibility: undefined }),);- const state = useTaskStore.getState();- expect(state.listQueryComplete).toBe(true);- expect(state.tasks).toEqual([]);- expect(state.isTaskListInit).toBe(false);});- it('resets stale task data when the status filter changes the query scope', () => {- useTaskStore.setState({- isTaskListInit: true,- listAgentId: '__all__',- listQueryStatuses: undefined,- listQueryVisibility: 'all',- listVisibility: 'all',- tasks: [{ id: 'completed-task' }] as any,- tasksTotal: 1,- });-- useTaskStore- .getState()- .useFetchTaskList({ allAgents: true, statuses: ['running', 'backlog'], visibility: 'all' });-- const state = useTaskStore.getState();- expect(state.listQueryStatuses).toBe('backlog,running');- expect(state.tasks).toEqual([]);- expect(state.tasksTotal).toBe(0);- expect(state.isTaskListInit).toBe(false);- });-- it('leaves the shared scope alone while the list query is disabled', () => {- // The "My tasks" board keeps this page's all-agents list mounted but- // disabled. `listAgentId` is one shared slot that the board's group- // query owns while it is up β a disabled list query claiming it would- // wipe `taskGroups` on every render.- useTaskStore.setState({- isTaskGroupListInit: true,- listAgentId: '__mine__:assigned',- taskGroups: [{ key: 'backlog', tasks: [{ identifier: 'T-1' }], total: 1 }] as any,- });-- renderHook(() =>- useTaskStore.getState().useFetchTaskList({ allAgents: true, enabled: false }),- );-- expect(useTaskStore.getState()).toMatchObject({- isTaskGroupListInit: true,- listAgentId: '__mine__:assigned',- });- expect(useTaskStore.getState().taskGroups).toHaveLength(1);- });-- it('resets stale task data when an embedded visibility override changes the query scope', () => {- useTaskStore.setState({- isTaskListInit: true,- listAgentId: '__all__',- listQueryVisibility: 'private',- listVisibility: 'private',- tasks: [{ id: 'private-task' }] as any,- tasksTotal: 1,- });-- useTaskStore.getState().useFetchTaskList({ allAgents: true, visibility: 'all' });-- const state = useTaskStore.getState();- expect(state.listQueryVisibility).toBe('all');- expect(state.tasks).toEqual([]);- expect(state.tasksTotal).toBe(0);- expect(state.isTaskListInit).toBe(false);+ // Home's recent block excludes live schedules and finished statuses+ // server-side, ordered by activity; the Tasks page walks everything by+ // creation. Every one of those has to be part of the list identity, or the+ // two surfaces would serve each other's rows.+ it('gives every ordering, filter and walk mode its own list entry', () => {+ const base = { allAgents: true, visibility: 'all' } as const;+ const keys = [+ listKey(base),+ listKey({ ...base, orderBy: 'updatedAt' }),+ listKey({ ...base, automated: false }),+ listKey({ ...base, statuses: ['running', 'backlog'] }),+ listKey({ ...base, complete: true }),+ listKey({ ...base, visibility: 'private' }),+ listKey({ agentId: 'agent-1', visibility: 'all' }),+ listKey({ projectId: 'project-1', visibility: 'all' }),+ ];+ expect(new Set(keys).size).toBe(keys.length);+ // The status set is order-insensitive.+ expect(listKey({ ...base, statuses: ['backlog', 'running'] })).toBe(keys[3]);});- });- describe('useFetchTaskGroupList', () => {- it('passes the ordinary-task automation filter through the kanban query', async () => {- const { useClientDataSWR } = await import('@/libs/swr');+ it('passes the automation and status filters to the server', async () => {const { taskService } = await import('@/services/task');renderHook(() =>- useTaskStore.getState().useFetchTaskGroupList({ allAgents: true, automated: false }),+ useTaskStore.getState().useFetchTaskList({+ allAgents: true,+ automated: false,+ orderBy: 'updatedAt',+ statuses: ['running', 'backlog'],+ visibility: 'all',+ }),);- expect(useClientDataSWR).toHaveBeenCalledWith(- ['task:groupList', '__all__', 'all', { automated: false }],- expect.any(Function),- expect.any(Object),+ const [list] = await syncCalls('taskList');+ await list.fetcher();+ expect(taskService.list).toHaveBeenCalledWith(+ expect.objectContaining({+ automated: false,+ orderBy: 'updatedAt',+ statuses: ['backlog', 'running'],+ }),);- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => Promise<unknown>;- await fetcher();- expect(taskService.groupList).toHaveBeenCalledWith(- expect.objectContaining({ automated: false }),+ });++ it('has no query key while disabled, so it claims no rows', () => {+ const { result } = renderHook(() =>+ useTaskStore.getState().useFetchTaskList({ allAgents: true, enabled: false }),);+ expect(result.current.queryKey).toBeUndefined();});});@@ -430,7 +263,9 @@ describe('TaskListSliceAction', () => {const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');- useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 });+ renderHook(() =>+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 }),+ );expect(useClientDataSWR).toHaveBeenCalledWith(['task:scheduledList', '__all__', 'all', { limit: 50, offset: 50 }],@@ -448,7 +283,9 @@ describe('TaskListSliceAction', () => {const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');- useTaskStore.getState().useFetchScheduledTaskList({ agentId: 'agent-1', limit: 50 });+ renderHook(() =>+ useTaskStore.getState().useFetchScheduledTaskList({ agentId: 'agent-1', limit: 50 }),+ );expect(useClientDataSWR).toHaveBeenCalledWith(['task:scheduledList', 'agent-1', 'all', { limit: 50, offset: undefined }],@@ -466,7 +303,9 @@ describe('TaskListSliceAction', () => {const { useClientDataSWR } = await import('@/libs/swr');const { taskService } = await import('@/services/task');- useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, projectId: 'project-1' });+ renderHook(() =>+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, projectId: 'project-1' }),+ );expect(useClientDataSWR).toHaveBeenCalledWith(['task:scheduledList', '__project__:project-1', 'all', { limit: 50, offset: undefined }],@@ -483,8 +322,10 @@ describe('TaskListSliceAction', () => {it('keeps concurrent consumers isolated by their SWR keys', async () => {const { useClientDataSWR } = await import('@/libs/swr');- useTaskStore.getState().useFetchScheduledTaskList({ limit: 5 });- useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 });+ renderHook(() => useTaskStore.getState().useFetchScheduledTaskList({ limit: 5 }));+ renderHook(() =>+ useTaskStore.getState().useFetchScheduledTaskList({ limit: 50, offset: 50 }),+ );expect(vi.mocked(useClientDataSWR).mock.calls.map(([key]) => key)).toEqual([['task:scheduledList', '__all__', 'all', { limit: 5, offset: undefined }],@@ -493,41 +334,53 @@ describe('TaskListSliceAction', () => {});});- describe('setListVisibility', () => {- it('should update visibility filter and reset list state', async () => {- useTaskStore.setState({- isTaskListInit: true,- listVisibility: 'private',- tasks: [{ id: 't1' }] as any,- tasksTotal: 1,- });+ describe('reactive query inputs', () => {+ it('re-keys a mounted list and board when the visibility chip changes', () => {+ const { result } = renderHook(() => ({+ board: useTaskStore.getState().useFetchTaskGroupList({ allAgents: true }),+ list: useTaskStore.getState().useFetchTaskList({ allAgents: true }),+ }));+ const before = { ...result.current };- useTaskStore.getState().setListVisibility('workspace');+ act(() => useTaskStore.getState().setListVisibility('private'));- const state = useTaskStore.getState();- expect(state.listVisibility).toBe('workspace');- // Reset clears the previous-filter results so the chip flip doesn't- // briefly render stale entries from the old filter.- expect(state.tasks).toEqual([]);- expect(state.tasksTotal).toBe(0);- expect(state.isTaskListInit).toBe(false);+ expect(result.current.list.queryKey).not.toBe(before.list.queryKey);+ expect(result.current.board.queryKey).not.toBe(before.board.queryKey);});- it('should no-op when the filter does not change', async () => {- useTaskStore.setState({- isTaskListInit: true,- listVisibility: 'private',- tasks: [{ id: 't1' }] as any,- tasksTotal: 1,+ it('does not refetch lists or boards on window focus', async () => {+ const { useClientDataSWR } = await import('@/libs/swr');+ renderHook(() => {+ useTaskStore.getState().useFetchTaskList({ allAgents: true, complete: true });+ useTaskStore.getState().useFetchTaskGroupList({ allAgents: true });});- useTaskStore.getState().setListVisibility('private');+ const syncConfigs = vi+ .mocked(useClientDataSWR)+ .mock.calls.filter(([key]) => Array.isArray(key) && key[0] === 'replica:sync')+ .map(([, , config]) => config as { revalidateOnFocus?: boolean });+ expect(syncConfigs).toHaveLength(2);+ for (const config of syncConfigs) expect(config.revalidateOnFocus).toBe(false);+ });+ });- const state = useTaskStore.getState();- expect(state.tasks).toHaveLength(1);- expect(state.isTaskListInit).toBe(true);+ describe('setListVisibility', () => {+ it('updates the filter; each visibility reads its own list entry', () => {+ useTaskStore.getState().setListVisibility('workspace');+ expect(useTaskStore.getState().listVisibility).toBe('workspace');++ const { result } = renderHook(() =>+ useTaskStore.getState().useFetchTaskList({ allAgents: true }),+ );+ const workspaceKey = result.current.queryKey;+ act(() => useTaskStore.getState().setListVisibility('private'));+ const { result: privateList } = renderHook(() =>+ useTaskStore.getState().useFetchTaskList({ allAgents: true }),+ );+ expect(privateList.current.queryKey).not.toBe(workspaceKey);});});+// The Tasks page renders every task it receives, grouped client-side, and// has no pagination. Without `complete` it only ever saw the first server// page (50 newest by creation), so older tasks silently vanished once a@@ -555,12 +408,13 @@ describe('TaskListSliceAction', () => {});let taskServiceList: (...args: any[]) => any;const runFetcher = async (options: Record<string, unknown>) => {- const { useClientDataSWR } = await import('@/libs/swr');- useTaskStore.getState().useFetchTaskList({ allAgents: true, visibility: 'all', ...options });- const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as (- key: unknown[],- ) => Promise<{ data: Row[]; total: number }>;- return fetcher(['task:list', '__all__', 'all', 'createdAt']);+ renderHook(() =>+ useTaskStore+ .getState()+ .useFetchTaskList({ allAgents: true, visibility: 'all', ...options }),+ );+ const [list] = await syncCalls('taskList');+ return list.fetcher() as Promise<{ data: Row[]; total: number }>;};beforeEach(async () => {diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.tsindex 93eedc993d3..a4f0895cf0c 100644--- a/src/store/task/slices/list/action.ts+++ b/src/store/task/slices/list/action.ts@@ -1,51 +1,34 @@import type { TaskStatus } from '@lobechat/types';-import { useEffect } from 'react';+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';import { mutate, useClientDataSWR } from '@/libs/swr';-import { isMyTaskListKey, isScheduledTaskListKey, isTaskListKey, taskKeys } from '@/libs/swr/keys';+import { isMyTaskListKey, isScheduledTaskListKey, taskKeys } from '@/libs/swr/keys';import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';import type { TaskStore } from '../../store';-import type {- TaskGroupItem,- TaskKanbanGroupBy,- TaskListItem,- TaskListVisibilityFilter,-} from './initialState';+import { useTaskStore } from '../../store';+import type { TaskKanbanGroupBy, TaskListVisibilityFilter } from './initialState';+import {+ type CollectionTask,+ taskGroupListEntity,+ type TaskGroupListQuery,+ taskGroupListQueryKey,+ taskGroupListResource,+ type TaskGroupListValue,+ taskListEntity,+ type TaskListQuery,+ taskListQueryKey,+ taskListResource,+ type TaskListValue,+} from './projection';/**- * Sentinel used as `listAgentId` when the task list is showing tasks across all agents- * (e.g. the `/tasks` page). Keeps the SWR cache key distinct from per-agent lists so- * the two don't collide and `refreshTaskList()` can invalidate the correct entry.+ * 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.*/-export const ALL_AGENTS_LIST_KEY = '__all__';+const ALL_AGENTS_LIST_KEY = '__all__';const PROJECT_LIST_KEY_PREFIX = '__project__:';-/**- * Scope key of the Tasks page's "My tasks" board. Shaped like the project- * prefix so one `listAgentId` slot keeps every board scope apart: the SWR key,- * the scope-change reset and the refresh helpers all derive from it, and the- * `assigned` / `created` sub-views can never serve each other's groups.- */-const MINE_LIST_KEY_PREFIX = '__mine__:';--const projectIdFromListKey = (key?: string) =>- key?.startsWith(PROJECT_LIST_KEY_PREFIX) ? key.slice(PROJECT_LIST_KEY_PREFIX.length) : undefined;--const isMineListKey = (key?: string) => !!key?.startsWith(MINE_LIST_KEY_PREFIX);--/**- * Visibility the grouped query actually runs with. "My tasks" is not offered- * the visibility chip and its list view (`useFetchMyTaskList`) sends no- * visibility at all, so its board has to ignore the chip too β otherwise a- * value left over from the ordinary tab would silently change the row set on- * the list β board switch. Shared with the refresh helpers so the key they- * rebuild is the key the fetch registered.- */-const effectiveGroupVisibility = (- listKey: string | undefined,- visibility: TaskListVisibilityFilter,-): TaskListVisibilityFilter => (isMineListKey(listKey) ? 'all' : visibility);// Default kanban groups: 5 columns// 'scheduled' shares the 'running' column β both represent "automation in@@ -83,19 +66,15 @@ const filterToServerVisibility = (export const COMPLETE_TASK_LIST_PAGE_SIZE = 100;export const COMPLETE_TASK_LIST_MAX_ITEMS = 1000;-/**- * Cleared whenever the list scope changes (all-agents <-> a specific agent).- * The list and group datasets are shared store fields, so without this reset- * the previous scope's tasks would render until the new fetch resolves β e.g.- * the `/tasks` page briefly showing only the last-visited agent's tasks.- */-const scopeChangeResetState = {- isTaskGroupListInit: false,- isTaskListInit: false,- taskGroups: [] as TaskGroupItem[],- tasks: [] as TaskListItem[],- tasksTotal: 0,-};+/** 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. */+ isLoading: boolean;+ /** Alias of `revalidate`. */+ mutate: () => Promise<unknown>;+ /** Read the collection with `taskListSelectors.*(queryKey)`; undefined while disabled. */+ queryKey?: string;+}type Setter = StoreSetter<TaskStore>;@@ -105,31 +84,136 @@ export const createTaskListSlice = (set: Setter, get: () => TaskStore, _api?: unexport class TaskListSliceActionImpl {readonly #get: () => TaskStore;readonly #set: Setter;+ readonly #taskList;+ readonly #taskGroupList;constructor(set: Setter, get: () => TaskStore, _api?: unknown) {void _api;this.#set = set;this.#get = get;+ this.#taskList = createReplicaSlice(taskListResource, {+ actionPrefix: 'taskList',+ entity: taskListEntity,+ fetcher: (query) => this.#fetchList(query),+ get,+ merge: (incoming, _confirmed, query) => ({+ items: incoming.data,+ ...(query.statuses && { statuses: query.statuses }),+ total: incoming.total,+ }),+ set,+ stateKey: 'taskListReplica',+ view: recordLens<TaskStore, TaskListValue>('taskListMap'),+ });+ this.#taskGroupList = createReplicaSlice(taskGroupListResource, {+ actionPrefix: 'taskGroupList',+ entity: taskGroupListEntity,+ fetcher: (query) => this.#fetchGroups(query),+ get,+ merge: (incoming, _confirmed, query) => ({+ ...(query.excludeStatuses && { excludeStatuses: query.excludeStatuses }),+ groupBy: query.groupBy,+ groups: incoming.data,+ }),+ set,+ stateKey: 'taskGroupListReplica',+ view: recordLens<TaskStore, TaskGroupListValue>('taskGroupListMap'),+ });}+ #fetchList = (query: TaskListQuery) => {+ const params = {+ ...(query.agentId ? { assigneeAgentId: query.agentId } : {}),+ automated: query.automated,+ orderBy: query.orderBy,+ projectId: query.projectId,+ statuses: query.statuses,+ visibility: filterToServerVisibility(query.visibility),+ };+ return query.complete ? this.fetchCompleteTaskList(params) : this.fetchTaskList(params);+ };++ #fetchGroups = (query: TaskGroupListQuery) =>+ taskService.groupList({+ assigneeAgentId: query.agentId,+ ...(query.automated === undefined ? {} : { automated: query.automated }),+ excludeStatuses: query.excludeStatuses,+ ...(query.groupBy === 'status'+ ? { groups: DEFAULT_KANBAN_GROUPS }+ : { groupBy: query.groupBy }),+ projectId: query.projectId,+ scope: query.scope,+ visibility: filterToServerVisibility(query.visibility),+ });++ #toSyncResult = (+ sync: ReplicaSyncResult,+ queryKey: string | undefined,+ hasValue: boolean,+ ): TaskCollectionSyncResult => ({+ ...sync,+ isLoading: sync.isValidating && !hasValue,+ mutate: sync.revalidate,+ queryKey,+ });++ /** The task (by identifier) as any loaded list or board holds it. */+ internal_findCollectionTask = (identifier: string): CollectionTask | undefined => {+ const { taskGroupListMap, taskListMap } = this.#get();+ for (const value of Object.values(taskListMap)) {+ const task = value.items.find((item) => item.identifier === identifier);+ if (task) return task;+ }+ for (const value of Object.values(taskGroupListMap)) {+ for (const group of value.groups) {+ const task = group.tasks.find((item) => item.identifier === identifier);+ if (task) return task;+ }+ }+ return undefined;+ };++ /**+ * Optimistic patch of a task in every loaded list and board (a status board+ * moves the card). `commit` keeps it as confirmed until the refresh lands and+ * applies the change to persisted lists and boards that are not loaded, so+ * reopening one later does not paint the old status; `rollback` restores+ * every loaded collection exactly, card order included.+ */+ internal_beginCollectionTaskOptimistic = (+ identifier: string,+ fn: <T extends CollectionTask>(task: T) => T,+ ) => {+ const tokens = [+ ...this.#taskList.beginEntityOptimistic<CollectionTask>(identifier, fn),+ ...this.#taskGroupList.beginEntityOptimistic<CollectionTask>(identifier, fn),+ ];+ return {+ commit: () => {+ tokens.forEach((token) => token.commit());+ void this.#taskList.patchStoredEntity<CollectionTask>(identifier, fn);+ void this.#taskGroupList.patchStoredEntity<CollectionTask>(identifier, fn);+ },+ rollback: () => tokens.forEach((token) => token.rollback()),+ };+ };++ /**+ * Optimistic overlay on one board (a drag between columns): shows now,+ * `commit` keeps it until the refresh lands, `rollback` restores the board.+ */+ internal_beginTaskGroupOptimistic = (+ queryKey: string,+ apply: (value: TaskGroupListValue) => TaskGroupListValue,+ ) => this.#taskGroupList.beginOptimistic(queryKey, apply);++ setActiveTaskListKey = (queryKey?: string): void => {+ if (this.#get().activeTaskListKey === queryKey) return;+ this.#set({ activeTaskListKey: queryKey }, false, 'setActiveTaskListKey');+ };+refreshTaskGroupList = async (): Promise<void> => {- const {- groupListQueryAutomated,- listAgentId,- listGroupBy,- listGroupExcludeStatuses,- listVisibility,- } = this.#get();- await mutate(- taskKeys.groupList(- listAgentId,- effectiveGroupVisibility(listAgentId, listVisibility),- listGroupBy,- listGroupExcludeStatuses,- projectIdFromListKey(listAgentId),- groupListQueryAutomated,- ),- );+ await this.#taskGroupList.revalidate();};fetchTaskList = async (params: Parameters<typeof taskService.list>[0]) =>@@ -166,30 +250,12 @@ export class TaskListSliceActionImpl {};refreshTaskList = async (): Promise<void> => {- const {- groupListQueryAutomated,- listAgentId,- listGroupBy,- listGroupExcludeStatuses,- listVisibility,- } = this.#get();- const projectId = projectIdFromListKey(listAgentId);await Promise.all([- // Every cached variant of the list β both orderings, any visibility chip- // or automation filter β an edit can move a task across each of those- // boundaries (touching reorders `updatedAt`, scheduling flips the- // automation filter), so they are invalidated by root, not enumerated.- mutate(isTaskListKey),- mutate(- taskKeys.groupList(- listAgentId,- effectiveGroupVisibility(listAgentId, listVisibility),- listGroupBy,- listGroupExcludeStatuses,- projectId,- groupListQueryAutomated,- ),- ),+ // 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.+ 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),@@ -198,23 +264,10 @@ export class TaskListSliceActionImpl {]);};- setListAgentId = (agentId?: string): void => {- this.#set({ listAgentId: agentId }, false, 'setListAgentId');- };-setListVisibility = (visibility: TaskListVisibilityFilter): void => {if (this.#get().listVisibility === visibility) return;- // Clear the cached list so the chip flip doesn't render stale entries- // from the previous filter while the new fetch is in flight.- this.#set(- {- ...scopeChangeResetState,- listQueryVisibility: visibility,- listVisibility: visibility,- },- false,- 'setListVisibility',- );+ // Each visibility is its own list entry, so nothing needs clearing here.+ this.#set({ listVisibility: visibility }, false, 'setListVisibility');};useFetchTaskGroupList = (@@ -232,7 +285,7 @@ export class TaskListSliceActionImpl {*/scope?: 'assigned' | 'created';} = {},- ) => {+ ): TaskCollectionSyncResult => {const {agentId,allAgents = false,@@ -243,109 +296,32 @@ export class TaskListSliceActionImpl {projectId,scope,} = options;- const effectiveKey = scope- ? `${MINE_LIST_KEY_PREFIX}${scope}`- : projectId- ? `${PROJECT_LIST_KEY_PREFIX}${projectId}`- : allAgents- ? ALL_AGENTS_LIST_KEY- : agentId;- const excludeStatusesSignature = excludeStatuses?.length- ? [...excludeStatuses].sort().join(',')- : undefined;- const { groupListQueryAutomated, listAgentId, listGroupBy, listGroupExcludeStatuses } =- this.#get();- const isQueryScopeCurrent =- !effectiveKey ||- (listAgentId === effectiveKey &&- groupListQueryAutomated === automated &&- listGroupBy === groupBy &&- listGroupExcludeStatuses === excludeStatusesSignature);-- // Reset after render so changing the board dimension never notifies React- // subscribers while another component is rendering. The caller gates old- // groups with `isQueryScopeCurrent` until this effect commits the new scope.- useEffect(() => {- if (!effectiveKey) return;-- const current = this.#get();- if (- current.listAgentId === effectiveKey &&- current.groupListQueryAutomated === automated &&- current.listGroupBy === groupBy &&- current.listGroupExcludeStatuses === excludeStatusesSignature- ) {- return;- }-- this.#set(- current.listAgentId !== effectiveKey- ? {- ...scopeChangeResetState,- groupListQueryAutomated: automated,- listAgentId: effectiveKey,- listGroupBy: groupBy,- listGroupExcludeStatuses: excludeStatusesSignature,- }- : {- isTaskGroupListInit: false,- groupListQueryAutomated: automated,- listGroupBy: groupBy,- listGroupExcludeStatuses: excludeStatusesSignature,- taskGroups: [],- },- false,- 'useFetchTaskGroupList/syncQueryScope',- );- }, [automated, effectiveKey, excludeStatusesSignature, groupBy]);- const listVisibility = effectiveGroupVisibility(effectiveKey, this.#get().listVisibility);-- const swr = useClientDataSWR(- enabled && effectiveKey- ? taskKeys.groupList(- effectiveKey,- listVisibility,- groupBy,- excludeStatusesSignature,- projectId,- automated,- )- : null,- async () => {- return taskService.groupList({- assigneeAgentId: allAgents || scope ? undefined : agentId,- ...(automated === undefined ? {} : { automated }),- excludeStatuses: excludeStatuses?.length ? [...excludeStatuses] : undefined,- ...(groupBy === 'status' ? { groups: DEFAULT_KANBAN_GROUPS } : { groupBy }),+ // Subscribed, so flipping the visibility chip re-keys the board query.+ const listVisibility = useTaskStore((s) => s.listVisibility);+ const hasScope = !!(scope || projectId || allAgents || agentId);+ const query: TaskGroupListQuery | undefined = hasScope+ ? {+ agentId: allAgents || scope ? undefined : agentId,+ automated,+ excludeStatuses: excludeStatuses?.length ? [...excludeStatuses].sort() : undefined,+ groupBy,projectId,scope,- visibility: filterToServerVisibility(listVisibility),- });- },- {- onSuccess: (data: { data: TaskGroupItem[] }) => {- const current = this.#get();- if (- current.listAgentId !== effectiveKey ||- current.groupListQueryAutomated !== automated ||- current.listGroupBy !== groupBy ||- current.listGroupExcludeStatuses !== excludeStatusesSignature ||- effectiveGroupVisibility(effectiveKey, current.listVisibility) !== listVisibility- ) {- return;- }-- this.#set(- { isTaskGroupListInit: true, taskGroups: data.data },- false,- 'useFetchTaskGroupList/onSuccess',- );- },- revalidateOnFocus: false,- },+ // "My tasks" is not offered the visibility chip and its list view+ // (`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,+ }+ : undefined;+ const queryKey = query ? taskGroupListQueryKey(query) : undefined;+ // A board is a deliberate view, not a live feed: no refetch on focus.+ const sync = this.#taskGroupList.useSync(query, { enabled, revalidateOnFocus: false });+ return this.#toSyncResult(+ sync,+ enabled ? queryKey : undefined,+ !!queryKey && !!this.#get().taskGroupListMap[queryKey],);-- return { ...swr, isQueryScopeCurrent };};/**@@ -449,7 +425,7 @@ export class TaskListSliceActionImpl {/** Override the Task page's persisted filter for embedded consumers. */visibility?: TaskListVisibilityFilter;} = {},- ) => {+ ): TaskCollectionSyncResult => {const {agentId,allAgents = false,@@ -461,89 +437,27 @@ export class TaskListSliceActionImpl {statuses,visibility,} = options;- const effectiveKey = projectId- ? `${PROJECT_LIST_KEY_PREFIX}${projectId}`- : allAgents- ? ALL_AGENTS_LIST_KEY- : agentId;- const listVisibility = visibility ?? this.#get().listVisibility;- // Order-insensitive signature, only for change detection in the scope guard.- const statusesSignature = statuses?.length ? [...statuses].sort().join(',') : undefined;- const {- listAgentId,- listQueryAutomated,- listQueryComplete,- listQueryStatuses,- listQueryVisibility,- } = this.#get();-- // `tasks` is shared by the full Tasks page and embedded overviews. Reset it- // when any part of the effective query changes so an `all` override does- // not temporarily inherit a previously initialized private/workspace list,- // nor the Tasks page a list narrowed by Home's automation/status filters,- // nor the list view a single kanban page posing as the complete list.- //- // Only an ENABLED query claims the scope. `listAgentId` is one shared slot- // and `useFetchTaskGroupList` writes it too, so a disabled list query that- // still claimed it would fight the board that is actually fetching: on the- // "My tasks" board this page keeps its (disabled) all-agents list mounted,- // and the two hooks alternately reset `taskGroups` to [] every render.- if (- enabled &&- effectiveKey &&- (listAgentId !== effectiveKey ||- listQueryVisibility !== listVisibility ||- listQueryAutomated !== automated ||- listQueryComplete !== complete ||- listQueryStatuses !== statusesSignature)- ) {- this.#set(- {- ...scopeChangeResetState,- listAgentId: effectiveKey,- listQueryAutomated: automated,- listQueryComplete: complete,- listQueryStatuses: statusesSignature,- listQueryVisibility: listVisibility,- },- false,- 'useFetchTaskList/syncQueryScope',- );- }-- return useClientDataSWR(- enabled && effectiveKey- ? taskKeys.list(effectiveKey, listVisibility, orderBy, projectId, {- automated,- complete,- statuses,- })- : null,- async ([, id]: [string, string]) => {- const params = {- ...(allAgents || projectId ? {} : { assigneeAgentId: id }),+ // Subscribed, so flipping the visibility chip re-keys the list query.+ const listVisibility = useTaskStore((s) => s.listVisibility);+ const hasScope = !!(projectId || allAgents || agentId);+ const query: TaskListQuery | undefined = hasScope+ ? {+ agentId: allAgents || projectId ? undefined : agentId,automated,+ complete: complete || undefined,orderBy,projectId,- statuses: statuses?.length ? [...statuses] : undefined,- visibility: filterToServerVisibility(listVisibility),- };- return complete ? this.fetchCompleteTaskList(params) : this.fetchTaskList(params);- },- {- onSuccess: (data: { data: TaskListItem[]; total: number }) => {- this.#set(- {- isTaskListInit: true,- tasks: data.data,- tasksTotal: data.total,- },- false,- 'useFetchTaskList/onSuccess',- );- },- revalidateOnFocus: false,- },+ statuses: statuses?.length ? [...statuses].sort() : undefined,+ visibility: visibility ?? listVisibility,+ }+ : undefined;+ const queryKey = query ? taskListQueryKey(query) : undefined;+ // No refetch on focus: a `complete` list walks up to ten pages per sync.+ const sync = this.#taskList.useSync(query, { enabled, revalidateOnFocus: false });+ return this.#toSyncResult(+ sync,+ enabled ? queryKey : undefined,+ !!queryKey && !!this.#get().taskListMap[queryKey],);};}diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.tsindex 7dd373bd12c..6a7399f675f 100644--- a/src/store/task/slices/list/initialState.ts+++ b/src/store/task/slices/list/initialState.ts@@ -1,5 +1,8 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';import type { taskService } from '@/services/task';+import type { TaskGroupListValue, TaskListValue } from './projection';+// Derive types from TRPC inference via serviceexport type TaskListItem = Awaited<ReturnType<typeof taskService.list>>['data'][number];export type TaskGroupItem = Awaited<ReturnType<typeof taskService.groupList>>['data'][number];@@ -16,54 +19,28 @@ export type TaskListVisibilityFilter = 'all' | 'private' | 'workspace';export type TaskKanbanGroupBy = 'assignee' | 'member' | 'priority' | 'status';export interface TaskListSliceState {- groupListQueryAutomated?: boolean;- isTaskGroupListInit: boolean;- isTaskListInit: boolean;- listAgentId?: string;- /** Grouping dimension of the task data currently stored in `taskGroups`. */- listGroupBy: TaskKanbanGroupBy;- /** Excluded statuses of the current grouped query, as a sorted signature. */- listGroupExcludeStatuses?: string;- /**- * Automation filter of the task data currently stored in `tasks` β `false`- * for Home's recent block (live schedules excluded server-side), undefined- * for the unfiltered Tasks page. Tracked like `listQueryVisibility` so a- * scope change resets the shared field instead of rendering the other- * surface's filter.- */- listQueryAutomated?: boolean;- /**- * Whether the data in `tasks` is the complete list (every page walked) or- * a single server page. Tracked for the same scope-reset reason as- * `listQueryAutomated`: flipping list β kanban must not render the other- * variant's rows under the new variant's expectations.- */- listQueryComplete?: boolean;/**- * Status narrowing of the data in `tasks`, as an order-insensitive signature- * (sorted, comma-joined) β undefined when the query is unnarrowed. Tracked- * for the same scope-reset reason as `listQueryAutomated`.+ * The list the Tasks page is showing (`taskListMap` key) β what the task+ * manager agent sees as "the viewed list".*/- listQueryStatuses?: string;- /** Effective visibility of the task data currently stored in `tasks`. */- listQueryVisibility: TaskListVisibilityFilter;+ activeTaskListKey?: string;/** Defaults to 'all' so the Tasks top entry shows every visible task* (private + workspace-shared) without narrowing. */listVisibility: TaskListVisibilityFilter;- taskGroups: TaskGroupItem[];- tasks: TaskListItem[];- tasksTotal: number;+ /** Replica view of the kanban groups, one entry per board query (`taskGroupListQueryKey`). */+ taskGroupListMap: Record<string, TaskGroupListValue>;+ /** Replica bookkeeping of `taskGroupListMap`. */+ taskGroupListReplica: ReplicaState<TaskGroupListValue>;+ /** Replica view of the task lists, one entry per list query (`taskListQueryKey`). */+ taskListMap: Record<string, TaskListValue>;+ /** Replica bookkeeping of `taskListMap`. */+ taskListReplica: ReplicaState<TaskListValue>;}export const initialTaskListSliceState: TaskListSliceState = {- groupListQueryAutomated: undefined,- isTaskGroupListInit: false,- isTaskListInit: false,- listGroupBy: 'status',- listQueryComplete: false,- listQueryVisibility: 'all',listVisibility: 'all',- taskGroups: [],- tasks: [],- tasksTotal: 0,+ taskGroupListMap: {},+ taskGroupListReplica: createReplicaState(),+ taskListMap: {},+ taskListReplica: createReplicaState(),};diff --git a/src/store/task/slices/list/projection.ts b/src/store/task/slices/list/projection.tsnew file mode 100644index 00000000000..2110cff09a0--- /dev/null+++ b/src/store/task/slices/list/projection.ts@@ -0,0 +1,164 @@+import type { TaskStatus } from '@lobechat/types';++import { defineReplica, type ReplicaEntityAdapter, stableQueryKey } from '@/libs/replica';+import type { taskService } from '@/services/task';++import type {+ TaskGroupItem,+ TaskKanbanGroupBy,+ TaskListItem,+ TaskListVisibilityFilter,+} from './initialState';++type TaskListResponse = Awaited<ReturnType<typeof taskService.list>>;+/** A card on the board (the group endpoint's row shape). */+export type TaskGroupTask = TaskGroupItem['tasks'][number];+/** A task as either collection holds it; both carry `identifier` and `status`. */+export type CollectionTask = TaskGroupTask | TaskListItem;+type TaskGroupListResponse = Awaited<ReturnType<typeof taskService.groupList>>;++/**+ * Everything that decides which rows a task list holds. Each distinct query is+ * its own replica entry, so the Tasks page, Home's recent block and a project+ * page never share β or reset β one list.+ */+export interface TaskListQuery {+ /** Assignee filter; absent for all-agents and project scopes. */+ agentId?: string;+ automated?: boolean;+ /** Every page walked (the Tasks list view), or the first server page. */+ complete?: boolean;+ orderBy?: 'createdAt' | 'updatedAt';+ projectId?: string;+ /** Sorted, so the same status set is one entry. */+ statuses?: TaskStatus[];+ visibility: TaskListVisibilityFilter;+}++export interface TaskListValue {+ items: TaskListItem[];+ /** The query's status filter, so a status change can drop a row it no longer matches. */+ statuses?: TaskStatus[];+ total: number;+}++export interface TaskGroupListQuery {+ agentId?: string;+ automated?: boolean;+ /** Sorted. */+ excludeStatuses?: TaskStatus[];+ groupBy: TaskKanbanGroupBy;+ projectId?: string;+ /** "My tasks" board. */+ scope?: 'assigned' | 'created';+ visibility: TaskListVisibilityFilter;+}++export interface TaskGroupListValue {+ /** The board's hidden statuses, so a status change can drop a card it no longer shows. */+ excludeStatuses?: TaskStatus[];+ groupBy: TaskKanbanGroupBy;+ groups: TaskGroupItem[];+}++export const taskListQueryKey = (query: TaskListQuery) => stableQueryKey(query);+export const taskGroupListQueryKey = (query: TaskGroupListQuery) => stableQueryKey(query);++export const taskListResource = defineReplica<TaskListQuery, TaskListValue, TaskListResponse>({+ key: taskListQueryKey,+ name: 'taskList',+ storage: 'indexedDB',+ version: 1,+});++export const taskGroupListResource = defineReplica<+ TaskGroupListQuery,+ TaskGroupListValue,+ TaskGroupListResponse+>({+ key: taskGroupListQueryKey,+ name: 'taskGroupList',+ storage: 'indexedDB',+ version: 1,+});++/** Kanban column of a status when the board groups by status. */+export const taskGroupKeyByStatus: Record<TaskStatus, string> = {+ backlog: 'backlog',+ canceled: 'canceled',+ completed: 'done',+ failed: 'needsInput',+ paused: 'needsInput',+ running: 'running',+ scheduled: 'running',+};++/** Tasks are addressed by `identifier` (e.g. `T-12`) across the task store. */+export const taskListEntity: ReplicaEntityAdapter<TaskListValue, TaskListItem> = {+ has: (data, id) => data.items.some((task) => task.identifier === id),+ map: (data, id, fn) => {+ let removed = 0;+ let changed = false;+ const items: TaskListItem[] = [];+ for (const task of data.items) {+ if (task.identifier !== id) {+ items.push(task);+ continue;+ }+ let next = fn(task);+ // A row whose new status falls outside the query's filter leaves the list.+ if (next && data.statuses && !data.statuses.includes(next.status as TaskStatus))+ next = undefined;+ if (next !== task) changed = true;+ if (next === undefined) removed++;+ else items.push(next);+ }+ return changed ? { ...data, items, total: data.total - removed } : data;+ },+};++/**+ * A task inside the board's groups. On a status board a status change moves+ * the card to its new column (appended), keeping each column's `total` right.+ */+export const taskGroupListEntity: ReplicaEntityAdapter<TaskGroupListValue, TaskGroupTask> = {+ has: (data, id) =>+ data.groups.some((group) => group.tasks.some((task) => task.identifier === id)),+ map: (data, id, fn) => {+ const current = data.groups+ .flatMap((group) => group.tasks)+ .find((task) => task.identifier === id);+ if (!current) return data;+ let next = fn(current);+ if (next === current) return data;+ // A card whose new status the board hides (`hideCompleted`) leaves it, even+ // though the server still returns the hidden status's empty column.+ if (next && data.excludeStatuses?.includes(next.status as TaskStatus)) next = undefined;++ const status = next?.status as TaskStatus | undefined;+ const moves = data.groupBy === 'status' && next !== undefined && status !== current.status;+ const targetKey = moves && status ? taskGroupKeyByStatus[status] : undefined;+ const groups = data.groups.map((group) => {+ const contains = group.tasks.some((task) => task.identifier === id);+ if (moves) {+ const isTarget = group.key === targetKey;+ if (!contains && !isTarget) return group;+ const rest = group.tasks.filter((task) => task.identifier !== id);+ return {+ ...group,+ tasks: isTarget ? [...rest, next!] : rest,+ total: group.total - (contains ? 1 : 0) + (isTarget ? 1 : 0),+ };+ }+ if (!contains) return group;+ return {+ ...group,+ tasks: group.tasks.flatMap((task) =>+ task.identifier !== id ? [task] : next === undefined ? [] : [next],+ ),+ total: next === undefined ? group.total - 1 : group.total,+ };+ });+ return { ...data, groups };+ },+};