-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask-store.ts
More file actions
1204 lines (1053 loc) · 40.6 KB
/
Copy pathtask-store.ts
File metadata and controls
1204 lines (1053 loc) · 40.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { create } from 'zustand';
import { arrayMove } from '@dnd-kit/sortable';
import type { Task, TaskStatus, SubtaskStatus, ImplementationPlan, Subtask, TaskMetadata, ExecutionProgress, ExecutionPhase, ReviewReason, TaskDraft, ImageAttachment, TaskOrderState, TaskTokenStats } from '../../shared/types';
import { debugLog } from '../../shared/utils/debug-logger';
import { isTerminalPhase } from '../../shared/constants/phase-protocol';
/** Maximum log entries stored per task to prevent renderer OOM */
export const MAX_LOG_ENTRIES = 5000;
interface TaskState {
tasks: Task[];
selectedTaskId: string | null;
isLoading: boolean;
error: string | null;
taskOrder: TaskOrderState | null; // Per-column task ordering for kanban board
// Actions
setTasks: (tasks: Task[]) => void;
addTask: (task: Task) => void;
updateTask: (taskId: string, updates: Partial<Task>) => void;
updateTaskStatus: (taskId: string, status: TaskStatus) => void;
updateTaskFromPlan: (taskId: string, plan: ImplementationPlan) => void;
updateExecutionProgress: (taskId: string, progress: Partial<ExecutionProgress>) => void;
updateTokenStats: (taskId: string, tokenStats: TaskTokenStats) => void;
appendLog: (taskId: string, log: string) => void;
batchAppendLogs: (taskId: string, logs: string[]) => void;
selectTask: (taskId: string | null) => void;
setLoading: (loading: boolean) => void;
setError: (error: string | null) => void;
clearTasks: () => void;
// Task order actions for kanban drag-and-drop reordering
setTaskOrder: (order: TaskOrderState) => void;
reorderTasksInColumn: (status: TaskStatus, activeId: string, overId: string) => void;
moveTaskToColumnTop: (taskId: string, targetStatus: TaskStatus, sourceStatus?: TaskStatus) => void;
loadTaskOrder: (projectId: string) => void;
saveTaskOrder: (projectId: string) => boolean;
clearTaskOrder: (projectId: string) => void;
// Task status change listeners (for queue auto-promotion)
registerTaskStatusChangeListener: (listener: (taskId: string, oldStatus: TaskStatus | undefined, newStatus: TaskStatus) => void) => () => void;
// Selectors
getSelectedTask: () => Task | undefined;
getTasksByStatus: (status: TaskStatus) => Task[];
}
/**
* Helper to find task index by id or specId.
* Returns -1 if not found.
*/
function findTaskIndex(tasks: Task[], taskId: string): number {
return tasks.findIndex((t) => t.id === taskId || t.specId === taskId);
}
/**
* Task status change listeners for queue auto-promotion
* Stored outside the store to avoid triggering re-renders
*/
const taskStatusChangeListeners = new Set<(taskId: string, oldStatus: TaskStatus | undefined, newStatus: TaskStatus) => void>();
/**
* Notify all registered listeners when a task status changes
*/
function notifyTaskStatusChange(taskId: string, oldStatus: TaskStatus | undefined, newStatus: TaskStatus): void {
for (const listener of taskStatusChangeListeners) {
try {
listener(taskId, oldStatus, newStatus);
} catch (error) {
console.error('[TaskStore] Error in task status change listener:', error);
}
}
}
/**
* Helper to update a single task efficiently.
* Uses slice instead of map to avoid iterating all tasks.
*/
function updateTaskAtIndex(tasks: Task[], index: number, updater: (task: Task) => Task): Task[] {
if (index < 0 || index >= tasks.length) return tasks;
const updatedTask = updater(tasks[index]);
// If the task reference didn't change, return original array
if (updatedTask === tasks[index]) {
return tasks;
}
// Create new array with only the changed task replaced
const newTasks = [...tasks];
newTasks[index] = updatedTask;
return newTasks;
}
/**
* Validates implementation plan data structure before processing.
* Returns true if valid, false if invalid/incomplete.
*/
function validatePlanData(plan: ImplementationPlan): boolean {
// Validate plan has phases array
if (!plan.phases || !Array.isArray(plan.phases)) {
console.warn('[validatePlanData] Invalid plan: missing or invalid phases array');
return false;
}
// Validate each phase has subtasks array
for (let i = 0; i < plan.phases.length; i++) {
const phase = plan.phases[i];
if (!phase || !phase.subtasks || !Array.isArray(phase.subtasks)) {
console.warn(`[validatePlanData] Invalid phase ${i}: missing or invalid subtasks array`);
return false;
}
// Validate each subtask has at minimum a description
for (let j = 0; j < phase.subtasks.length; j++) {
const subtask = phase.subtasks[j];
if (!subtask || typeof subtask !== 'object') {
console.warn(`[validatePlanData] Invalid subtask at phase ${i}, index ${j}: not an object`);
return false;
}
// Description is critical - we can't show a subtask without it
if (!subtask.description || typeof subtask.description !== 'string' || subtask.description.trim() === '') {
console.warn(`[validatePlanData] Invalid subtask at phase ${i}, index ${j}: missing or empty description`);
return false;
}
}
}
return true;
}
// localStorage key prefix for task order persistence
const TASK_ORDER_KEY_PREFIX = 'task-order-state';
/**
* Get the localStorage key for a project's task order
*/
function getTaskOrderKey(projectId: string): string {
return `${TASK_ORDER_KEY_PREFIX}-${projectId}`;
}
/**
* Create an empty task order state with all status columns
*/
function createEmptyTaskOrder(): TaskOrderState {
return {
backlog: [],
queue: [],
in_progress: [],
ai_review: [],
human_review: [],
done: [],
pr_created: [],
error: []
};
}
/**
* Fetch token stats for a task from the backend and update the store
* @param taskId - The task ID to fetch stats for
*/
async function fetchAndUpdateTokenStats(taskId: string): Promise<void> {
try {
// Get the store state to access tasks
const store = useTaskStore.getState();
const task = store.tasks.find((t) => t.id === taskId || t.specId === taskId);
if (!task) {
debugLog('[fetchAndUpdateTokenStats] Task not found:', taskId);
return;
}
// Import project store dynamically to avoid circular dependencies
const { useProjectStore } = await import('./project-store');
const projectStore = useProjectStore.getState();
const project = projectStore.projects.find((p) => p.id === task.projectId);
if (!project) {
debugLog('[fetchAndUpdateTokenStats] Project not found:', task.projectId);
return;
}
// Fetch token stats via electronAPI
const result = await window.electronAPI.getTokenStats(
project.path,
task.specId
);
if (result.success && result.data) {
// Update the store with fetched token stats
store.updateTokenStats(taskId, result.data);
debugLog('[fetchAndUpdateTokenStats] Token stats updated:', {
taskId,
total_tokens: result.data.total_tokens
});
} else if (!result.success && result.error) {
debugLog('[fetchAndUpdateTokenStats] Failed to fetch token stats:', result.error);
}
// If result.data is null, token_stats.json doesn't exist yet (not an error)
} catch (error) {
console.error('[fetchAndUpdateTokenStats] Error fetching token stats:', error);
}
}
export const useTaskStore = create<TaskState>((set, get) => ({
tasks: [],
selectedTaskId: null,
isLoading: false,
error: null,
taskOrder: null,
setTasks: (tasks) => set({ tasks }),
addTask: (task) =>
set((state) => {
// Determine which column the task belongs to based on its status
const status = task.status || 'backlog';
// Update task order if it exists - new tasks go to top of their column
let taskOrder = state.taskOrder;
if (taskOrder) {
const newTaskOrder = { ...taskOrder };
// Add task ID to the top of the appropriate column
if (newTaskOrder[status]) {
// Ensure the task isn't already in the array (safety check)
newTaskOrder[status] = newTaskOrder[status].filter(id => id !== task.id);
// Add to top (index 0)
newTaskOrder[status] = [task.id, ...newTaskOrder[status]];
} else {
// Initialize column order array if it doesn't exist
newTaskOrder[status] = [task.id];
}
taskOrder = newTaskOrder;
}
return {
tasks: [...state.tasks, task],
taskOrder
};
}),
updateTask: (taskId, updates) =>
set((state) => {
const index = findTaskIndex(state.tasks, taskId);
if (index === -1) return state;
return {
tasks: updateTaskAtIndex(state.tasks, index, (t) => ({ ...t, ...updates }))
};
}),
updateTaskStatus: (taskId, status) => {
// Capture old status before update
const state = get();
const index = findTaskIndex(state.tasks, taskId);
if (index === -1) {
debugLog('[updateTaskStatus] Task not found:', taskId);
return;
}
const oldTask = state.tasks[index];
const oldStatus = oldTask.status;
// Skip if status is the same
if (oldStatus === status) return;
// Perform the state update
set((state) => {
return {
tasks: updateTaskAtIndex(state.tasks, index, (t) => {
// Determine execution progress based on status transition
let executionProgress = t.executionProgress;
// Track status transition for debugging flip-flop issues
const previousStatus = t.status;
const statusChanged = previousStatus !== status;
if (status === 'backlog') {
// When status goes to backlog, reset execution progress to idle
// This ensures the planning/coding animation stops when task is stopped
executionProgress = { phase: 'idle' as ExecutionPhase, phaseProgress: 0, overallProgress: 0 };
} else if (status === 'in_progress' && !t.executionProgress?.phase) {
// When starting a task and no phase is set yet, default to planning
// This prevents the "no active phase" UI state during startup race condition
executionProgress = { phase: 'planning' as ExecutionPhase, phaseProgress: 0, overallProgress: 0 };
}
// Log status transitions to help diagnose flip-flop issues
debugLog('[updateTaskStatus] Status transition:', {
taskId,
previousStatus,
newStatus: status,
statusChanged,
currentPhase: t.executionProgress?.phase,
newPhase: executionProgress?.phase
});
return { ...t, status, executionProgress, updatedAt: new Date() };
})
};
});
// Notify listeners after state update (schedule after current tick)
queueMicrotask(() => {
notifyTaskStatusChange(taskId, oldStatus, status);
});
// Fetch token stats when task transitions to in_progress or done status
if (status === 'in_progress' || status === 'done') {
fetchAndUpdateTokenStats(taskId);
}
},
updateTaskFromPlan: (taskId, plan) =>
set((state) => {
// FIX (PR Review): Gate debug logging to prevent production console clutter
debugLog('[updateTaskFromPlan] called with plan:', {
taskId,
feature: plan.feature,
phases: plan.phases?.length || 0,
totalSubtasks: plan.phases?.reduce((acc, p) => acc + (p.subtasks?.length || 0), 0) || 0
// Note: planData removed to avoid verbose output in logs
});
const index = findTaskIndex(state.tasks, taskId);
if (index === -1) {
console.log('[updateTaskFromPlan] Task not found:', taskId);
return state;
}
// Validate plan data before processing
if (!validatePlanData(plan)) {
console.error('[updateTaskFromPlan] Invalid plan data, skipping update:', {
taskId,
plan
});
return state;
}
return {
tasks: updateTaskAtIndex(state.tasks, index, (t) => {
const subtasks: Subtask[] = plan.phases.flatMap((phase) =>
phase.subtasks.map((subtask) => {
// Ensure all required fields have valid values to prevent UI issues
// Use crypto.randomUUID() for stronger randomness when available
const id = subtask.id || (typeof crypto !== 'undefined' && crypto.randomUUID
? crypto.randomUUID()
: `subtask-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`);
// Defensive fallback: validatePlanData() ensures description exists, but kept for safety
const description = subtask.description || 'No description available';
const title = description; // Title and description are the same for subtasks
const status = (subtask.status as SubtaskStatus) || 'pending';
return {
id,
title,
description,
status,
files: [],
verification: subtask.verification as Subtask['verification']
};
})
);
debugLog('[updateTaskFromPlan] Created subtasks:', {
taskId,
subtaskCount: subtasks.length,
subtasks: subtasks.map(s => ({
id: s.id,
title: s.title,
status: s.status
}))
});
const allCompleted = subtasks.every((s) => s.status === 'completed');
const anyFailed = subtasks.some((s) => s.status === 'failed');
const anyInProgress = subtasks.some((s) => s.status === 'in_progress');
const anyCompleted = subtasks.some((s) => s.status === 'completed');
let status: TaskStatus = t.status;
let reviewReason: ReviewReason | undefined = t.reviewReason;
// RACE CONDITION FIX: Don't let stale plan data override status during active execution
// Strengthen guard: ANY active phase means NO status recalculation from plan data
const activePhases: ExecutionPhase[] = ['planning', 'coding', 'qa_review', 'qa_fixing'];
const isInActivePhase = Boolean(t.executionProgress?.phase && activePhases.includes(t.executionProgress.phase));
// FIX (Flip-Flop Bug): Terminal phases should NOT trigger status recalculation
// When phase is 'complete' or 'failed', the task has finished and status should be stable
const isInTerminalPhase = Boolean(t.executionProgress?.phase && isTerminalPhase(t.executionProgress.phase));
// FIX (Subtask 2-1): Terminal task statuses should NEVER be recalculated from plan data
// pr_created, done, and error are finalized workflow states set by explicit user/system actions
// Once a task reaches these statuses, they should only change via explicit user actions (like drag-drop)
// This prevents stale plan file reads from incorrectly downgrading completed tasks
// NOTE: Keep this in sync with TERMINAL_STATUSES in project-store.ts
const TERMINAL_TASK_STATUSES: TaskStatus[] = ['pr_created', 'done', 'error'];
const isInTerminalStatus = TERMINAL_TASK_STATUSES.includes(t.status);
// FIX (Flip-Flop Bug): Respect explicit human_review status from plan file
// When the plan explicitly says 'human_review', don't override it with calculated status
// Note: ImplementationPlan type already defines status?: TaskStatus
const planStatus = plan.status;
const isExplicitHumanReview = planStatus === 'human_review';
// FIX (ACS-203): Add defensive check for terminal status transitions
// Before allowing transition to 'done', 'human_review', or 'ai_review', verify:
// 1. Subtasks array is properly populated (not empty)
// 2. All subtasks are actually completed (for 'done' and 'ai_review' statuses)
const hasSubtasks = subtasks.length > 0;
const terminalStatuses: TaskStatus[] = ['human_review', 'done'];
// If task is currently in a terminal status, validate subtasks before allowing downgrade
// This prevents flip-flop when plan file is written with incomplete data
const shouldBlockTerminalTransition = (newStatus: TaskStatus): boolean => {
// Block if: moving to terminal status but subtasks indicate incomplete work
if (terminalStatuses.includes(newStatus) || newStatus === 'ai_review') {
// For ai_review, all subtasks must be completed
if (newStatus === 'ai_review' && (!allCompleted || !hasSubtasks)) {
return true;
}
// For done, all subtasks must be completed
if (newStatus === 'done' && (!allCompleted || !hasSubtasks)) {
return true;
}
// For human_review with 'completed' reason, all subtasks must be done
// But allow 'errors' or 'qa_rejected' reasons even with incomplete subtasks
if (newStatus === 'human_review' && anyFailed) {
return false; // Allow human_review for failed subtasks
}
}
return false;
};
// Only recalculate status if:
// 1. NOT in an active execution phase (planning, coding, qa_review, qa_fixing)
// 2. NOT in a terminal phase (complete, failed) - status should be stable
// 3. NOT in a terminal task status (pr_created, done) - finalized workflow states
// 4. Plan doesn't explicitly say human_review
// 5. Would not create an invalid terminal transition (ACS-203)
if (!isInActivePhase && !isInTerminalPhase && !isInTerminalStatus && !isExplicitHumanReview) {
if (allCompleted && hasSubtasks) {
// FIX (Flip-Flop Bug): Don't downgrade from terminal statuses to ai_review
// Once a task reaches human_review or done, it should stay there
// unless explicitly changed (these are finalized workflow states)
if (!terminalStatuses.includes(t.status)) {
status = 'ai_review';
}
} else if (anyFailed) {
status = 'human_review';
reviewReason = 'errors';
} else if (anyInProgress || anyCompleted) {
status = 'in_progress';
}
}
// FIX (ACS-203): Final validation - prevent invalid terminal status transitions
// This catches cases where the logic above would set a terminal status
// but the subtask state doesn't support it (e.g., empty subtasks array)
if (shouldBlockTerminalTransition(status)) {
// Capture attempted status before reassignment for accurate logging
const attemptedStatus = status;
// Keep current status instead of transitioning to invalid terminal state
status = t.status;
debugLog('[updateTaskFromPlan] Blocked invalid terminal transition:', {
taskId,
attemptedStatus,
currentStatus: t.status,
hasSubtasks,
allCompleted,
anyFailed,
subtaskCount: subtasks.length
});
}
debugLog('[updateTaskFromPlan] Status computation:', {
taskId,
currentStatus: t.status,
newStatus: status,
isInActivePhase,
isInTerminalPhase,
isInTerminalStatus,
isExplicitHumanReview,
planStatus,
currentPhase: t.executionProgress?.phase,
allCompleted,
anyFailed,
anyInProgress,
anyCompleted
});
return {
...t,
title: plan.feature || t.title,
subtasks,
status,
reviewReason,
updatedAt: new Date()
};
})
};
}),
updateExecutionProgress: (taskId, progress) => {
// Capture old phase before update for real-time token stats fetching
const state = get();
const index = findTaskIndex(state.tasks, taskId);
if (index === -1) return;
const oldTask = state.tasks[index];
const oldPhase = oldTask.executionProgress?.phase;
const newPhase = progress.phase;
// Perform the state update
set((state) => {
const index = findTaskIndex(state.tasks, taskId);
if (index === -1) return state;
return {
tasks: updateTaskAtIndex(state.tasks, index, (t) => {
const existingProgress = t.executionProgress || {
phase: 'idle' as ExecutionPhase,
phaseProgress: 0,
overallProgress: 0,
sequenceNumber: 0
};
const incomingSeq = progress.sequenceNumber ?? 0;
const currentSeq = existingProgress.sequenceNumber ?? 0;
if (incomingSeq > 0 && currentSeq > 0 && incomingSeq < currentSeq) {
// FIX (ACS-55): Log when updates are dropped due to sequence numbers
// This helps debug phase transition issues
console.warn('[updateExecutionProgress] Dropping out-of-order update:', {
taskId,
incomingSeq,
currentSeq,
incomingPhase: progress.phase,
currentPhase: existingProgress.phase
});
return t; // Skip out-of-order update
}
// Only update updatedAt on phase transitions (not on every progress tick)
// This prevents unnecessary re-renders from the memo comparator
const phaseChanged = progress.phase && progress.phase !== existingProgress.phase;
return {
...t,
executionProgress: {
...existingProgress,
...progress
},
// Only set updatedAt on phase changes to reduce re-renders
...(phaseChanged ? { updatedAt: new Date() } : {})
};
})
};
});
// Fetch updated token stats when phase changes (real-time updates during task execution)
// This enables live token display as each phase completes (planning → coding → validation)
if (newPhase && newPhase !== oldPhase && newPhase !== 'idle') {
debugLog('[updateExecutionProgress] Phase changed, fetching token stats:', {
taskId,
oldPhase,
newPhase
});
fetchAndUpdateTokenStats(taskId);
}
},
updateTokenStats: (taskId, tokenStats) =>
set((state) => {
const index = findTaskIndex(state.tasks, taskId);
if (index === -1) return state;
return {
tasks: updateTaskAtIndex(state.tasks, index, (t) => ({
...t,
tokenStats
}))
};
}),
appendLog: (taskId, log) =>
set((state) => {
const index = findTaskIndex(state.tasks, taskId);
if (index === -1) return state;
return {
tasks: updateTaskAtIndex(state.tasks, index, (t) => ({
...t,
logs: [...(t.logs || []).slice(-(MAX_LOG_ENTRIES - 1)), log]
}))
};
}),
// Batch append multiple logs at once (single state update instead of N updates)
batchAppendLogs: (taskId, logs) =>
set((state) => {
if (logs.length === 0) return state;
const index = findTaskIndex(state.tasks, taskId);
if (index === -1) return state;
return {
tasks: updateTaskAtIndex(state.tasks, index, (t) => ({
...t,
logs: [...(t.logs || []).slice(-(MAX_LOG_ENTRIES - logs.length)), ...logs].slice(-MAX_LOG_ENTRIES)
}))
};
}),
selectTask: (taskId) => {
set({ selectedTaskId: taskId });
// Fetch token stats for the selected task
if (taskId) {
fetchAndUpdateTokenStats(taskId);
}
},
setLoading: (isLoading) => set({ isLoading }),
setError: (error) => set({ error }),
clearTasks: () => set({ tasks: [], selectedTaskId: null, taskOrder: null }),
// Task order actions for kanban drag-and-drop reordering
setTaskOrder: (order) => set({ taskOrder: order }),
reorderTasksInColumn: (status, activeId, overId) => {
set((state) => {
if (!state.taskOrder) return state;
const columnOrder = state.taskOrder[status];
if (!columnOrder) return state;
const oldIndex = columnOrder.indexOf(activeId);
const newIndex = columnOrder.indexOf(overId);
// Both tasks must be in the column order array
if (oldIndex === -1 || newIndex === -1) return state;
return {
taskOrder: {
...state.taskOrder,
[status]: arrayMove(columnOrder, oldIndex, newIndex)
}
};
});
},
moveTaskToColumnTop: (taskId, targetStatus, sourceStatus) => {
set((state) => {
if (!state.taskOrder) return state;
// Create a copy of the task order to modify
const newTaskOrder = { ...state.taskOrder };
// Remove from source column if provided
if (sourceStatus && newTaskOrder[sourceStatus]) {
newTaskOrder[sourceStatus] = newTaskOrder[sourceStatus].filter(id => id !== taskId);
}
// Add to top of target column
if (newTaskOrder[targetStatus]) {
// Remove from target column first (in case it already exists there)
newTaskOrder[targetStatus] = newTaskOrder[targetStatus].filter(id => id !== taskId);
// Add to top (index 0)
newTaskOrder[targetStatus] = [taskId, ...newTaskOrder[targetStatus]];
} else {
// Initialize column order array if it doesn't exist
newTaskOrder[targetStatus] = [taskId];
}
return { taskOrder: newTaskOrder };
});
},
loadTaskOrder: (projectId) => {
try {
const key = getTaskOrderKey(projectId);
const stored = localStorage.getItem(key);
if (stored) {
const parsed = JSON.parse(stored);
// Validate structure before assigning - type assertion is compile-time only
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
console.warn('Invalid task order data in localStorage, resetting to empty');
set({ taskOrder: createEmptyTaskOrder() });
return;
}
// Helper to validate column values are string arrays
const isValidColumnArray = (val: unknown): val is string[] =>
Array.isArray(val) && val.every(item => typeof item === 'string');
// Merge with empty order to handle partial data and validate each column
const emptyOrder = createEmptyTaskOrder();
const validatedOrder: TaskOrderState = {
backlog: isValidColumnArray(parsed.backlog) ? parsed.backlog : emptyOrder.backlog,
queue: isValidColumnArray(parsed.queue) ? parsed.queue : emptyOrder.queue,
in_progress: isValidColumnArray(parsed.in_progress) ? parsed.in_progress : emptyOrder.in_progress,
ai_review: isValidColumnArray(parsed.ai_review) ? parsed.ai_review : emptyOrder.ai_review,
human_review: isValidColumnArray(parsed.human_review) ? parsed.human_review : emptyOrder.human_review,
done: isValidColumnArray(parsed.done) ? parsed.done : emptyOrder.done,
pr_created: isValidColumnArray(parsed.pr_created) ? parsed.pr_created : emptyOrder.pr_created,
error: isValidColumnArray(parsed.error) ? parsed.error : emptyOrder.error
};
set({ taskOrder: validatedOrder });
} else {
set({ taskOrder: createEmptyTaskOrder() });
}
} catch (error) {
console.error('Failed to load task order:', error);
set({ taskOrder: createEmptyTaskOrder() });
}
},
saveTaskOrder: (projectId) => {
try {
const state = get();
if (!state.taskOrder) {
// Nothing to save - return false to indicate no save occurred
return false;
}
const key = getTaskOrderKey(projectId);
localStorage.setItem(key, JSON.stringify(state.taskOrder));
return true;
} catch (error) {
console.error('Failed to save task order:', error);
return false;
}
},
clearTaskOrder: (projectId) => {
try {
const key = getTaskOrderKey(projectId);
localStorage.removeItem(key);
set({ taskOrder: null });
} catch (error) {
console.error('Failed to clear task order:', error);
}
},
getSelectedTask: () => {
const state = get();
return state.tasks.find((t) => t.id === state.selectedTaskId);
},
getTasksByStatus: (status) => {
const state = get();
return state.tasks.filter((t) => t.status === status);
},
registerTaskStatusChangeListener: (listener) => {
taskStatusChangeListeners.add(listener);
// Return cleanup function to unregister
return () => {
taskStatusChangeListeners.delete(listener);
};
}
}));
/**
* Load tasks for a project
* @param projectId - The project ID to load tasks for
* @param options - Optional parameters
* @param options.forceRefresh - If true, invalidates server-side cache before fetching (for refresh button)
*/
export async function loadTasks(projectId: string, options?: { forceRefresh?: boolean }): Promise<void> {
const store = useTaskStore.getState();
store.setLoading(true);
store.setError(null);
try {
const result = await window.electronAPI.getTasks(projectId, options);
if (result.success && result.data) {
store.setTasks(result.data);
} else {
store.setError(result.error || 'Failed to load tasks');
}
} catch (error) {
store.setError(error instanceof Error ? error.message : 'Unknown error');
} finally {
store.setLoading(false);
}
}
/**
* Create a new task
*/
export async function createTask(
projectId: string,
title: string,
description: string,
metadata?: TaskMetadata
): Promise<Task | null> {
const store = useTaskStore.getState();
try {
const result = await window.electronAPI.createTask(projectId, title, description, metadata);
if (result.success && result.data) {
store.addTask(result.data);
return result.data;
} else {
store.setError(result.error || 'Failed to create task');
return null;
}
} catch (error) {
store.setError(error instanceof Error ? error.message : 'Unknown error');
return null;
}
}
/**
* Start a task
*/
export function startTask(taskId: string, options?: { parallel?: boolean; workers?: number }): void {
window.electronAPI.startTask(taskId, options);
}
/**
* Stop a task
*/
export function stopTask(taskId: string): void {
window.electronAPI.stopTask(taskId);
}
/**
* Submit review for a task
*/
export async function submitReview(
taskId: string,
approved: boolean,
feedback?: string,
images?: ImageAttachment[]
): Promise<boolean> {
const store = useTaskStore.getState();
try {
const result = await window.electronAPI.submitReview(taskId, approved, feedback, images);
if (result.success) {
store.updateTaskStatus(taskId, approved ? 'done' : 'in_progress');
return true;
}
return false;
} catch {
return false;
}
}
/**
* Result type for persistTaskStatus with worktree info
*/
export interface PersistStatusResult {
success: boolean;
worktreeExists?: boolean;
worktreePath?: string;
error?: string;
}
/**
* Update task status and persist to file
* Returns additional info if a worktree exists and needs cleanup confirmation
*/
export async function persistTaskStatus(
taskId: string,
status: TaskStatus,
options?: { forceCleanup?: boolean; keepWorktree?: boolean }
): Promise<PersistStatusResult> {
const store = useTaskStore.getState();
try {
// Persist to file first (don't optimistically update for 'done' status)
const result = await window.electronAPI.updateTaskStatus(taskId, status, options);
if (!result.success) {
// Check if this is a worktree exists case
if (result.worktreeExists) {
console.log('[persistTaskStatus] Worktree exists, confirmation needed');
return {
success: false,
worktreeExists: true,
worktreePath: result.worktreePath,
error: result.error
};
}
console.error('Failed to persist task status:', result.error);
return { success: false, error: result.error };
}
// Only update local state after backend confirms success
store.updateTaskStatus(taskId, status);
return { success: true };
} catch (error) {
console.error('Error persisting task status:', error);
return { success: false, error: String(error) };
}
}
/**
* Force complete a task by cleaning up its worktree
* Used when user confirms they want to delete the worktree and mark as done
* Returns full result including error details for better UX
*/
export async function forceCompleteTask(taskId: string): Promise<PersistStatusResult> {
return persistTaskStatus(taskId, 'done', { forceCleanup: true });
}
/**
* Update task title/description/metadata and persist to file
*/
export async function persistUpdateTask(
taskId: string,
updates: { title?: string; description?: string; metadata?: Partial<TaskMetadata> }
): Promise<boolean> {
const store = useTaskStore.getState();
try {
// Call the IPC to persist changes to spec files
const result = await window.electronAPI.updateTask(taskId, updates);
if (result.success && result.data) {
// Update local state with the returned task data
store.updateTask(taskId, {
title: result.data.title,
description: result.data.description,
metadata: result.data.metadata,
updatedAt: new Date()
});
return true;
}
console.error('Failed to persist task update:', result.error);
return false;
} catch (error) {
console.error('Error persisting task update:', error);
return false;
}
}
/**
* Check if a task has an active running process
*/
export async function checkTaskRunning(taskId: string): Promise<boolean> {
try {
const result = await window.electronAPI.checkTaskRunning(taskId);
return result.success && result.data === true;
} catch (error) {
console.error('Error checking task running status:', error);
return false;
}
}
/**
* Recover a stuck task (status shows in_progress but no process running)
* @param taskId - The task ID to recover
* @param options - Recovery options (autoRestart defaults to true)
*/
export async function recoverStuckTask(
taskId: string,
options: { targetStatus?: TaskStatus; autoRestart?: boolean } = { autoRestart: true }
): Promise<{ success: boolean; message: string; autoRestarted?: boolean }> {
const store = useTaskStore.getState();
try {
const result = await window.electronAPI.recoverStuckTask(taskId, options);
if (result.success && result.data) {
// Update local state
store.updateTaskStatus(taskId, result.data.newStatus);
return {
success: true,
message: result.data.message,
autoRestarted: result.data.autoRestarted
};
}
return {
success: false,
message: result.error || 'Failed to recover task'
};
} catch (error) {
console.error('Error recovering stuck task:', error);
return {
success: false,
message: error instanceof Error ? error.message : 'Unknown error'
};
}
}
/**
* Delete a task and its spec directory
*/
export async function deleteTask(
taskId: string
): Promise<{ success: boolean; error?: string }> {