🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: sync task status across detail and list (#17994)
Arvin Xu8c62e226eb52
diff --git a/src/store/task/slices/lifecycle/action.test.ts b/src/store/task/slices/lifecycle/action.test.tsindex f84596b0b99..5a5b543eb70 100644--- a/src/store/task/slices/lifecycle/action.test.ts+++ b/src/store/task/slices/lifecycle/action.test.ts@@ -25,6 +25,8 @@ beforeEach(() => {useTaskStore.setState({activeTaskId: 'T-1',taskDetailMap: { 'T-1': { ...mockDetail } },+ taskGroups: [],+ tasks: [],});});@@ -104,6 +106,124 @@ describe('TaskLifecycleSliceAction', () => {await useTaskStore.getState().updateTaskStatus('T-1', 'paused');});+ it('should immediately synchronize list and kanban collections', async () => {+ useTaskStore.setState({+ taskGroups: [+ { 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,+ });+ 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({+ tasks: [],+ total: 0,+ });+ expect(state.taskGroups.find((group) => group.key === 'done')).toMatchObject({+ tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],+ total: 1,+ });++ return { success: true } as any;+ });++ await useTaskStore.getState().updateTaskStatus('T-1', 'completed');+ });++ it('should roll list and kanban collections back when the status update fails', async () => {+ useTaskStore.setState({+ taskGroups: [+ { 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,+ });+ vi.mocked(taskService.updateStatus).mockRejectedValue(new Error('fail'));++ await expect(useTaskStore.getState().updateTaskStatus('T-1', 'completed')).rejects.toThrow(+ 'fail',+ );++ 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({+ tasks: [expect.objectContaining({ identifier: 'T-1', status: 'backlog' })],+ total: 1,+ });+ expect(state.taskGroups.find((group) => group.key === 'done')).toMatchObject({+ tasks: [],+ total: 0,+ });+ });++ it('should preserve the committed status when cache refreshes fail', async () => {+ const { mutate } = await import('@/libs/swr');+ useTaskStore.setState({+ taskGroups: [+ { 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,+ });+ vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);+ vi.mocked(mutate)+ .mockRejectedValueOnce(new Error('detail refresh failed'))+ .mockRejectedValueOnce(new Error('list refresh failed'))+ .mockRejectedValueOnce(new Error('group refresh failed'));++ await expect(useTaskStore.getState().updateTaskStatus('T-1', 'completed')).resolves.toBe(+ 'T-1',+ );++ 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({+ tasks: [expect.objectContaining({ identifier: 'T-1', status: 'completed' })],+ total: 1,+ });+ });++ it('should not let an older failed request roll back a newer status', async () => {+ let rejectFirstRequest: (reason: Error) => void = () => {};+ useTaskStore.setState({+ taskGroups: [+ { 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,+ });+ vi.mocked(taskService.updateStatus)+ .mockImplementationOnce(+ async () =>+ new Promise((_, reject) => {+ rejectFirstRequest = reject;+ }),+ )+ .mockResolvedValueOnce({ success: true } as any);++ const firstRequest = useTaskStore.getState().updateTaskStatus('T-1', 'completed');+ const secondRequest = useTaskStore.getState().updateTaskStatus('T-1', 'canceled');++ await secondRequest;+ rejectFirstRequest(new Error('first request failed'));+ 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({+ tasks: [expect.objectContaining({ identifier: 'T-1', status: 'canceled' })],+ total: 1,+ });+ expect(state.taskGroups.find((group) => group.key === 'done')).toMatchObject({+ tasks: [],+ total: 0,+ });+ });+it('should call updateStatus with canceled', async () => {vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);diff --git a/src/store/task/slices/lifecycle/action.ts b/src/store/task/slices/lifecycle/action.tsindex 9fa93af7b14..53f4ddf495b 100644--- a/src/store/task/slices/lifecycle/action.ts+++ b/src/store/task/slices/lifecycle/action.ts@@ -12,12 +12,27 @@ 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;+export const createTaskLifecycleSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>new TaskLifecycleSliceActionImpl(set, get, _api);export class TaskLifecycleSliceActionImpl {readonly #get: () => TaskStore;+ #nextStatusTransitionVersion = 0;readonly #set: Setter;+ readonly #statusTransitionVersions = new Map<string, number>();constructor(set: Setter, get: () => TaskStore, _api?: unknown) {void _api;@@ -115,27 +130,110 @@ export class TaskLifecycleSliceActionImpl {extraUpdate?: Partial<TaskDetailData>,error?: string,): Promise<void> => {+ const transitionVersion = ++this.#nextStatusTransitionVersion;+ 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;+ const previousStatus = isTaskStatus(previousStatusCandidate)+ ? previousStatusCandidate+ : undefined;+this.#get().internal_dispatchTaskDetail({id,type: 'updateTaskDetail',value: { status, ...extraUpdate },});- await runMutation(this.#set, this.#get, {- mutate: async () => {- await taskService.updateStatus(id, status, error);- await this.#get().internal_refreshTaskDetail(id);- await this.#get().refreshTaskList();- },- name: 'transitionStatus',- onError: async (err) => {- console.error(`[TaskStore] Failed to transition task to ${status}:`, err);- await this.#get().internal_refreshTaskDetail(id);- saveToast(err, {- retry: () => void this.#transitionStatus(id, status, extraUpdate, error),- });- },- setStatus: (s) => this.#get().internal_setTaskSaveStatus(id, s),- });+ this.#patchTaskCollectionsStatus(id, status);++ try {+ await runMutation(this.#set, this.#get, {+ mutate: async () => {+ await taskService.updateStatus(id, status, error);+ },+ name: 'transitionStatus',+ onError: async (err) => {+ console.error(`[TaskStore] Failed to transition task to ${status}:`, err);+ if (this.#statusTransitionVersions.get(id) !== transitionVersion) return;++ if (previousStatus) this.#patchTaskCollectionsStatus(id, previousStatus);+ try {+ await this.#get().internal_refreshTaskDetail(id);+ } catch (refreshError) {+ console.error(+ `[TaskStore] Failed to refresh task ${id} after status failure:`,+ refreshError,+ );+ }+ saveToast(err, {+ retry: () => void this.#transitionStatus(id, status, extraUpdate, error),+ });+ },+ setStatus: (s) => {+ if (this.#statusTransitionVersions.get(id) === transitionVersion) {+ this.#get().internal_setTaskSaveStatus(id, s);+ }+ },+ });++ if (this.#statusTransitionVersions.get(id) !== transitionVersion) return;++ const refreshResults = await Promise.allSettled([+ this.#get().internal_refreshTaskDetail(id),+ this.#get().refreshTaskList(),+ ]);+ for (const refreshResult of refreshResults) {+ if (refreshResult.status === 'rejected') {+ log(+ 'Failed to refresh task %s after successful status update: %O',+ id,+ refreshResult.reason,+ );+ }+ }+ } finally {+ if (this.#statusTransitionVersions.get(id) === transitionVersion) {+ this.#statusTransitionVersions.delete(id);+ }+ }+ };++ #patchTaskCollectionsStatus = (id: string, status: TaskStatus): void => {+ const { 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 targetGroupKey = taskGroupKeyByStatus[status];+ const nextTasks = listTask+ ? tasks.map((item) => (item.identifier === id ? { ...item, status } : item))+ : tasks;+ const nextTaskGroups = groupedTask+ ? taskGroups.map((group) => {+ 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;++ this.#set(+ { taskGroups: nextTaskGroups, tasks: nextTasks },+ false,+ 'transitionStatus/patchTaskCollections',+ );};}