🤯 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: subtask assignee refresh and rollback handling (#14353)
AmAzing-79dc61ac50b8
diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex bb685decbd6..c1c1059a77f 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -31,7 +31,7 @@ vi.mock('@/components/AntdStaticMethods', () => ({}));beforeEach(() => {- vi.clearAllMocks();+ vi.resetAllMocks();useTaskStore.setState({activeTaskId: undefined,isCreatingTask: false,@@ -136,6 +136,77 @@ describe('TaskDetailSliceAction', () => {expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);expect(message.error).toHaveBeenCalled();});++ 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: {+ 'T-parent': {+ identifier: 'T-parent',+ instruction: 'Parent',+ status: 'backlog',+ subtasks: [{ assignee: null, identifier: 'T-sub', name: 'Sub', status: 'backlog' }],+ },+ 'T-sub': { identifier: 'T-sub', instruction: 'Sub', status: 'backlog' },+ },+ });++ vi.mocked(taskService.update).mockRejectedValue(new Error('fail'));++ await expect(+ useTaskStore.getState().updateTask('T-sub', { assigneeAgentId: 'agent-x' }),+ ).rejects.toThrow('fail');++ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-sub']);+ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-parent']);+ });++ it('should not show error when update succeeds but cache refresh fails', async () => {+ const { mutate } = await import('@/libs/swr');+ const { message } = await import('@/components/AntdStaticMethods');+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },+ },+ });++ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);+ vi.mocked(mutate).mockRejectedValue(new Error('network blip'));++ await useTaskStore.getState().updateTask('T-1', { assigneeAgentId: 'agent-x' });++ expect(useTaskStore.getState().taskSaveStatus).toBe('saved');+ expect(message.error).not.toHaveBeenCalled();+ });++ 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: {+ 'T-parent': {+ identifier: 'T-parent',+ instruction: 'Parent',+ status: 'backlog',+ subtasks: [{ assignee: null, identifier: 'T-sub', name: 'Sub', status: 'backlog' }],+ },+ },+ });++ vi.mocked(taskService.update).mockImplementation(async () => {+ useTaskStore.setState({ activeTaskId: 'T-other' });+ throw new Error('fail');+ });++ await expect(+ useTaskStore.getState().updateTask('T-sub', { assigneeAgentId: 'agent-x' }),+ ).rejects.toThrow('fail');++ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-sub']);+ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-parent']);+ });});describe('deleteTask', () => {diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex a1f017ec844..d8abe19d4d1 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -10,7 +10,7 @@ import type { StoreSetter } from '@/store/types';import type { TaskStore } from '../../store';import { useTaskStore } from '../../store';import type { TaskDetailDispatch } from './reducer';-import { taskDetailReducer } from './reducer';+import { findSubtaskParentId, taskDetailReducer } from './reducer';type CreatedTask = NonNullable<Awaited<ReturnType<typeof taskService.create>>['data']>;type DeletedTask = NonNullable<Awaited<ReturnType<typeof taskService.delete>>['data']>;@@ -229,19 +229,30 @@ export class TaskDetailSliceActionImpl {...rest,...(assigneeAgentId !== undefined ? { agentId: assigneeAgentId } : {}),};++ // Snapshot every map entry the optimistic patch will touch BEFORE dispatch.+ // activeTaskId can change mid-flight, and the patch can mutate a parent's+ // cached subtree in addition to `id`, so rollback must target both.+ const patchedParentId = findSubtaskParentId(this.#get().taskDetailMap, id);+ const snapshotActiveTaskId = this.#get().activeTaskId;+ const refreshPatchedTargets = async (): Promise<void> => {+ const targets = new Set<string>([id]);+ if (patchedParentId) targets.add(patchedParentId);+ if (snapshotActiveTaskId) targets.add(snapshotActiveTaskId);+ await Promise.all(+ Array.from(targets).map((target) => this.internal_refreshTaskDetail(target)),+ );+ };+this.internal_dispatchTaskDetail({ id, type: 'updateTaskDetail', value: optimistic });this.#set({ taskSaveStatus: 'saving' }, false, 'updateTask/saving');try {await taskService.update(id, data);this.#set({ taskSaveStatus: 'saved' }, false, 'updateTask/saved');- if (assigneeAgentId !== undefined) {- await this.#get().refreshTaskList();- }} catch (error) {this.#set({ taskSaveStatus: 'idle' }, false, 'updateTask/error');- // Revert by refreshing from server- await this.internal_refreshTaskDetail(id);+ await refreshPatchedTargets();message.error(t('taskDetail.updateFailed', {defaultValue: 'Failed to update task',@@ -250,6 +261,10 @@ export class TaskDetailSliceActionImpl {);throw error;}++ if (assigneeAgentId !== undefined) {+ await Promise.all([this.#get().refreshTaskList(), refreshPatchedTargets()]).catch(() => {});+ }};useFetchTaskDetail = (taskId?: string) => {diff --git a/src/store/task/slices/detail/reducer.test.ts b/src/store/task/slices/detail/reducer.test.tsindex c4042472801..a77b11e742f 100644--- a/src/store/task/slices/detail/reducer.test.ts+++ b/src/store/task/slices/detail/reducer.test.ts@@ -2,7 +2,7 @@ import type { TaskDetailData } from '@lobechat/types';import { describe, expect, it } from 'vitest';import type { TaskDetailDispatch } from './reducer';-import { taskDetailReducer } from './reducer';+import { findSubtaskParentId, taskDetailReducer } from './reducer';const mockDetail: TaskDetailData = {identifier: 'T-1',@@ -81,6 +81,99 @@ describe('taskDetailReducer', () => {expect(result['T-999']).toBeUndefined();});++ describe('nested subtasks', () => {+ const buildParentWithSubtasks = (): TaskDetailData => ({+ identifier: 'T-3',+ instruction: 'Parent',+ name: 'Parent',+ status: 'backlog',+ subtasks: [+ {+ assignee: {+ avatar: 'old-avatar',+ backgroundColor: '#000',+ id: 'agent-old',+ title: 'Old Agent',+ },+ identifier: 'T-3.1',+ name: 'Sub 1',+ priority: 2,+ status: 'backlog',+ },+ {+ children: [+ {+ assignee: null,+ identifier: 'T-3.2.1',+ name: 'Nested',+ status: 'backlog',+ },+ ],+ identifier: 'T-3.2',+ name: 'Sub 2',+ status: 'backlog',+ },+ ],+ });++ it('should patch a subtask assignee.id when agentId is updated', () => {+ const state: Record<string, TaskDetailData> = { 'T-3': buildParentWithSubtasks() };+ const result = taskDetailReducer(state, {+ id: 'T-3.1',+ type: 'updateTaskDetail',+ value: { agentId: 'agent-new' },+ });++ const patched = result['T-3'].subtasks?.[0];+ expect(patched?.assignee?.id).toBe('agent-new');+ // Other assignee fields preserved (the avatar resolves reactively from agent store)+ expect(patched?.assignee?.title).toBe('Old Agent');+ });++ it('should create assignee object when patching agentId on subtask without assignee', () => {+ const state: Record<string, TaskDetailData> = { 'T-3': buildParentWithSubtasks() };+ const result = taskDetailReducer(state, {+ id: 'T-3.2.1',+ type: 'updateTaskDetail',+ value: { agentId: 'agent-new' },+ });++ const patched = result['T-3'].subtasks?.[1].children?.[0];+ expect(patched?.assignee).toEqual({+ avatar: null,+ backgroundColor: null,+ id: 'agent-new',+ title: null,+ });+ });++ it('should clear subtask assignee when agentId is null', () => {+ const state: Record<string, TaskDetailData> = { 'T-3': buildParentWithSubtasks() };+ const result = taskDetailReducer(state, {+ id: 'T-3.1',+ type: 'updateTaskDetail',+ value: { agentId: null },+ });++ const patched = result['T-3'].subtasks?.[0];+ expect(patched?.assignee).toBeNull();+ });++ it('should patch name and priority alongside agentId', () => {+ const state: Record<string, TaskDetailData> = { 'T-3': buildParentWithSubtasks() };+ const result = taskDetailReducer(state, {+ id: 'T-3.1',+ type: 'updateTaskDetail',+ value: { agentId: 'agent-new', name: 'Renamed', priority: 5 },+ });++ const patched = result['T-3'].subtasks?.[0];+ expect(patched?.name).toBe('Renamed');+ expect(patched?.priority).toBe(5);+ expect(patched?.assignee?.id).toBe('agent-new');+ });+ });});describe('deleteTaskDetail', () => {@@ -118,4 +211,57 @@ describe('taskDetailReducer', () => {expect(result).toBe(state);});++ describe('findSubtaskParentId', () => {+ const buildParent = (): TaskDetailData => ({+ identifier: 'T-parent',+ instruction: 'Parent',+ name: 'Parent',+ status: 'backlog',+ subtasks: [+ { assignee: null, identifier: 'T-sub-1', name: 'Sub 1', status: 'backlog' },+ {+ children: [+ { assignee: null, identifier: 'T-sub-2-1', name: 'Nested', status: 'backlog' },+ ],+ identifier: 'T-sub-2',+ name: 'Sub 2',+ status: 'backlog',+ },+ ],+ });++ it('should return the parent id when the target lives directly in its subtasks', () => {+ const map = { 'T-parent': buildParent() };+ expect(findSubtaskParentId(map, 'T-sub-1')).toBe('T-parent');+ });++ it('should return the parent id when the target is nested deeper in children', () => {+ const map = { 'T-parent': buildParent() };+ expect(findSubtaskParentId(map, 'T-sub-2-1')).toBe('T-parent');+ });++ it('should return undefined when no entry has the target in its subtree', () => {+ const map = { 'T-parent': buildParent() };+ expect(findSubtaskParentId(map, 'T-unknown')).toBeUndefined();+ });++ it('should skip the entry whose key matches the id (self) and return the real parent', () => {+ const map: Record<string, TaskDetailData> = {+ 'T-parent': buildParent(),+ // The subtask is also cached under its own key (e.g. user opened it as a detail page).+ 'T-sub-1': {+ identifier: 'T-sub-1',+ instruction: 'Sub',+ name: 'Sub 1',+ status: 'backlog',+ },+ };+ expect(findSubtaskParentId(map, 'T-sub-1')).toBe('T-parent');+ });++ it('should return undefined for an empty map', () => {+ expect(findSubtaskParentId({}, 'T-1')).toBeUndefined();+ });+ });});diff --git a/src/store/task/slices/detail/reducer.ts b/src/store/task/slices/detail/reducer.tsindex 467390c2e2e..6b6e16e3614 100644--- a/src/store/task/slices/detail/reducer.ts+++ b/src/store/task/slices/detail/reducer.ts@@ -6,6 +6,28 @@ export type TaskDetailDispatch =| { id: string; type: 'setTaskDetail'; value: TaskDetailData }| { id: string; type: 'updateTaskDetail'; value: Partial<TaskDetailData> };+const containsSubtaskInTree = (subtasks: TaskDetailSubtask[], id: string): boolean => {+ for (const subtask of subtasks) {+ if (subtask.identifier === id) return true;+ if (subtask.children && containsSubtaskInTree(subtask.children, id)) return true;+ }+ return false;+};++// Mirrors the walk in `updateTaskDetail` so callers can pre-compute which+// parent entry an upcoming dispatch will mutate (e.g. for optimistic rollback).+export const findSubtaskParentId = (+ map: Record<string, TaskDetailData>,+ id: string,+): string | undefined => {+ for (const parentId in map) {+ if (parentId === id) continue;+ const subtasks = map[parentId]?.subtasks;+ if (subtasks && containsSubtaskInTree(subtasks, id)) return parentId;+ }+ return undefined;+};+// Walk the subtask tree (subtasks live nested under a parent task's detail)// and patch the entry whose identifier matches. Returns true if patched.const patchSubtaskInTree = (@@ -17,6 +39,18 @@ const patchSubtaskInTree = (if (subtask.identifier === id) {if (value.name !== undefined) subtask.name = value.name;if (value.priority !== undefined) subtask.priority = value.priority;+ if (value.agentId !== undefined) {+ // null = unassigned (clear it). For a real agentId, only patching assignee.id+ // is enough — AssigneeAvatar resolves title/avatar/backgroundColor reactively+ // from the agent store via useAgentDisplayMeta(agentId).+ if (value.agentId === null) {+ subtask.assignee = null;+ } else {+ subtask.assignee = subtask.assignee+ ? { ...subtask.assignee, id: value.agentId }+ : { avatar: null, backgroundColor: null, id: value.agentId, title: null };+ }+ }return true;}if (subtask.children && patchSubtaskInTree(subtask.children, id, value)) {