🤯 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
🔨 chore: add Task store — service layer, selectors, and 4 slices (#13500)
Tsukif2a95f9ae602
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex 08f675c29b3..c0ee51a58eb 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -82,6 +82,7 @@ export interface TaskDetailData {dependencies?: Array<{ dependsOn: string; type: string }>;description?: string | null;error?: string | null;+ // heartbeat.interval: 周期执行间隔 | heartbeat.timeout+lastAt: watchdog 监控(检测卡死)heartbeat?: {interval?: number | null;lastAt?: string | null;diff --git a/src/services/__tests__/task.test.ts b/src/services/__tests__/task.test.tsnew file mode 100644index 00000000000..5396735a8fe--- /dev/null+++ b/src/services/__tests__/task.test.ts@@ -0,0 +1,173 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';+import { taskService } from '@/services/task';++// Mock lambdaClient+vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ brief: {+ markRead: { mutate: vi.fn() },+ resolve: { mutate: vi.fn() },+ },+ task: {+ addComment: { mutate: vi.fn() },+ addDependency: { mutate: vi.fn() },+ cancelTopic: { mutate: vi.fn() },+ clearAll: { mutate: vi.fn() },+ create: { mutate: vi.fn() },+ delete: { mutate: vi.fn() },+ deleteTopic: { mutate: vi.fn() },+ detail: { query: vi.fn() },+ find: { query: vi.fn() },+ getDependencies: { query: vi.fn() },+ getCheckpoint: { query: vi.fn() },+ getPinnedDocuments: { query: vi.fn() },+ getReview: { query: vi.fn() },+ getSubtasks: { query: vi.fn() },+ getTaskTree: { query: vi.fn() },+ getTopics: { query: vi.fn() },+ groupList: { query: vi.fn() },+ list: { query: vi.fn() },+ pinDocument: { mutate: vi.fn() },+ removeDependency: { mutate: vi.fn() },+ reorderSubtasks: { mutate: vi.fn() },+ run: { mutate: vi.fn() },+ runReview: { mutate: vi.fn() },+ unpinDocument: { mutate: vi.fn() },+ update: { mutate: vi.fn() },+ updateCheckpoint: { mutate: vi.fn() },+ updateConfig: { mutate: vi.fn() },+ updateReview: { mutate: vi.fn() },+ updateStatus: { mutate: vi.fn() },+ },+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+});++describe('TaskService', () => {+ describe('queries', () => {+ it('find should call task.find.query', async () => {+ await taskService.find('T-1');+ expect(lambdaClient.task.find.query).toHaveBeenCalledWith({ id: 'T-1' });+ });++ it('getDetail should call task.detail.query', async () => {+ await taskService.getDetail('T-1');+ expect(lambdaClient.task.detail.query).toHaveBeenCalledWith({ id: 'T-1' });+ });++ it('list should call task.list.query with params', async () => {+ const params = { assigneeAgentId: 'agt_1', limit: 50, offset: 0 };+ await taskService.list(params);+ expect(lambdaClient.task.list.query).toHaveBeenCalledWith(params);+ });++ it('getSubtasks should call task.getSubtasks.query', async () => {+ await taskService.getSubtasks('T-1');+ expect(lambdaClient.task.getSubtasks.query).toHaveBeenCalledWith({ id: 'T-1' });+ });++ it('getTaskTree should call task.getTaskTree.query', async () => {+ await taskService.getTaskTree('T-1');+ expect(lambdaClient.task.getTaskTree.query).toHaveBeenCalledWith({ id: 'T-1' });+ });+ });++ describe('mutations', () => {+ it('create should call task.create.mutate', async () => {+ const params = { instruction: 'Do something', name: 'Test' };+ await taskService.create(params);+ expect(lambdaClient.task.create.mutate).toHaveBeenCalledWith(params);+ });++ it('update should merge id with data', async () => {+ await taskService.update('T-1', { name: 'Updated', priority: 1 });+ expect(lambdaClient.task.update.mutate).toHaveBeenCalledWith({+ id: 'T-1',+ name: 'Updated',+ priority: 1,+ });+ });++ it('delete should call task.delete.mutate', async () => {+ await taskService.delete('T-1');+ expect(lambdaClient.task.delete.mutate).toHaveBeenCalledWith({ id: 'T-1' });+ });++ it('updateStatus should pass status directly', async () => {+ await taskService.updateStatus('T-1', 'running');+ expect(lambdaClient.task.updateStatus.mutate).toHaveBeenCalledWith({+ error: undefined,+ id: 'T-1',+ status: 'running',+ });+ });++ it('run should merge id with params', async () => {+ await taskService.run('T-1', { prompt: 'Focus on tests' });+ expect(lambdaClient.task.run.mutate).toHaveBeenCalledWith({+ id: 'T-1',+ prompt: 'Focus on tests',+ });+ });++ it('addComment should pass all params', async () => {+ await taskService.addComment('T-1', 'Great work', { topicId: 'tpc_1' });+ expect(lambdaClient.task.addComment.mutate).toHaveBeenCalledWith({+ content: 'Great work',+ id: 'T-1',+ topicId: 'tpc_1',+ });+ });++ it('addDependency should default type to blocks', async () => {+ await taskService.addDependency('T-1', 'T-2');+ expect(lambdaClient.task.addDependency.mutate).toHaveBeenCalledWith({+ dependsOnId: 'T-2',+ taskId: 'T-1',+ type: 'blocks',+ });+ });++ it('updateConfig should call task.updateConfig.mutate', async () => {+ await taskService.updateConfig('T-1', { model: 'gpt-4o', provider: 'openai' });+ expect(lambdaClient.task.updateConfig.mutate).toHaveBeenCalledWith({+ config: { model: 'gpt-4o', provider: 'openai' },+ id: 'T-1',+ });+ });++ it('cancelTopic should call task.cancelTopic.mutate', async () => {+ await taskService.cancelTopic('tpc_1');+ expect(lambdaClient.task.cancelTopic.mutate).toHaveBeenCalledWith({ topicId: 'tpc_1' });+ });++ it('pinDocument should pass all params', async () => {+ await taskService.pinDocument('T-1', 'doc_1', 'user');+ expect(lambdaClient.task.pinDocument.mutate).toHaveBeenCalledWith({+ documentId: 'doc_1',+ pinnedBy: 'user',+ taskId: 'T-1',+ });+ });+ });++ describe('brief operations', () => {+ it('resolveBrief should call brief.resolve.mutate', async () => {+ await taskService.resolveBrief('brief_1', { action: 'approve' });+ expect(lambdaClient.brief.resolve.mutate).toHaveBeenCalledWith({+ action: 'approve',+ id: 'brief_1',+ });+ });++ it('markBriefRead should call brief.markRead.mutate', async () => {+ await taskService.markBriefRead('brief_1');+ expect(lambdaClient.brief.markRead.mutate).toHaveBeenCalledWith({ id: 'brief_1' });+ });+ });+});diff --git a/src/services/task.ts b/src/services/task.tsnew file mode 100644index 00000000000..7187a9e13f4--- /dev/null+++ b/src/services/task.ts@@ -0,0 +1,135 @@+import type { CheckpointConfig } from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++class TaskService {+ // ── Queries ──++ find = async (id: string) => lambdaClient.task.find.query({ id });++ getDetail = async (id: string) => lambdaClient.task.detail.query({ id });++ list = async (params: {+ assigneeAgentId?: string;+ limit?: number;+ offset?: number;+ parentTaskId?: string | null;+ status?: string;+ }) => lambdaClient.task.list.query(params);++ groupList = async (params: {+ assigneeAgentId?: string;+ groups: Array<{+ key: string;+ limit?: number;+ offset?: number;+ statuses: string[];+ }>;+ parentTaskId?: string | null;+ }) => lambdaClient.task.groupList.query(params);++ getSubtasks = async (id: string) => lambdaClient.task.getSubtasks.query({ id });++ getTaskTree = async (id: string) => lambdaClient.task.getTaskTree.query({ id });++ getTopics = async (id: string) => lambdaClient.task.getTopics.query({ id });++ getDependencies = async (id: string) => lambdaClient.task.getDependencies.query({ id });++ getPinnedDocuments = async (id: string) => lambdaClient.task.getPinnedDocuments.query({ id });++ getCheckpoint = async (id: string) => lambdaClient.task.getCheckpoint.query({ id });++ getReview = async (id: string) => lambdaClient.task.getReview.query({ id });++ // ── Mutations ──++ create = async (params: {+ assigneeAgentId?: string;+ assigneeUserId?: string;+ description?: string;+ identifierPrefix?: string;+ instruction: string;+ name?: string;+ parentTaskId?: string;+ priority?: number;+ }) => lambdaClient.task.create.mutate(params);++ update = async (+ id: string,+ data: {+ assigneeAgentId?: string | null;+ assigneeUserId?: string | null;+ config?: Record<string, unknown>;+ context?: Record<string, unknown>;+ description?: string;+ // heartbeatInterval: 周期执行间隔(秒),控制每隔多久自动执行一次 task+ heartbeatInterval?: number;+ // heartbeatTimeout: watchdog 超时阈值(秒),用于检测 running task 是否卡死+ heartbeatTimeout?: number | null;+ instruction?: string;+ name?: string;+ priority?: number;+ },+ ) => lambdaClient.task.update.mutate({ id, ...data });++ delete = async (id: string) => lambdaClient.task.delete.mutate({ id });++ clearAll = async () => lambdaClient.task.clearAll.mutate();++ updateStatus = async (+ id: string,+ status: 'backlog' | 'canceled' | 'completed' | 'failed' | 'paused' | 'running',+ error?: string,+ ) => lambdaClient.task.updateStatus.mutate({ error, id, status });++ run = async (id: string, params?: { continueTopicId?: string; prompt?: string }) =>+ lambdaClient.task.run.mutate({ id, ...params });++ addComment = async (id: string, content: string, opts?: { briefId?: string; topicId?: string }) =>+ lambdaClient.task.addComment.mutate({ content, id, ...opts });++ addDependency = async (+ taskId: string,+ dependsOnId: string,+ type: 'blocks' | 'relates' = 'blocks',+ ) => lambdaClient.task.addDependency.mutate({ dependsOnId, taskId, type });++ removeDependency = async (taskId: string, dependsOnId: string) =>+ lambdaClient.task.removeDependency.mutate({ dependsOnId, taskId });++ reorderSubtasks = async (id: string, order: string[]) =>+ lambdaClient.task.reorderSubtasks.mutate({ id, order });++ cancelTopic = async (topicId: string) => lambdaClient.task.cancelTopic.mutate({ topicId });++ deleteTopic = async (topicId: string) => lambdaClient.task.deleteTopic.mutate({ topicId });++ // 安全 merge config(不会覆盖 checkpoint/review 等其他 config 字段)+ updateConfig = async (id: string, config: Record<string, unknown>) =>+ lambdaClient.task.updateConfig.mutate({ config, id });++ updateCheckpoint = async (id: string, checkpoint: CheckpointConfig) =>+ lambdaClient.task.updateCheckpoint.mutate({ checkpoint, id });++ updateReview = async (...args: Parameters<typeof lambdaClient.task.updateReview.mutate>) =>+ lambdaClient.task.updateReview.mutate(...args);++ runReview = async (id: string, params?: { content?: string; topicId?: string }) =>+ lambdaClient.task.runReview.mutate({ id, ...params });++ pinDocument = async (taskId: string, documentId: string, pinnedBy?: string) =>+ lambdaClient.task.pinDocument.mutate({ documentId, pinnedBy, taskId });++ unpinDocument = async (taskId: string, documentId: string) =>+ lambdaClient.task.unpinDocument.mutate({ documentId, taskId });++ // ── Brief operations ──++ resolveBrief = async (id: string, opts?: { action?: string; comment?: string }) =>+ lambdaClient.brief.resolve.mutate({ id, ...opts });++ markBriefRead = async (id: string) => lambdaClient.brief.markRead.mutate({ id });+}++export const taskService = new TaskService();diff --git a/src/store/task/index.ts b/src/store/task/index.tsnew file mode 100644index 00000000000..81f97cabd0d--- /dev/null+++ b/src/store/task/index.ts@@ -0,0 +1,3 @@+export type { TaskStore } from './store';+export { useTaskStore } from './store';+export { getTaskStoreState } from './store';diff --git a/src/store/task/initialState.ts b/src/store/task/initialState.tsnew file mode 100644index 00000000000..7d0d0d0929b--- /dev/null+++ b/src/store/task/initialState.ts@@ -0,0 +1,11 @@+import type { TaskDetailSliceState } from './slices/detail/initialState';+import { initialTaskDetailSliceState } from './slices/detail/initialState';+import type { TaskListSliceState } from './slices/list/initialState';+import { initialTaskListSliceState } from './slices/list/initialState';++export type TaskStoreState = TaskDetailSliceState & TaskListSliceState;++export const initialState: TaskStoreState = {+ ...initialTaskListSliceState,+ ...initialTaskDetailSliceState,+};diff --git a/src/store/task/selectors/activitySelectors.test.ts b/src/store/task/selectors/activitySelectors.test.tsnew file mode 100644index 00000000000..e35a70b4cdd--- /dev/null+++ b/src/store/task/selectors/activitySelectors.test.ts@@ -0,0 +1,138 @@+import type { TaskDetailActivity, TaskDetailData } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { TaskStoreState } from '../initialState';+import { initialState } from '../initialState';+import { taskActivitySelectors } from './activitySelectors';++const createActivity = (+ overrides: Partial<TaskDetailActivity> & { type: TaskDetailActivity['type'] },+): TaskDetailActivity => ({+ time: '2026-04-01T00:00:00Z',+ ...overrides,+});++const mockDetail: TaskDetailData = {+ activities: [+ createActivity({ id: 'a1', time: '2026-04-01T10:00:00Z', title: 'Topic 1', type: 'topic' }),+ createActivity({+ briefType: 'decision',+ id: 'a2',+ resolvedAction: null,+ time: '2026-04-01T11:00:00Z',+ type: 'brief',+ }),+ createActivity({+ content: 'A comment',+ id: 'a3',+ time: '2026-04-01T09:00:00Z',+ type: 'comment',+ }),+ createActivity({+ briefType: 'result',+ id: 'a4',+ resolvedAction: 'approve',+ time: '2026-04-01T12:00:00Z',+ type: 'brief',+ }),+ ],+ identifier: 'T-1',+ instruction: 'Test',+ status: 'paused',+};++const createState = (overrides: Partial<TaskStoreState> = {}): TaskStoreState => ({+ ...initialState,+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': mockDetail },+ ...overrides,+});++describe('taskActivitySelectors', () => {+ describe('activeTaskActivities', () => {+ it('should return activities sorted by time (newest first)', () => {+ const result = taskActivitySelectors.activeTaskActivities(createState());+ expect(result[0].id).toBe('a4'); // 12:00+ expect(result[1].id).toBe('a2'); // 11:00+ expect(result[2].id).toBe('a1'); // 10:00+ expect(result[3].id).toBe('a3'); // 09:00+ });++ it('should return empty array when no active task', () => {+ const state = createState({ activeTaskId: undefined });+ expect(taskActivitySelectors.activeTaskActivities(state)).toEqual([]);+ });++ it('should return empty array when no activities', () => {+ const state = createState({+ taskDetailMap: {+ 'T-1': { ...mockDetail, activities: undefined },+ },+ });+ expect(taskActivitySelectors.activeTaskActivities(state)).toEqual([]);+ });+ });++ describe('filtered selectors', () => {+ const state = createState();++ it('should filter briefs', () => {+ const briefs = taskActivitySelectors.activeTaskBriefs(state);+ expect(briefs).toHaveLength(2);+ expect(briefs.every((b) => b.type === 'brief')).toBe(true);+ });++ it('should filter topics', () => {+ const topics = taskActivitySelectors.activeTaskTopics(state);+ expect(topics).toHaveLength(1);+ expect(topics[0].type).toBe('topic');+ });++ it('should filter comments', () => {+ const comments = taskActivitySelectors.activeTaskComments(state);+ expect(comments).toHaveLength(1);+ expect(comments[0].type).toBe('comment');+ });+ });++ describe('unresolvedBriefCount', () => {+ it('should count unresolved briefs', () => {+ // a2 has resolvedAction: null, a4 has resolvedAction: 'approve'+ expect(taskActivitySelectors.unresolvedBriefCount(createState())).toBe(1);+ });++ it('should return 0 when all briefs resolved', () => {+ const state = createState({+ taskDetailMap: {+ 'T-1': {+ ...mockDetail,+ activities: [+ createActivity({+ briefType: 'result',+ id: 'a1',+ resolvedAction: 'approve',+ type: 'brief',+ }),+ ],+ },+ },+ });+ expect(taskActivitySelectors.unresolvedBriefCount(state)).toBe(0);+ });+ });++ describe('hasUnresolvedBriefs', () => {+ it('should return true when unresolved briefs exist', () => {+ expect(taskActivitySelectors.hasUnresolvedBriefs(createState())).toBe(true);+ });++ it('should return false when no unresolved briefs', () => {+ const state = createState({+ taskDetailMap: {+ 'T-1': { ...mockDetail, activities: [] },+ },+ });+ expect(taskActivitySelectors.hasUnresolvedBriefs(state)).toBe(false);+ });+ });+});diff --git a/src/store/task/selectors/activitySelectors.ts b/src/store/task/selectors/activitySelectors.tsnew file mode 100644index 00000000000..2c6bcc1f9ba--- /dev/null+++ b/src/store/task/selectors/activitySelectors.ts@@ -0,0 +1,38 @@+import type { TaskDetailActivity } from '@lobechat/types';++import type { TaskStoreState } from '../initialState';+import { taskDetailSelectors } from './detailSelectors';++const activeTaskActivities = (s: TaskStoreState): TaskDetailActivity[] => {+ const detail = taskDetailSelectors.activeTaskDetail(s);+ if (!detail?.activities) return [];++ return [...detail.activities].sort((a, b) => {+ const timeA = a.time ? new Date(a.time).getTime() : 0;+ const timeB = b.time ? new Date(b.time).getTime() : 0;+ return timeB - timeA;+ });+};++const activeTaskBriefs = (s: TaskStoreState): TaskDetailActivity[] =>+ activeTaskActivities(s).filter((a) => a.type === 'brief');++const activeTaskTopics = (s: TaskStoreState): TaskDetailActivity[] =>+ activeTaskActivities(s).filter((a) => a.type === 'topic');++const activeTaskComments = (s: TaskStoreState): TaskDetailActivity[] =>+ activeTaskActivities(s).filter((a) => a.type === 'comment');++const unresolvedBriefCount = (s: TaskStoreState): number =>+ activeTaskBriefs(s).filter((b) => !b.resolvedAction).length;++const hasUnresolvedBriefs = (s: TaskStoreState): boolean => unresolvedBriefCount(s) > 0;++export const taskActivitySelectors = {+ activeTaskActivities,+ activeTaskBriefs,+ activeTaskComments,+ activeTaskTopics,+ hasUnresolvedBriefs,+ unresolvedBriefCount,+};diff --git a/src/store/task/selectors/detailSelectors.test.ts b/src/store/task/selectors/detailSelectors.test.tsnew file mode 100644index 00000000000..506aef92b46--- /dev/null+++ b/src/store/task/selectors/detailSelectors.test.ts@@ -0,0 +1,236 @@+import type { TaskDetailData } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { TaskStoreState } from '../initialState';+import { initialState } from '../initialState';+import { taskDetailSelectors } from './detailSelectors';++const mockDetail: TaskDetailData = {+ agentId: 'agt_1',+ checkpoint: { onAgentRequest: true },+ config: { model: 'gpt-4o', provider: 'openai' },+ dependencies: [{ dependsOn: 'T-2', type: 'blocks' }],+ description: 'A test task',+ error: null,+ heartbeat: { interval: 300, timeout: null },+ identifier: 'T-1',+ instruction: 'Do something',+ name: 'Test Task',+ parent: { identifier: 'T-0', name: 'Parent' },+ priority: 2,+ review: { enabled: false },+ status: 'running',+ subtasks: [{ identifier: 'T-1-1', name: 'Sub', status: 'backlog' }],+ topicCount: 3,+ workspace: [],+};++const createState = (overrides: Partial<TaskStoreState> = {}): TaskStoreState => ({+ ...initialState,+ ...overrides,+});++describe('taskDetailSelectors', () => {+ describe('activeTaskDetail', () => {+ it('should return undefined when no active task', () => {+ const state = createState();+ expect(taskDetailSelectors.activeTaskDetail(state)).toBeUndefined();+ });++ it('should return detail from map when activeTaskId is set', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': mockDetail },+ });+ expect(taskDetailSelectors.activeTaskDetail(state)).toEqual(mockDetail);+ });+ });++ describe('field selectors', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': mockDetail },+ });++ it('should return activeTaskName', () => {+ expect(taskDetailSelectors.activeTaskName(state)).toBe('Test Task');+ });++ it('should return activeTaskStatus', () => {+ expect(taskDetailSelectors.activeTaskStatus(state)).toBe('running');+ });++ it('should return activeTaskPriority', () => {+ expect(taskDetailSelectors.activeTaskPriority(state)).toBe(2);+ });++ it('should return default priority when no detail', () => {+ expect(taskDetailSelectors.activeTaskPriority(createState())).toBe(0);+ });++ it('should return activeTaskInstruction', () => {+ expect(taskDetailSelectors.activeTaskInstruction(state)).toBe('Do something');+ });++ it('should return activeTaskAgentId', () => {+ expect(taskDetailSelectors.activeTaskAgentId(state)).toBe('agt_1');+ });++ it('should return activeTaskModel', () => {+ expect(taskDetailSelectors.activeTaskModel(state)).toBe('gpt-4o');+ });++ it('should return activeTaskProvider', () => {+ expect(taskDetailSelectors.activeTaskProvider(state)).toBe('openai');+ });++ it('should return undefined model/provider when no config', () => {+ const noConfigState = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, config: undefined } },+ });+ expect(taskDetailSelectors.activeTaskModel(noConfigState)).toBeUndefined();+ expect(taskDetailSelectors.activeTaskProvider(noConfigState)).toBeUndefined();+ });++ it('should return activeTaskPeriodicInterval from heartbeat', () => {+ expect(taskDetailSelectors.activeTaskPeriodicInterval(state)).toBe(300);+ });++ it('should return 0 for periodicInterval when no heartbeat', () => {+ const noHbState = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, heartbeat: undefined } },+ });+ expect(taskDetailSelectors.activeTaskPeriodicInterval(noHbState)).toBe(0);+ });++ it('should return activeTaskSubtasks', () => {+ expect(taskDetailSelectors.activeTaskSubtasks(state)).toHaveLength(1);+ });++ it('should return empty array when no subtasks', () => {+ expect(taskDetailSelectors.activeTaskSubtasks(createState())).toEqual([]);+ });++ it('should return activeTaskParent', () => {+ expect(taskDetailSelectors.activeTaskParent(state)?.identifier).toBe('T-0');+ });++ it('should return activeTaskTopicCount', () => {+ expect(taskDetailSelectors.activeTaskTopicCount(state)).toBe(3);+ });+ });++ describe('canRunActiveTask', () => {+ it('should return true for backlog task with agentId', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, status: 'backlog' } },+ });+ expect(taskDetailSelectors.canRunActiveTask(state)).toBe(true);+ });++ it('should return true for paused task with agentId', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, status: 'paused' } },+ });+ expect(taskDetailSelectors.canRunActiveTask(state)).toBe(true);+ });++ it('should return true for failed task with agentId', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, status: 'failed' } },+ });+ expect(taskDetailSelectors.canRunActiveTask(state)).toBe(true);+ });++ it('should return false for running task', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, status: 'running' } },+ });+ expect(taskDetailSelectors.canRunActiveTask(state)).toBe(false);+ });++ it('should return false when no agentId', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, agentId: null } },+ });+ expect(taskDetailSelectors.canRunActiveTask(state)).toBe(false);+ });+ });++ describe('canPauseActiveTask', () => {+ it('should return true for running task', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, status: 'running' } },+ });+ expect(taskDetailSelectors.canPauseActiveTask(state)).toBe(true);+ });++ it('should return false for non-running task', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, status: 'paused' } },+ });+ expect(taskDetailSelectors.canPauseActiveTask(state)).toBe(false);+ });+ });++ describe('canCancelActiveTask', () => {+ it.each(['running', 'paused', 'backlog'] as const)(+ 'should return true for %s task',+ (status) => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, status } },+ });+ expect(taskDetailSelectors.canCancelActiveTask(state)).toBe(true);+ },+ );++ it.each(['completed', 'canceled'] as const)('should return false for %s task', (status) => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail, status } },+ });+ expect(taskDetailSelectors.canCancelActiveTask(state)).toBe(false);+ });+ });++ describe('isTaskDetailLoading', () => {+ it('should return true when no activeTaskId', () => {+ expect(taskDetailSelectors.isTaskDetailLoading(createState())).toBe(true);+ });++ it('should return true when detail not in map', () => {+ const state = createState({ activeTaskId: 'T-1', taskDetailMap: {} });+ expect(taskDetailSelectors.isTaskDetailLoading(state)).toBe(true);+ });++ it('should return false when detail exists', () => {+ const state = createState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': mockDetail },+ });+ expect(taskDetailSelectors.isTaskDetailLoading(state)).toBe(false);+ });+ });++ describe('taskDetailById', () => {+ it('should return detail for given id', () => {+ const state = createState({ taskDetailMap: { 'T-1': mockDetail } });+ expect(taskDetailSelectors.taskDetailById('T-1')(state)).toEqual(mockDetail);+ });++ it('should return undefined for missing id', () => {+ const state = createState({ taskDetailMap: {} });+ expect(taskDetailSelectors.taskDetailById('T-999')(state)).toBeUndefined();+ });+ });+});diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.tsnew file mode 100644index 00000000000..9fc03329711--- /dev/null+++ b/src/store/task/selectors/detailSelectors.ts@@ -0,0 +1,97 @@+import type { TaskDetailData } from '@lobechat/types';++import type { TaskStoreState } from '../initialState';++const activeTaskId = (s: TaskStoreState) => s.activeTaskId;++const activeTaskDetail = (s: TaskStoreState): TaskDetailData | undefined =>+ s.activeTaskId ? s.taskDetailMap[s.activeTaskId] : undefined;++const taskDetailById = (id: string) => (s: TaskStoreState) => s.taskDetailMap[id];++const isTaskDetailLoading = (s: TaskStoreState): boolean =>+ !s.activeTaskId || !s.taskDetailMap[s.activeTaskId];++const activeTaskName = (s: TaskStoreState) => activeTaskDetail(s)?.name;++const activeTaskStatus = (s: TaskStoreState) => activeTaskDetail(s)?.status;++const activeTaskPriority = (s: TaskStoreState) => activeTaskDetail(s)?.priority ?? 0;++const activeTaskInstruction = (s: TaskStoreState) => activeTaskDetail(s)?.instruction;++const activeTaskDescription = (s: TaskStoreState) => activeTaskDetail(s)?.description;++const activeTaskAgentId = (s: TaskStoreState) => activeTaskDetail(s)?.agentId;++// TODO [LOBE-6634]: 等后端 getTaskDetail 返回 model/provider 后,改为读 detail.model / detail.provider+const activeTaskModel = (s: TaskStoreState) =>+ activeTaskDetail(s)?.config?.model as string | undefined;++const activeTaskProvider = (s: TaskStoreState) =>+ activeTaskDetail(s)?.config?.provider as string | undefined;++const activeTaskSubtasks = (s: TaskStoreState) => activeTaskDetail(s)?.subtasks ?? [];++const activeTaskDependencies = (s: TaskStoreState) => activeTaskDetail(s)?.dependencies ?? [];++const activeTaskParent = (s: TaskStoreState) => activeTaskDetail(s)?.parent;++// 周期执行间隔(秒),0 或 undefined 表示未配置+const activeTaskPeriodicInterval = (s: TaskStoreState) =>+ activeTaskDetail(s)?.heartbeat?.interval ?? 0;++const activeTaskCheckpoint = (s: TaskStoreState) => activeTaskDetail(s)?.checkpoint;++const activeTaskReview = (s: TaskStoreState) => activeTaskDetail(s)?.review;++const activeTaskWorkspace = (s: TaskStoreState) => activeTaskDetail(s)?.workspace ?? [];++const activeTaskError = (s: TaskStoreState) => activeTaskDetail(s)?.error;++const activeTaskTopicCount = (s: TaskStoreState) => activeTaskDetail(s)?.topicCount ?? 0;++const canRunActiveTask = (s: TaskStoreState): boolean => {+ const detail = activeTaskDetail(s);+ if (!detail) return false;+ return ['backlog', 'failed', 'paused'].includes(detail.status) && !!detail.agentId;+};++const canPauseActiveTask = (s: TaskStoreState): boolean =>+ activeTaskDetail(s)?.status === 'running';++const canCancelActiveTask = (s: TaskStoreState): boolean => {+ const detail = activeTaskDetail(s);+ if (!detail) return false;+ return ['backlog', 'paused', 'running'].includes(detail.status);+};++const taskSaveStatus = (s: TaskStoreState) => s.taskSaveStatus;++export const taskDetailSelectors = {+ activeTaskAgentId,+ activeTaskCheckpoint,+ activeTaskModel,+ activeTaskDependencies,+ activeTaskDescription,+ activeTaskDetail,+ activeTaskError,+ activeTaskId,+ activeTaskInstruction,+ activeTaskName,+ activeTaskParent,+ activeTaskPeriodicInterval,+ activeTaskPriority,+ activeTaskProvider,+ activeTaskReview,+ activeTaskStatus,+ activeTaskSubtasks,+ activeTaskTopicCount,+ activeTaskWorkspace,+ canCancelActiveTask,+ canPauseActiveTask,+ canRunActiveTask,+ isTaskDetailLoading,+ taskDetailById,+ taskSaveStatus,+};diff --git a/src/store/task/selectors/index.ts b/src/store/task/selectors/index.tsnew file mode 100644index 00000000000..d074162ffa0--- /dev/null+++ b/src/store/task/selectors/index.ts@@ -0,0 +1,3 @@+export { taskActivitySelectors } from './activitySelectors';+export { taskDetailSelectors } from './detailSelectors';+export { taskListSelectors } from './listSelectors';diff --git a/src/store/task/selectors/listSelectors.test.ts b/src/store/task/selectors/listSelectors.test.tsnew file mode 100644index 00000000000..9475f7513b1--- /dev/null+++ b/src/store/task/selectors/listSelectors.test.ts@@ -0,0 +1,147 @@+import { describe, expect, it } from 'vitest';++import type { TaskStoreState } from '../initialState';+import { initialState } from '../initialState';+import { taskListSelectors } from './listSelectors';++const createState = (overrides: Partial<TaskStoreState> = {}): TaskStoreState => ({+ ...initialState,+ ...overrides,+});++describe('taskListSelectors', () => {+ describe('getDisplayStatus', () => {+ it('should map backend statuses to UI labels', () => {+ expect(taskListSelectors.getDisplayStatus('backlog')).toBe('Backlog');+ expect(taskListSelectors.getDisplayStatus('running')).toBe('In progress');+ expect(taskListSelectors.getDisplayStatus('paused')).toBe('Needs input');+ expect(taskListSelectors.getDisplayStatus('failed')).toBe('Needs input');+ expect(taskListSelectors.getDisplayStatus('completed')).toBe('Done');+ expect(taskListSelectors.getDisplayStatus('canceled')).toBe('Canceled');+ });++ it('should return raw status for unknown values', () => {+ expect(taskListSelectors.getDisplayStatus('unknown')).toBe('unknown');+ });+ });++ describe('kanban column selectors (from taskGroups)', () => {+ const taskGroups = [+ {+ hasMore: false,+ key: 'backlog',+ limit: 50,+ offset: 0,+ tasks: [{ identifier: 'T-1', status: 'backlog' }],+ total: 1,+ },+ {+ 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 viewMode', () => {+ expect(taskListSelectors.viewMode(createState({ viewMode: 'kanban' }))).toBe('kanban');+ });++ it('should return isTaskListInit', () => {+ expect(taskListSelectors.isTaskListInit(createState({ isTaskListInit: true }))).toBe(true);+ });++ it('should return taskListTotal', () => {+ expect(taskListSelectors.taskListTotal(createState({ tasksTotal: 42 }))).toBe(42);+ });++ it('should return isTaskGroupListInit', () => {+ expect(+ taskListSelectors.isTaskGroupListInit(createState({ isTaskGroupListInit: true })),+ ).toBe(true);+ });+ });+});diff --git a/src/store/task/selectors/listSelectors.ts b/src/store/task/selectors/listSelectors.tsnew file mode 100644index 00000000000..e7364cf030c--- /dev/null+++ b/src/store/task/selectors/listSelectors.ts@@ -0,0 +1,56 @@+import type { TaskStoreState } from '../initialState';+import type { TaskGroupItem, TaskListItem } from '../slices/list/initialState';++const taskList = (s: TaskStoreState): TaskListItem[] => s.tasks;++const taskListTotal = (s: TaskStoreState) => s.tasksTotal;++const isTaskListInit = (s: TaskStoreState) => s.isTaskListInit;++const viewMode = (s: TaskStoreState) => s.viewMode;++const statusDisplayMap: Record<string, string> = {+ backlog: 'Backlog',+ canceled: 'Canceled',+ completed: 'Done',+ failed: 'Needs input',+ paused: 'Needs input',+ running: 'In progress',+};++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 ?? [];++const needsInputTasks = (s: TaskStoreState) => taskGroupByKey('needsInput')(s)?.tasks ?? [];++const doneTasks = (s: TaskStoreState) => taskGroupByKey('done')(s)?.tasks ?? [];++const isListEmpty = (s: TaskStoreState) => s.isTaskListInit && s.tasks.length === 0;++export const taskListSelectors = {+ backlogTasks,+ doneTasks,+ getDisplayStatus,+ isListEmpty,+ isTaskGroupListInit,+ isTaskListInit,+ needsInputTasks,+ runningTasks,+ taskGroupByKey,+ taskGroups,+ taskList,+ taskListTotal,+ viewMode,+};diff --git a/src/store/task/slices/config/action.test.ts b/src/store/task/slices/config/action.test.tsnew file mode 100644index 00000000000..fc73af68e10--- /dev/null+++ b/src/store/task/slices/config/action.test.ts@@ -0,0 +1,159 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { taskService } from '@/services/task';++import { useTaskStore } from '../../store';++vi.mock('@/services/task', () => ({+ taskService: {+ markBriefRead: vi.fn(),+ resolveBrief: vi.fn(),+ runReview: vi.fn(),+ update: vi.fn(),+ updateCheckpoint: vi.fn(),+ updateConfig: vi.fn(),+ updateReview: vi.fn(),+ },+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(),+}));++const mockDetail = {+ checkpoint: { onAgentRequest: false },+ identifier: 'T-1',+ instruction: 'Test',+ review: null,+ status: 'backlog',+} as any;++beforeEach(() => {+ vi.clearAllMocks();+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail } },+ });+});++describe('TaskConfigSliceAction', () => {+ describe('updateCheckpoint', () => {+ it('should optimistically update and call service', async () => {+ vi.mocked(taskService.updateCheckpoint).mockResolvedValue({ success: true } as any);++ const checkpoint = { onAgentRequest: true };+ await useTaskStore.getState().updateCheckpoint('T-1', checkpoint);++ expect(useTaskStore.getState().taskDetailMap['T-1'].checkpoint).toEqual(checkpoint);+ expect(taskService.updateCheckpoint).toHaveBeenCalledWith('T-1', checkpoint);+ });++ it('should refresh on error', async () => {+ const { mutate } = await import('@/libs/swr');+ vi.mocked(taskService.updateCheckpoint).mockRejectedValue(new Error('fail'));++ await useTaskStore.getState().updateCheckpoint('T-1', { onAgentRequest: true });++ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ });+ });++ describe('updateReview', () => {+ it('should optimistically update and call service', async () => {+ vi.mocked(taskService.updateReview).mockResolvedValue({ success: true } as any);++ const review = { enabled: true, rubrics: [] };+ await useTaskStore.getState().updateReview('T-1', review as any);++ expect(useTaskStore.getState().taskDetailMap['T-1'].review).toEqual(review);+ expect(taskService.updateReview).toHaveBeenCalledWith({ id: 'T-1', review });+ });+ });++ 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,+ success: true,+ } as any);++ const result = await useTaskStore.getState().runReview('T-1', { content: 'Test output' });++ expect(taskService.runReview).toHaveBeenCalledWith('T-1', { content: 'Test output' });+ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ expect(result).toEqual({ data: mockResult, success: true });+ });++ it('should throw on error', async () => {+ vi.mocked(taskService.runReview).mockRejectedValue(new Error('review failed'));++ await expect(useTaskStore.getState().runReview('T-1', { content: 'Test' })).rejects.toThrow(+ 'review failed',+ );+ });+ });++ describe('updateTaskModelConfig', () => {+ it('should call updateConfig with model/provider and refresh detail', async () => {+ const { mutate } = await import('@/libs/swr');+ vi.mocked(taskService.updateConfig).mockResolvedValue({ success: true } as any);++ await useTaskStore+ .getState()+ .updateTaskModelConfig('T-1', { model: 'claude-sonnet-4-6', provider: 'anthropic' });++ expect(taskService.updateConfig).toHaveBeenCalledWith('T-1', {+ model: 'claude-sonnet-4-6',+ provider: 'anthropic',+ });+ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ });+ });++ 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(['fetchTaskDetail', 'T-1']);+ });++ it('should send 0 when null to disable', async () => {+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().updatePeriodicInterval('T-1', null);++ expect(taskService.update).toHaveBeenCalledWith('T-1', { heartbeatInterval: 0 });+ });+ });++ 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(['fetchTaskDetail', 'T-1']);+ });+ });++ 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(['fetchTaskDetail', 'T-1']);+ });+ });+});diff --git a/src/store/task/slices/config/action.ts b/src/store/task/slices/config/action.tsnew file mode 100644index 00000000000..481da278fe5--- /dev/null+++ b/src/store/task/slices/config/action.ts@@ -0,0 +1,114 @@+import type { CheckpointConfig } from '@lobechat/types';++import { taskService } from '@/services/task';+import type { StoreSetter } from '@/store/types';++import type { TaskStore } from '../../store';++type Setter = StoreSetter<TaskStore>;++export const createTaskConfigSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>+ new TaskConfigSliceActionImpl(set, get, _api);++export class TaskConfigSliceActionImpl {+ readonly #get: () => TaskStore;++ constructor(set: Setter, get: () => TaskStore, _api?: unknown) {+ void _api;+ void set;+ this.#get = get;+ }++ markBriefRead = async (briefId: string): Promise<void> => {+ await taskService.markBriefRead(briefId);+ const { activeTaskId, internal_refreshTaskDetail } = this.#get();+ if (activeTaskId) await internal_refreshTaskDetail(activeTaskId);+ };++ resolveBrief = async (+ briefId: string,+ opts?: { action?: string; comment?: string },+ ): Promise<void> => {+ await taskService.resolveBrief(briefId, opts);+ const { activeTaskId, internal_refreshTaskDetail } = this.#get();+ if (activeTaskId) await internal_refreshTaskDetail(activeTaskId);+ };++ runReview = async (id: string, params?: { content?: string; topicId?: string }) => {+ try {+ const result = await taskService.runReview(id, params);+ await this.#get().internal_refreshTaskDetail(id);+ return result;+ } catch (error) {+ console.error('[TaskStore] Failed to run review:', error);+ throw error;+ }+ };++ updateCheckpoint = async (id: string, checkpoint: CheckpointConfig): Promise<void> => {+ this.#get().internal_dispatchTaskDetail({+ id,+ type: 'updateTaskDetail',+ value: { checkpoint },+ });++ try {+ await taskService.updateCheckpoint(id, checkpoint);+ await this.#get().internal_refreshTaskDetail(id);+ } catch (error) {+ console.error('[TaskStore] Failed to update checkpoint:', error);+ await this.#get().internal_refreshTaskDetail(id);+ }+ };++ updateReview = async (+ id: string,+ review: Parameters<typeof taskService.updateReview>[0]['review'],+ ): Promise<void> => {+ this.#get().internal_dispatchTaskDetail({+ id,+ type: 'updateTaskDetail',+ value: { review },+ });++ try {+ await taskService.updateReview({ id, review });+ await this.#get().internal_refreshTaskDetail(id);+ } catch (error) {+ console.error('[TaskStore] Failed to update review:', error);+ await this.#get().internal_refreshTaskDetail(id);+ }+ };++ // 通过 task.updateConfig 安全 merge model/provider 到 config,不会覆盖 checkpoint/review+ updateTaskModelConfig = async (+ id: string,+ modelConfig: { model?: string; provider?: string },+ ): Promise<void> => {+ try {+ await taskService.updateConfig(id, modelConfig);+ await this.#get().internal_refreshTaskDetail(id);+ } catch (error) {+ console.error('[TaskStore] Failed to update task model config:', error);+ }+ };++ // 配置周期执行间隔(heartbeatInterval 字段,单位:秒,null 或 0 禁用)+ // 后端周期执行逻辑待 LOBE-6587 就绪后自动生效,前端可先完成 UI 配置+ updatePeriodicInterval = async (id: string, interval: number | null): Promise<void> => {+ try {+ await taskService.update(id, { heartbeatInterval: interval ?? 0 });+ await this.#get().internal_refreshTaskDetail(id);+ } catch (error) {+ console.error('[TaskStore] Failed to update periodic interval:', error);+ }+ };++ // TODO [LOBE-6587]: 定时任务(cron 模式)+ // updateSchedule(id, { pattern, timezone }) — 后端 task.update schema 尚未暴露 schedulePattern/scheduleTimezone+}++export type TaskConfigSliceAction = Pick<+ TaskConfigSliceActionImpl,+ keyof TaskConfigSliceActionImpl+>;diff --git a/src/store/task/slices/config/index.ts b/src/store/task/slices/config/index.tsnew file mode 100644index 00000000000..22ffe9f672c--- /dev/null+++ b/src/store/task/slices/config/index.ts@@ -0,0 +1,2 @@+export type { TaskConfigSliceAction } from './action';+export { createTaskConfigSlice } from './action';diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsnew file mode 100644index 00000000000..7443b08ad0c--- /dev/null+++ b/src/store/task/slices/detail/action.test.ts@@ -0,0 +1,218 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { taskService } from '@/services/task';++import { useTaskStore } from '../../store';++vi.mock('@/services/task', () => ({+ taskService: {+ addComment: vi.fn(),+ addDependency: vi.fn(),+ create: vi.fn(),+ delete: vi.fn(),+ getDetail: vi.fn(),+ pinDocument: vi.fn(),+ removeDependency: vi.fn(),+ reorderSubtasks: vi.fn(),+ unpinDocument: vi.fn(),+ update: vi.fn(),+ },+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(),+}));++beforeEach(() => {+ vi.clearAllMocks();+ useTaskStore.setState({+ activeTaskId: undefined,+ isCreatingTask: false,+ isDeletingTask: false,+ taskDetailMap: {},+ taskSaveStatus: 'idle',+ });+});++describe('TaskDetailSliceAction', () => {+ describe('setActiveTaskId', () => {+ it('should set activeTaskId', () => {+ useTaskStore.getState().setActiveTaskId('T-1');+ expect(useTaskStore.getState().activeTaskId).toBe('T-1');+ });++ it('should not update if same id', () => {+ useTaskStore.setState({ activeTaskId: 'T-1' });+ const spy = vi.fn();+ useTaskStore.subscribe(spy);++ useTaskStore.getState().setActiveTaskId('T-1');+ // Should not trigger state change+ expect(spy).not.toHaveBeenCalled();+ });+ });++ describe('createTask', () => {+ it('should call service and return identifier', async () => {+ vi.mocked(taskService.create).mockResolvedValue({+ data: { identifier: 'T-1' },+ message: 'ok',+ success: true,+ } as any);++ const result = await useTaskStore.getState().createTask({+ instruction: 'Do something',+ name: 'Test',+ });++ expect(taskService.create).toHaveBeenCalledWith({+ instruction: 'Do something',+ name: 'Test',+ });+ expect(result).toBe('T-1');+ });++ it('should set isCreatingTask during creation', async () => {+ vi.mocked(taskService.create).mockImplementation(async () => {+ expect(useTaskStore.getState().isCreatingTask).toBe(true);+ return { data: { identifier: 'T-1' }, success: true } as any;+ });++ await useTaskStore.getState().createTask({ instruction: 'Test' });+ expect(useTaskStore.getState().isCreatingTask).toBe(false);+ });++ it('should return null on error', async () => {+ vi.mocked(taskService.create).mockRejectedValue(new Error('fail'));++ const result = await useTaskStore.getState().createTask({ instruction: 'Test' });+ expect(result).toBeNull();+ expect(useTaskStore.getState().isCreatingTask).toBe(false);+ });+ });++ describe('updateTask', () => {+ it('should optimistically update taskDetailMap', async () => {+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': { identifier: 'T-1', instruction: 'Old', name: 'Old Name', status: 'backlog' },+ },+ });++ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().updateTask('T-1', { name: 'New Name' });++ expect(useTaskStore.getState().taskDetailMap['T-1'].name).toBe('New Name');+ expect(taskService.update).toHaveBeenCalledWith('T-1', { name: 'New Name' });+ expect(useTaskStore.getState().taskSaveStatus).toBe('saved');+ });++ it('should refresh on error', async () => {+ const { mutate } = await import('@/libs/swr');+ useTaskStore.setState({+ taskDetailMap: {+ 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },+ },+ });++ vi.mocked(taskService.update).mockRejectedValue(new Error('fail'));++ await useTaskStore.getState().updateTask('T-1', { name: 'New' });++ expect(useTaskStore.getState().taskSaveStatus).toBe('idle');+ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-1']);+ });+ });++ describe('deleteTask', () => {+ it('should remove from map and clear activeTaskId', async () => {+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },+ },+ });++ vi.mocked(taskService.delete).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().deleteTask('T-1');++ expect(useTaskStore.getState().taskDetailMap['T-1']).toBeUndefined();+ expect(useTaskStore.getState().activeTaskId).toBeUndefined();+ });++ it('should set isDeletingTask during deletion', async () => {+ useTaskStore.setState({+ taskDetailMap: {+ 'T-1': { identifier: 'T-1', instruction: 'Test', status: 'backlog' },+ },+ });++ vi.mocked(taskService.delete).mockImplementation(async () => {+ expect(useTaskStore.getState().isDeletingTask).toBe(true);+ return { success: true } as any;+ });++ await useTaskStore.getState().deleteTask('T-1');+ expect(useTaskStore.getState().isDeletingTask).toBe(false);+ });+ });++ 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(['fetchTaskDetail', 'T-1']);+ });+ });++ 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(['fetchTaskDetail', 'T-1']);+ });+ });++ describe('internal_dispatchTaskDetail', () => {+ it('should set task detail via reducer', () => {+ const detail = { identifier: 'T-1', instruction: 'Test', status: 'backlog' } as any;++ useTaskStore.getState().internal_dispatchTaskDetail({+ id: 'T-1',+ type: 'setTaskDetail',+ value: detail,+ });++ expect(useTaskStore.getState().taskDetailMap['T-1']).toEqual(detail);+ });++ it('should not update state if reducer returns same reference', () => {+ const detail = { identifier: 'T-1', instruction: 'Test', status: 'backlog' } as any;+ useTaskStore.setState({ taskDetailMap: { 'T-1': detail } });++ const spy = vi.fn();+ useTaskStore.subscribe(spy);++ // Update with non-existent id — reducer returns same state+ useTaskStore.getState().internal_dispatchTaskDetail({+ id: 'T-999',+ type: 'updateTaskDetail',+ value: { name: 'Ghost' },+ });++ expect(spy).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsnew file mode 100644index 00000000000..70f4581ba05--- /dev/null+++ b/src/store/task/slices/detail/action.ts@@ -0,0 +1,184 @@+import type { TaskDetailData } from '@lobechat/types';+import isEqual from 'fast-deep-equal';++import { mutate, useClientDataSWR } from '@/libs/swr';+import { taskService } from '@/services/task';+import type { StoreSetter } from '@/store/types';++import type { TaskStore } from '../../store';+import type { TaskDetailDispatch } from './reducer';+import { taskDetailReducer } from './reducer';++// config / heartbeatInterval / heartbeatTimeout 不在此处暴露:+// - model/provider 走 configSlice.updateTaskModelConfig+// - checkpoint 走 configSlice.updateCheckpoint+// - review 走 configSlice.updateReview+// - heartbeat 配置待 LOBE-6587 上游 infra 完成后新增专用 action+export interface TaskUpdatePayload {+ assigneeAgentId?: string | null;+ description?: string;+ instruction?: string;+ name?: string;+ priority?: number;+}++const FETCH_TASK_DETAIL_KEY = 'fetchTaskDetail';++type Setter = StoreSetter<TaskStore>;++export const createTaskDetailSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>+ new TaskDetailSliceActionImpl(set, get, _api);++export class TaskDetailSliceActionImpl {+ readonly #get: () => TaskStore;+ readonly #set: Setter;++ constructor(set: Setter, get: () => TaskStore, _api?: unknown) {+ void _api;+ this.#set = set;+ this.#get = get;+ }++ // ── Public Actions ──++ addComment = async (+ taskId: string,+ content: string,+ opts?: { briefId?: string; topicId?: string },+ ): Promise<void> => {+ await taskService.addComment(taskId, content, opts);+ await this.internal_refreshTaskDetail(taskId);+ };++ addDependency = async (+ taskId: string,+ dependsOnId: string,+ type?: 'blocks' | 'relates',+ ): Promise<void> => {+ await taskService.addDependency(taskId, dependsOnId, type);+ await this.internal_refreshTaskDetail(taskId);+ };++ createTask = async (params: {+ assigneeAgentId?: string;+ description?: string;+ instruction: string;+ name?: string;+ parentTaskId?: string;+ priority?: number;+ }): Promise<string | null> => {+ this.#set({ isCreatingTask: true }, false, 'createTask/start');+ try {+ const result = await taskService.create(params);+ await this.#get().refreshTaskList();+ return result.data?.identifier ?? null;+ } catch (error) {+ console.error('[TaskStore] Failed to create task:', error);+ return null;+ } finally {+ this.#set({ isCreatingTask: false }, false, 'createTask/end');+ }+ };++ deleteTask = async (id: string): Promise<void> => {+ this.#set({ isDeletingTask: true }, false, 'deleteTask/start');+ try {+ this.internal_dispatchTaskDetail({ id, type: 'deleteTaskDetail' });++ await taskService.delete(id);++ if (this.#get().activeTaskId === id) {+ this.#set({ activeTaskId: undefined }, false, 'deleteTask/clearActive');+ }++ await this.#get().refreshTaskList();+ } catch (error) {+ console.error('[TaskStore] Failed to delete task:', error);+ await this.internal_refreshTaskDetail(id);+ } finally {+ this.#set({ isDeletingTask: false }, false, 'deleteTask/end');+ }+ };++ pinDocument = async (taskId: string, documentId: string): Promise<void> => {+ await taskService.pinDocument(taskId, documentId);+ await this.internal_refreshTaskDetail(taskId);+ };++ removeDependency = async (taskId: string, dependsOnId: string): Promise<void> => {+ await taskService.removeDependency(taskId, dependsOnId);+ await this.internal_refreshTaskDetail(taskId);+ };++ reorderSubtasks = async (taskId: string, order: string[]): Promise<void> => {+ await taskService.reorderSubtasks(taskId, order);+ await this.internal_refreshTaskDetail(taskId);+ };++ setActiveTaskId = (taskId?: string): void => {+ if (this.#get().activeTaskId === taskId) return;+ this.#set({ activeTaskId: taskId }, false, 'setActiveTaskId');+ };++ unpinDocument = async (taskId: string, documentId: string): Promise<void> => {+ await taskService.unpinDocument(taskId, documentId);+ await this.internal_refreshTaskDetail(taskId);+ };++ updateTask = async (id: string, data: TaskUpdatePayload): Promise<void> => {+ // Optimistic update — all fields in TaskUpdatePayload directly map to TaskDetailData+ this.internal_dispatchTaskDetail({ id, type: 'updateTaskDetail', value: data });+ this.#set({ taskSaveStatus: 'saving' }, false, 'updateTask/saving');++ try {+ await taskService.update(id, data);+ this.#set({ taskSaveStatus: 'saved' }, false, 'updateTask/saved');+ } catch (error) {+ console.error('[TaskStore] Failed to update task:', error);+ this.#set({ taskSaveStatus: 'idle' }, false, 'updateTask/error');+ // Revert by refreshing from server+ await this.internal_refreshTaskDetail(id);+ }+ };++ useFetchTaskDetail = (taskId?: string) => {+ return useClientDataSWR(+ taskId ? [FETCH_TASK_DETAIL_KEY, taskId] : null,+ async ([, id]: [string, string]) => {+ const result = await taskService.getDetail(id);+ return result.data;+ },+ {+ onSuccess: (data: TaskDetailData) => {+ if (data && taskId) {+ this.internal_dispatchTaskDetail({+ id: taskId,+ type: 'setTaskDetail',+ value: data,+ });+ }+ },+ },+ );+ };++ // ── Internal Actions ──++ internal_dispatchTaskDetail = (payload: TaskDetailDispatch): void => {+ const currentMap = this.#get().taskDetailMap;+ const nextMap = taskDetailReducer(currentMap, payload);++ if (isEqual(nextMap, currentMap)) return;++ this.#set({ taskDetailMap: nextMap }, false, `internal_dispatchTaskDetail/${payload.type}`);+ };++ internal_refreshTaskDetail = async (id: string): Promise<void> => {+ await mutate([FETCH_TASK_DETAIL_KEY, id]);+ };+}++export type TaskDetailSliceAction = Pick<+ TaskDetailSliceActionImpl,+ keyof TaskDetailSliceActionImpl+>;diff --git a/src/store/task/slices/detail/index.ts b/src/store/task/slices/detail/index.tsnew file mode 100644index 00000000000..c45bbc91684--- /dev/null+++ b/src/store/task/slices/detail/index.ts@@ -0,0 +1,4 @@+export type { TaskDetailSliceAction } from './action';+export { createTaskDetailSlice } from './action';+export type { TaskDetailSliceState } from './initialState';+export { initialTaskDetailSliceState } from './initialState';diff --git a/src/store/task/slices/detail/initialState.ts b/src/store/task/slices/detail/initialState.tsnew file mode 100644index 00000000000..2a7b8d57023--- /dev/null+++ b/src/store/task/slices/detail/initialState.ts@@ -0,0 +1,16 @@+import type { TaskDetailData } from '@lobechat/types';++export interface TaskDetailSliceState {+ activeTaskId?: string;+ isCreatingTask: boolean;+ isDeletingTask: boolean;+ taskDetailMap: Record<string, TaskDetailData>;+ taskSaveStatus: 'idle' | 'saved' | 'saving';+}++export const initialTaskDetailSliceState: TaskDetailSliceState = {+ isCreatingTask: false,+ isDeletingTask: false,+ taskDetailMap: {},+ taskSaveStatus: 'idle',+};diff --git a/src/store/task/slices/detail/reducer.test.ts b/src/store/task/slices/detail/reducer.test.tsnew file mode 100644index 00000000000..c4042472801--- /dev/null+++ b/src/store/task/slices/detail/reducer.test.ts@@ -0,0 +1,121 @@+import type { TaskDetailData } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { TaskDetailDispatch } from './reducer';+import { taskDetailReducer } from './reducer';++const mockDetail: TaskDetailData = {+ identifier: 'T-1',+ instruction: 'Test instruction',+ name: 'Test Task',+ priority: 3,+ status: 'backlog',+};++const mockDetail2: TaskDetailData = {+ identifier: 'T-2',+ instruction: 'Another instruction',+ name: 'Another Task',+ status: 'running',+};++describe('taskDetailReducer', () => {+ describe('setTaskDetail', () => {+ it('should set a new task detail entry', () => {+ const state: Record<string, TaskDetailData> = {};+ const result = taskDetailReducer(state, {+ id: 'T-1',+ type: 'setTaskDetail',+ value: mockDetail,+ });++ expect(result['T-1']).toEqual(mockDetail);+ });++ it('should overwrite an existing entry', () => {+ const state: Record<string, TaskDetailData> = { 'T-1': mockDetail };+ const updated = { ...mockDetail, name: 'Updated Name' };+ const result = taskDetailReducer(state, {+ id: 'T-1',+ type: 'setTaskDetail',+ value: updated,+ });++ expect(result['T-1'].name).toBe('Updated Name');+ });++ it('should not affect other entries', () => {+ const state: Record<string, TaskDetailData> = { 'T-1': mockDetail };+ const result = taskDetailReducer(state, {+ id: 'T-2',+ type: 'setTaskDetail',+ value: mockDetail2,+ });++ expect(result['T-1']).toEqual(mockDetail);+ expect(result['T-2']).toEqual(mockDetail2);+ });+ });++ describe('updateTaskDetail', () => {+ it('should merge partial data into an existing entry', () => {+ const state: Record<string, TaskDetailData> = { 'T-1': mockDetail };+ const result = taskDetailReducer(state, {+ id: 'T-1',+ type: 'updateTaskDetail',+ value: { name: 'Updated', priority: 1 },+ });++ expect(result['T-1'].name).toBe('Updated');+ expect(result['T-1'].priority).toBe(1);+ expect(result['T-1'].instruction).toBe('Test instruction');+ });++ it('should not create entry if it does not exist', () => {+ const state: Record<string, TaskDetailData> = {};+ const result = taskDetailReducer(state, {+ id: 'T-999',+ type: 'updateTaskDetail',+ value: { name: 'Ghost' },+ });++ expect(result['T-999']).toBeUndefined();+ });+ });++ describe('deleteTaskDetail', () => {+ it('should remove an existing entry', () => {+ const state: Record<string, TaskDetailData> = {+ 'T-1': mockDetail,+ 'T-2': mockDetail2,+ };+ const result = taskDetailReducer(state, {+ id: 'T-1',+ type: 'deleteTaskDetail',+ });++ expect(result['T-1']).toBeUndefined();+ expect(result['T-2']).toEqual(mockDetail2);+ });++ it('should return state unchanged if id does not exist', () => {+ const state: Record<string, TaskDetailData> = { 'T-1': mockDetail };+ const result = taskDetailReducer(state, {+ id: 'T-999',+ type: 'deleteTaskDetail',+ });++ expect(result['T-1']).toEqual(mockDetail);+ });+ });++ it('should return state for unknown action type', () => {+ const state: Record<string, TaskDetailData> = { 'T-1': mockDetail };+ const result = taskDetailReducer(state, {+ id: 'T-1',+ type: 'unknown' as any,+ } as TaskDetailDispatch);++ expect(result).toBe(state);+ });+});diff --git a/src/store/task/slices/detail/reducer.ts b/src/store/task/slices/detail/reducer.tsnew file mode 100644index 00000000000..b2ae7bb6bcb--- /dev/null+++ b/src/store/task/slices/detail/reducer.ts@@ -0,0 +1,38 @@+import type { TaskDetailData } from '@lobechat/types';+import { produce } from 'immer';++export type TaskDetailDispatch =+ | { id: string; type: 'deleteTaskDetail' }+ | { id: string; type: 'setTaskDetail'; value: TaskDetailData }+ | { id: string; type: 'updateTaskDetail'; value: Partial<TaskDetailData> };++export const taskDetailReducer = (+ state: Record<string, TaskDetailData>,+ payload: TaskDetailDispatch,+): Record<string, TaskDetailData> => {+ switch (payload.type) {+ case 'setTaskDetail': {+ return produce(state, (draft) => {+ draft[payload.id] = payload.value;+ });+ }++ case 'updateTaskDetail': {+ return produce(state, (draft) => {+ if (draft[payload.id]) {+ Object.assign(draft[payload.id], payload.value);+ }+ });+ }++ case 'deleteTaskDetail': {+ return produce(state, (draft) => {+ delete draft[payload.id];+ });+ }++ default: {+ return state;+ }+ }+};diff --git a/src/store/task/slices/lifecycle/action.test.ts b/src/store/task/slices/lifecycle/action.test.tsnew file mode 100644index 00000000000..9ffa4a36e43--- /dev/null+++ b/src/store/task/slices/lifecycle/action.test.ts@@ -0,0 +1,148 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { taskService } from '@/services/task';++import { useTaskStore } from '../../store';++vi.mock('@/services/task', () => ({+ taskService: {+ cancelTopic: vi.fn(),+ deleteTopic: vi.fn(),+ run: vi.fn(),+ updateStatus: vi.fn(),+ },+}));++vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(),+}));++const mockDetail = { identifier: 'T-1', instruction: 'Test', status: 'backlog' } as any;++beforeEach(() => {+ vi.clearAllMocks();+ useTaskStore.setState({+ activeTaskId: 'T-1',+ taskDetailMap: { 'T-1': { ...mockDetail } },+ });+});++describe('TaskLifecycleSliceAction', () => {+ describe('runTask', () => {+ it('should optimistically set status to running and call service', async () => {+ vi.mocked(taskService.run).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().runTask('T-1');++ expect(taskService.run).toHaveBeenCalledWith('T-1', undefined);+ });++ it('should pass prompt and continueTopicId', async () => {+ vi.mocked(taskService.run).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().runTask('T-1', {+ continueTopicId: 'tpc_1',+ prompt: 'Focus on edge cases',+ });++ expect(taskService.run).toHaveBeenCalledWith('T-1', {+ continueTopicId: 'tpc_1',+ prompt: 'Focus on edge cases',+ });+ });++ 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(['fetchTaskDetail', 'T-1']);+ });+ });++ describe('pauseTask', () => {+ it('should call updateStatus with paused', async () => {+ vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().pauseTask('T-1');++ expect(taskService.updateStatus).toHaveBeenCalledWith('T-1', 'paused');+ });++ it('should optimistically set status', async () => {+ vi.mocked(taskService.updateStatus).mockImplementation(async () => {+ expect(useTaskStore.getState().taskDetailMap['T-1'].status).toBe('paused');+ return { success: true } as any;+ });++ await useTaskStore.getState().pauseTask('T-1');+ });+ });++ describe('cancelTask', () => {+ it('should call updateStatus with canceled', async () => {+ vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().cancelTask('T-1');++ expect(taskService.updateStatus).toHaveBeenCalledWith('T-1', 'canceled');+ });+ });++ describe('resumeTask', () => {+ it('should call updateStatus with backlog', async () => {+ vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().resumeTask('T-1');++ expect(taskService.updateStatus).toHaveBeenCalledWith('T-1', 'backlog');+ });+ });++ describe('completeTask', () => {+ it('should call updateStatus with completed', async () => {+ vi.mocked(taskService.updateStatus).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().completeTask('T-1');++ expect(taskService.updateStatus).toHaveBeenCalledWith('T-1', 'completed');+ });+ });++ 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(['fetchTaskDetail', 'T-1']);+ });++ it('should not refresh if no activeTaskId', async () => {+ const { mutate } = await import('@/libs/swr');+ useTaskStore.setState({ activeTaskId: undefined });+ vi.mocked(taskService.cancelTopic).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().cancelTopic('tpc_1');++ expect(taskService.cancelTopic).toHaveBeenCalledWith('tpc_1');+ expect(mutate).not.toHaveBeenCalled();+ });+ });++ 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(['fetchTaskDetail', 'T-1']);+ });+ });+});diff --git a/src/store/task/slices/lifecycle/action.ts b/src/store/task/slices/lifecycle/action.tsnew file mode 100644index 00000000000..cc453e3b49c--- /dev/null+++ b/src/store/task/slices/lifecycle/action.ts@@ -0,0 +1,97 @@+import type { TaskDetailData } from '@lobechat/types';++import { taskService } from '@/services/task';+import type { StoreSetter } from '@/store/types';++import type { TaskStore } from '../../store';++type Setter = StoreSetter<TaskStore>;++export const createTaskLifecycleSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>+ new TaskLifecycleSliceActionImpl(set, get, _api);++export class TaskLifecycleSliceActionImpl {+ readonly #get: () => TaskStore;++ constructor(set: Setter, get: () => TaskStore, _api?: unknown) {+ void _api;+ void set;+ this.#get = get;+ }++ cancelTask = async (id: string): Promise<void> => {+ await this.#transitionStatus(id, 'canceled');+ };++ cancelTopic = async (topicId: string): Promise<void> => {+ await taskService.cancelTopic(topicId);+ const { activeTaskId, internal_refreshTaskDetail } = this.#get();+ if (activeTaskId) await internal_refreshTaskDetail(activeTaskId);+ };++ completeTask = async (id: string): Promise<void> => {+ await this.#transitionStatus(id, 'completed');+ };++ deleteTopic = async (topicId: string): Promise<void> => {+ await taskService.deleteTopic(topicId);+ const { activeTaskId, internal_refreshTaskDetail } = this.#get();+ if (activeTaskId) await internal_refreshTaskDetail(activeTaskId);+ };++ pauseTask = async (id: string): Promise<void> => {+ await this.#transitionStatus(id, 'paused');+ };++ resumeTask = async (id: string): Promise<void> => {+ await this.#transitionStatus(id, 'backlog');+ };++ runTask = async (+ id: string,+ params?: { continueTopicId?: string; prompt?: string },+ ): Promise<void> => {+ this.#get().internal_dispatchTaskDetail({+ id,+ type: 'updateTaskDetail',+ value: { error: null, status: 'running' },+ });++ try {+ await taskService.run(id, params);+ await this.#get().internal_refreshTaskDetail(id);+ await this.#get().refreshTaskList();+ } catch (error) {+ console.error('[TaskStore] Failed to run task:', error);+ await this.#get().internal_refreshTaskDetail(id);+ }+ };++ // ── Private helper ──++ #transitionStatus = async (+ id: string,+ status: Parameters<typeof taskService.updateStatus>[1],+ extraUpdate?: Partial<TaskDetailData>,+ ): Promise<void> => {+ this.#get().internal_dispatchTaskDetail({+ id,+ type: 'updateTaskDetail',+ value: { status, ...extraUpdate },+ });++ try {+ await taskService.updateStatus(id, status);+ await this.#get().internal_refreshTaskDetail(id);+ await this.#get().refreshTaskList();+ } catch (error) {+ console.error(`[TaskStore] Failed to transition task to ${status}:`, error);+ await this.#get().internal_refreshTaskDetail(id);+ }+ };+}++export type TaskLifecycleSliceAction = Pick<+ TaskLifecycleSliceActionImpl,+ keyof TaskLifecycleSliceActionImpl+>;diff --git a/src/store/task/slices/lifecycle/index.ts b/src/store/task/slices/lifecycle/index.tsnew file mode 100644index 00000000000..b4fce9b1be6--- /dev/null+++ b/src/store/task/slices/lifecycle/index.ts@@ -0,0 +1,2 @@+export type { TaskLifecycleSliceAction } from './action';+export { createTaskLifecycleSlice } from './action';diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.tsnew file mode 100644index 00000000000..0b05d7691da--- /dev/null+++ b/src/store/task/slices/list/action.test.ts@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useTaskStore } from '../../store';++// Mock task service+vi.mock('@/services/task', () => ({+ taskService: {+ list: vi.fn(),+ },+}));++// Mock SWR+vi.mock('@/libs/swr', () => ({+ mutate: vi.fn(),+ useClientDataSWR: vi.fn(),+}));++beforeEach(() => {+ vi.clearAllMocks();+ useTaskStore.setState({+ isTaskListInit: false,+ listAgentId: undefined,+ tasks: [],+ tasksTotal: 0,+ viewMode: 'list',+ });+});++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();+ });+ });++ describe('setViewMode', () => {+ it('should toggle to kanban', () => {+ useTaskStore.getState().setViewMode('kanban');+ expect(useTaskStore.getState().viewMode).toBe('kanban');+ });++ it('should toggle back to list', () => {+ useTaskStore.getState().setViewMode('kanban');+ useTaskStore.getState().setViewMode('list');+ expect(useTaskStore.getState().viewMode).toBe('list');+ });+ });++ describe('refreshTaskList', () => {+ it('should call mutate with correct key', async () => {+ const { mutate } = await import('@/libs/swr');+ useTaskStore.setState({ listAgentId: 'agt_1' });++ await useTaskStore.getState().refreshTaskList();++ expect(mutate).toHaveBeenCalledWith(['fetchTaskList', 'agt_1']);+ });+ });+});diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.tsnew file mode 100644index 00000000000..c2cd90319a0--- /dev/null+++ b/src/store/task/slices/list/action.ts@@ -0,0 +1,109 @@+import { mutate, useClientDataSWR } from '@/libs/swr';+import { taskService } from '@/services/task';+import type { StoreSetter } from '@/store/types';++import type { TaskStore } from '../../store';+import type { TaskGroupItem, TaskListItem, TaskViewMode } from './initialState';++const FETCH_TASK_LIST_KEY = 'fetchTaskList';+const FETCH_TASK_GROUP_LIST_KEY = 'fetchTaskGroupList';++// Default kanban groups: 4 columns+const DEFAULT_KANBAN_GROUPS = [+ { key: 'backlog', statuses: ['backlog'] },+ { key: 'running', statuses: ['running'] },+ { key: 'needsInput', statuses: ['paused', 'failed'] },+ { key: 'done', statuses: ['completed'] },+];++type Setter = StoreSetter<TaskStore>;++export const createTaskListSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>+ new TaskListSliceActionImpl(set, get, _api);++export class TaskListSliceActionImpl {+ readonly #get: () => TaskStore;+ readonly #set: Setter;++ constructor(set: Setter, get: () => TaskStore, _api?: unknown) {+ void _api;+ this.#set = set;+ this.#get = get;+ }++ refreshTaskGroupList = async (): Promise<void> => {+ const { listAgentId } = this.#get();+ await mutate([FETCH_TASK_GROUP_LIST_KEY, listAgentId]);+ };++ refreshTaskList = async (): Promise<void> => {+ const { listAgentId } = this.#get();+ await mutate([FETCH_TASK_LIST_KEY, listAgentId]);+ };++ setListAgentId = (agentId?: string): void => {+ this.#set({ listAgentId: agentId }, false, 'setListAgentId');+ };++ setViewMode = (mode: TaskViewMode): void => {+ this.#set({ viewMode: mode }, false, 'setViewMode');+ };++ useFetchTaskGroupList = (agentId?: string, enabled: boolean = true) => {+ if (agentId && this.#get().listAgentId !== agentId) {+ this.#set({ listAgentId: agentId }, false, 'useFetchTaskGroupList/syncAgentId');+ }++ return useClientDataSWR(+ enabled && agentId ? [FETCH_TASK_GROUP_LIST_KEY, agentId] : null,+ async ([, id]: [string, string]) => {+ return taskService.groupList({+ assigneeAgentId: id,+ groups: DEFAULT_KANBAN_GROUPS,+ });+ },+ {+ fallbackData: { data: [], success: true },+ onSuccess: (data: { data: TaskGroupItem[] }) => {+ this.#set(+ { isTaskGroupListInit: true, taskGroups: data.data },+ false,+ 'useFetchTaskGroupList/onSuccess',+ );+ },+ revalidateOnFocus: false,+ },+ );+ };++ useFetchTaskList = (agentId?: string, enabled: boolean = true) => {+ // Sync listAgentId so refreshTaskList() uses the correct SWR key+ if (agentId && this.#get().listAgentId !== agentId) {+ this.#set({ listAgentId: agentId }, false, 'useFetchTaskList/syncAgentId');+ }++ return useClientDataSWR(+ enabled && agentId ? [FETCH_TASK_LIST_KEY, agentId] : null,+ async ([, id]: [string, string]) => {+ return taskService.list({ assigneeAgentId: id });+ },+ {+ fallbackData: { data: [], success: true, total: 0 },+ onSuccess: (data: { data: TaskListItem[]; total: number }) => {+ this.#set(+ {+ isTaskListInit: true,+ tasks: data.data,+ tasksTotal: data.total,+ },+ false,+ 'useFetchTaskList/onSuccess',+ );+ },+ revalidateOnFocus: false,+ },+ );+ };+}++export type TaskListSliceAction = Pick<TaskListSliceActionImpl, keyof TaskListSliceActionImpl>;diff --git a/src/store/task/slices/list/index.ts b/src/store/task/slices/list/index.tsnew file mode 100644index 00000000000..0da2cfe8b3b--- /dev/null+++ b/src/store/task/slices/list/index.ts@@ -0,0 +1,4 @@+export type { TaskListSliceAction } from './action';+export { createTaskListSlice } from './action';+export type { TaskListSliceState } from './initialState';+export { initialTaskListSliceState } from './initialState';diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.tsnew file mode 100644index 00000000000..7b93b3c0134--- /dev/null+++ b/src/store/task/slices/list/initialState.ts@@ -0,0 +1,26 @@+import type { taskService } from '@/services/task';++// Derive types from TRPC inference via service+export type TaskListItem = Awaited<ReturnType<typeof taskService.list>>['data'][number];+export type TaskGroupItem = Awaited<ReturnType<typeof taskService.groupList>>['data'][number];++export type TaskViewMode = 'kanban' | 'list';++export interface TaskListSliceState {+ isTaskGroupListInit: boolean;+ isTaskListInit: boolean;+ listAgentId?: string;+ taskGroups: TaskGroupItem[];+ tasks: TaskListItem[];+ tasksTotal: number;+ viewMode: TaskViewMode;+}++export const initialTaskListSliceState: TaskListSliceState = {+ isTaskGroupListInit: false,+ isTaskListInit: false,+ taskGroups: [],+ tasks: [],+ tasksTotal: 0,+ viewMode: 'list',+};diff --git a/src/store/task/store.ts b/src/store/task/store.tsnew file mode 100644index 00000000000..0c0d0f90b0c--- /dev/null+++ b/src/store/task/store.ts@@ -0,0 +1,54 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';+import type { StateCreator } from 'zustand/vanilla';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { flattenActions } from '../utils/flattenActions';+import type { TaskStoreState } from './initialState';+import { initialState } from './initialState';+import type { TaskConfigSliceAction } from './slices/config';+import { createTaskConfigSlice } from './slices/config';+import type { TaskDetailSliceAction } from './slices/detail';+import { createTaskDetailSlice } from './slices/detail';+import type { TaskLifecycleSliceAction } from './slices/lifecycle';+import { createTaskLifecycleSlice } from './slices/lifecycle';+import type { TaskListSliceAction } from './slices/list';+import { createTaskListSlice } from './slices/list';++// =============== aggregate createStoreFn ============ //++export interface TaskStore+ extends+ TaskConfigSliceAction,+ TaskDetailSliceAction,+ TaskLifecycleSliceAction,+ TaskListSliceAction,+ TaskStoreState {}++type TaskStoreAction = TaskConfigSliceAction &+ TaskDetailSliceAction &+ TaskLifecycleSliceAction &+ TaskListSliceAction;++const createStore: StateCreator<TaskStore, [['zustand/devtools', never]]> = (+ ...parameters: Parameters<StateCreator<TaskStore, [['zustand/devtools', never]]>>+) => ({+ ...initialState,+ ...flattenActions<TaskStoreAction>([+ createTaskListSlice(...parameters),+ createTaskDetailSlice(...parameters),+ createTaskLifecycleSlice(...parameters),+ createTaskConfigSlice(...parameters),+ ]),+});++// =============== implement useStore ============ //++const devtools = createDevtools('task');++export const useTaskStore = createWithEqualityFn<TaskStore>()(devtools(createStore), shallow);++expose('task', useTaskStore);++export const getTaskStoreState = () => useTaskStore.getState();