feat: fix ai actions

- add react-query
- implement cache invalidation strategy
This commit is contained in:
Ralph Khreish
2025-07-31 19:08:37 +03:00
parent c99d09885f
commit dadfa471cd
12 changed files with 261 additions and 145 deletions

View File

@@ -31,6 +31,9 @@ export const AIActionsSection: React.FC<AIActionsSectionProps> = ({
onAppendingChange onAppendingChange
}) => { }) => {
const [prompt, setPrompt] = useState(''); const [prompt, setPrompt] = useState('');
const [lastAction, setLastAction] = useState<'regenerate' | 'append' | null>(
null
);
const updateTask = useUpdateTask(); const updateTask = useUpdateTask();
const updateSubtask = useUpdateSubtask(); const updateSubtask = useUpdateSubtask();
@@ -39,6 +42,9 @@ export const AIActionsSection: React.FC<AIActionsSectionProps> = ({
return; return;
} }
setLastAction('regenerate');
onRegeneratingChange?.(true);
try { try {
if (isSubtask && parentTask) { if (isSubtask && parentTask) {
await updateSubtask.mutateAsync({ await updateSubtask.mutateAsync({
@@ -58,6 +64,9 @@ export const AIActionsSection: React.FC<AIActionsSectionProps> = ({
refreshComplexityAfterAI(); refreshComplexityAfterAI();
} catch (error) { } catch (error) {
console.error('❌ TaskDetailsView: Failed to regenerate task:', error); console.error('❌ TaskDetailsView: Failed to regenerate task:', error);
} finally {
setLastAction(null);
onRegeneratingChange?.(false);
} }
}; };
@@ -66,6 +75,9 @@ export const AIActionsSection: React.FC<AIActionsSectionProps> = ({
return; return;
} }
setLastAction('append');
onAppendingChange?.(true);
try { try {
if (isSubtask && parentTask) { if (isSubtask && parentTask) {
await updateSubtask.mutateAsync({ await updateSubtask.mutateAsync({
@@ -85,12 +97,16 @@ export const AIActionsSection: React.FC<AIActionsSectionProps> = ({
refreshComplexityAfterAI(); refreshComplexityAfterAI();
} catch (error) { } catch (error) {
console.error('❌ TaskDetailsView: Failed to append to task:', error); console.error('❌ TaskDetailsView: Failed to append to task:', error);
} finally {
setLastAction(null);
onAppendingChange?.(false);
} }
}; };
// Track loading states // Track loading states based on the last action
const isRegenerating = updateTask.isPending || updateSubtask.isPending; const isLoading = updateTask.isPending || updateSubtask.isPending;
const isAppending = updateTask.isPending || updateSubtask.isPending; const isRegenerating = isLoading && lastAction === 'regenerate';
const isAppending = isLoading && lastAction === 'append';
return ( return (
<CollapsibleSection <CollapsibleSection
@@ -180,7 +196,7 @@ export const AIActionsSection: React.FC<AIActionsSectionProps> = ({
</p> </p>
<p> <p>
<strong>Append:</strong> Adds new content to the existing task <strong>Append:</strong> Adds new content to the existing task
description based on your prompt implementation details based on your prompt
</p> </p>
</> </>
)} )}

View File

@@ -256,7 +256,10 @@ export const TaskMetadataSidebar: React.FC<TaskMetadataSidebarProps> = ({
</h4> </h4>
<div className="space-y-2"> <div className="space-y-2">
{currentTask.dependencies.map((depId) => { {currentTask.dependencies.map((depId) => {
const depTask = tasks.find((t) => t.id === depId); // Convert both to string for comparison since depId might be string or number
const depTask = tasks.find(
(t) => String(t.id) === String(depId)
);
const fullTitle = `Task ${depId}: ${depTask?.title || 'Unknown Task'}`; const fullTitle = `Task ${depId}: ${depTask?.title || 'Unknown Task'}`;
const truncatedTitle = const truncatedTitle =
fullTitle.length > 40 fullTitle.length > 40

View File

@@ -20,7 +20,9 @@ export const useTaskDetails = ({
}: UseTaskDetailsProps) => { }: UseTaskDetailsProps) => {
// Parse task ID to determine if it's a subtask (e.g., "13.2") // Parse task ID to determine if it's a subtask (e.g., "13.2")
const { isSubtask, parentId, subtaskIndex, taskIdForFetch } = useMemo(() => { const { isSubtask, parentId, subtaskIndex, taskIdForFetch } = useMemo(() => {
const parts = taskId.split('.'); // Ensure taskId is a string
const taskIdStr = String(taskId);
const parts = taskIdStr.split('.');
if (parts.length === 2) { if (parts.length === 2) {
return { return {
isSubtask: true, isSubtask: true,
@@ -31,9 +33,9 @@ export const useTaskDetails = ({
} }
return { return {
isSubtask: false, isSubtask: false,
parentId: taskId, parentId: taskIdStr,
subtaskIndex: -1, subtaskIndex: -1,
taskIdForFetch: taskId taskIdForFetch: taskIdStr
}; };
}, [taskId]); }, [taskId]);
@@ -50,7 +52,7 @@ export const useTaskDetails = ({
return { currentTask: subtask, parentTask: parent }; return { currentTask: subtask, parentTask: parent };
} }
} else { } else {
const task = tasks.find((t) => t.id === taskId); const task = tasks.find((t) => t.id === String(taskId));
if (task) { if (task) {
return { currentTask: task, parentTask: null }; return { currentTask: task, parentTask: null };
} }

View File

@@ -1,6 +1,8 @@
import type React from 'react'; import type React from 'react';
import { useContext } from 'react'; import { useContext, useState, useCallback } from 'react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { useQueryClient } from '@tanstack/react-query';
import { RefreshCw } from 'lucide-react';
import { import {
Breadcrumb, Breadcrumb,
BreadcrumbItem, BreadcrumbItem,
@@ -14,6 +16,7 @@ import { SubtasksSection } from './TaskDetails/SubtasksSection';
import { TaskMetadataSidebar } from './TaskDetails/TaskMetadataSidebar'; import { TaskMetadataSidebar } from './TaskDetails/TaskMetadataSidebar';
import { DetailsSection } from './TaskDetails/DetailsSection'; import { DetailsSection } from './TaskDetails/DetailsSection';
import { useTaskDetails } from './TaskDetails/useTaskDetails'; import { useTaskDetails } from './TaskDetails/useTaskDetails';
import { useTasks, taskKeys } from '../webview/hooks/useTaskQueries';
import type { TaskMasterTask } from '../webview/types'; import type { TaskMasterTask } from '../webview/types';
interface TaskDetailsViewProps { interface TaskDetailsViewProps {
@@ -33,7 +36,12 @@ export const TaskDetailsView: React.FC<TaskDetailsViewProps> = ({
} }
const { state, sendMessage } = context; const { state, sendMessage } = context;
const { tasks } = state; const { currentTag } = state;
const queryClient = useQueryClient();
const [isRefreshing, setIsRefreshing] = useState(false);
// Use React Query to fetch all tasks
const { data: allTasks = [] } = useTasks({ tag: currentTag });
const { const {
currentTask, currentTask,
@@ -43,7 +51,7 @@ export const TaskDetailsView: React.FC<TaskDetailsViewProps> = ({
taskFileDataError, taskFileDataError,
complexity, complexity,
refreshComplexityAfterAI refreshComplexityAfterAI
} = useTaskDetails({ taskId, sendMessage, tasks }); } = useTaskDetails({ taskId, sendMessage, tasks: allTasks });
const handleStatusChange = async (newStatus: TaskMasterTask['status']) => { const handleStatusChange = async (newStatus: TaskMasterTask['status']) => {
if (!currentTask) return; if (!currentTask) return;
@@ -68,6 +76,17 @@ export const TaskDetailsView: React.FC<TaskDetailsViewProps> = ({
onNavigateToTask(depId); onNavigateToTask(depId);
}; };
const handleRefresh = useCallback(async () => {
setIsRefreshing(true);
try {
// Invalidate all task queries
await queryClient.invalidateQueries({ queryKey: taskKeys.all });
} finally {
// Reset after a short delay to show the animation
setTimeout(() => setIsRefreshing(false), 500);
}
}, [queryClient]);
if (!currentTask) { if (!currentTask) {
return ( return (
<div className="flex items-center justify-center h-full"> <div className="flex items-center justify-center h-full">
@@ -89,6 +108,7 @@ export const TaskDetailsView: React.FC<TaskDetailsViewProps> = ({
{/* Left column - Main content (2/3 width) */} {/* Left column - Main content (2/3 width) */}
<div className="md:col-span-2 space-y-6"> <div className="md:col-span-2 space-y-6">
{/* Breadcrumb navigation */} {/* Breadcrumb navigation */}
<div className="flex items-center justify-between">
<Breadcrumb> <Breadcrumb>
<BreadcrumbList> <BreadcrumbList>
<BreadcrumbItem> <BreadcrumbItem>
@@ -120,6 +140,17 @@ export const TaskDetailsView: React.FC<TaskDetailsViewProps> = ({
</BreadcrumbItem> </BreadcrumbItem>
</BreadcrumbList> </BreadcrumbList>
</Breadcrumb> </Breadcrumb>
<button
onClick={handleRefresh}
disabled={isRefreshing}
className="p-1.5 rounded hover:bg-vscode-button-hoverBackground transition-colors"
title="Refresh task details"
>
<RefreshCw
className={`w-4 h-4 text-vscode-foreground/70 ${isRefreshing ? 'animate-spin' : ''}`}
/>
</button>
</div>
{/* Task title */} {/* Task title */}
<h1 className="text-2xl font-bold tracking-tight text-vscode-foreground"> <h1 className="text-2xl font-bold tracking-tight text-vscode-foreground">
@@ -172,7 +203,7 @@ export const TaskDetailsView: React.FC<TaskDetailsViewProps> = ({
{/* Right column - Metadata (1/3 width) */} {/* Right column - Metadata (1/3 width) */}
<TaskMetadataSidebar <TaskMetadataSidebar
currentTask={currentTask} currentTask={currentTask}
tasks={tasks} tasks={allTasks}
complexity={complexity} complexity={complexity}
isSubtask={isSubtask} isSubtask={isSubtask}
sendMessage={sendMessage} sendMessage={sendMessage}

View File

@@ -180,21 +180,14 @@ export class WebviewManager {
const { taskId, updates, options = {} } = data; const { taskId, updates, options = {} } = data;
// Use the update_task MCP tool // Use the update_task MCP tool
const result = await this.mcpClient.callTool('update_task', { await this.mcpClient.callTool('update_task', {
id: taskId, id: String(taskId),
prompt: updates.description || '', prompt: updates.description || '',
append: options.append || false, append: options.append || false,
research: options.research || false, research: options.research || false,
projectRoot: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath projectRoot: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath
}); });
// Refresh tasks after update
await this.repository.refresh();
const updatedTasks = await this.repository.getAll();
this.broadcast('tasksUpdated', {
tasks: updatedTasks,
source: 'task-update'
});
response = { success: true }; response = { success: true };
} catch (error) { } catch (error) {
this.logger.error('Failed to update task via MCP:', error); this.logger.error('Failed to update task via MCP:', error);
@@ -212,20 +205,13 @@ export class WebviewManager {
const { taskId, prompt, options = {} } = data; const { taskId, prompt, options = {} } = data;
// Use the update_subtask MCP tool // Use the update_subtask MCP tool
const result = await this.mcpClient.callTool('update_subtask', { await this.mcpClient.callTool('update_subtask', {
id: taskId, id: String(taskId),
prompt: prompt, prompt: prompt,
research: options.research || false, research: options.research || false,
projectRoot: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath projectRoot: vscode.workspace.workspaceFolders?.[0]?.uri.fsPath
}); });
// Refresh tasks after update
await this.repository.refresh();
const updatedTasks = await this.repository.getAll();
this.broadcast('tasksUpdated', {
tasks: updatedTasks,
source: 'task-update'
});
response = { success: true }; response = { success: true };
} catch (error) { } catch (error) {
this.logger.error('Failed to update subtask via MCP:', error); this.logger.error('Failed to update subtask via MCP:', error);

View File

@@ -176,7 +176,7 @@ export class TaskMasterApi {
try { try {
const mcpArgs: Record<string, unknown> = { const mcpArgs: Record<string, unknown> = {
id: taskId, id: String(taskId),
status: status, status: status,
projectRoot: options?.projectRoot || this.getWorkspaceRoot() projectRoot: options?.projectRoot || this.getWorkspaceRoot()
}; };
@@ -238,7 +238,7 @@ export class TaskMasterApi {
const prompt = `Update task with the following changes:\n${updateFields.join('\n')}`; const prompt = `Update task with the following changes:\n${updateFields.join('\n')}`;
const mcpArgs: Record<string, unknown> = { const mcpArgs: Record<string, unknown> = {
id: taskId, id: String(taskId),
prompt: prompt, prompt: prompt,
projectRoot: options?.projectRoot || this.getWorkspaceRoot() projectRoot: options?.projectRoot || this.getWorkspaceRoot()
}; };
@@ -284,7 +284,7 @@ export class TaskMasterApi {
try { try {
const mcpArgs: Record<string, unknown> = { const mcpArgs: Record<string, unknown> = {
id: taskId, id: String(taskId),
prompt: prompt, prompt: prompt,
projectRoot: options?.projectRoot || this.getWorkspaceRoot() projectRoot: options?.projectRoot || this.getWorkspaceRoot()
}; };
@@ -327,7 +327,7 @@ export class TaskMasterApi {
try { try {
const mcpArgs: Record<string, unknown> = { const mcpArgs: Record<string, unknown> = {
id: parentTaskId, id: String(parentTaskId),
title: subtaskData.title, title: subtaskData.title,
projectRoot: options?.projectRoot || this.getWorkspaceRoot() projectRoot: options?.projectRoot || this.getWorkspaceRoot()
}; };

View File

@@ -5,9 +5,7 @@
import React, { useReducer, useState, useEffect, useRef } from 'react'; import React, { useReducer, useState, useEffect, useRef } from 'react';
import { VSCodeContext } from './contexts/VSCodeContext'; import { VSCodeContext } from './contexts/VSCodeContext';
import { QueryProvider } from './providers/QueryProvider'; import { QueryProvider } from './providers/QueryProvider';
import { TaskMasterKanban } from './components/TaskMasterKanban'; import { AppContent } from './components/AppContent';
import TaskDetailsView from '@/components/TaskDetailsView';
import { ConfigView } from '@/components/ConfigView';
import { ToastContainer } from './components/ToastContainer'; import { ToastContainer } from './components/ToastContainer';
import { ErrorBoundary } from './components/ErrorBoundary'; import { ErrorBoundary } from './components/ErrorBoundary';
import { appReducer, initialState } from './reducers/appReducer'; import { appReducer, initialState } from './reducers/appReducer';
@@ -96,42 +94,7 @@ export const App: React.FC = () => {
}); });
}} }}
> >
{/* Conditional rendering for different views */} <AppContent />
{(() => {
console.log(
'🎯 App render - currentView:',
state.currentView,
'selectedTaskId:',
state.selectedTaskId
);
if (state.currentView === 'config') {
return (
<ConfigView
sendMessage={sendMessage}
onNavigateBack={() =>
dispatch({ type: 'NAVIGATE_TO_KANBAN' })
}
/>
);
}
if (state.currentView === 'task-details' && state.selectedTaskId) {
return (
<TaskDetailsView
taskId={state.selectedTaskId}
onNavigateBack={() =>
dispatch({ type: 'NAVIGATE_TO_KANBAN' })
}
onNavigateToTask={(taskId: string) =>
dispatch({ type: 'NAVIGATE_TO_TASK', payload: taskId })
}
/>
);
}
return <TaskMasterKanban />;
})()}
<ToastContainer <ToastContainer
notifications={state.toastNotifications} notifications={state.toastNotifications}
onDismiss={(id) => dispatch({ type: 'REMOVE_TOAST', payload: id })} onDismiss={(id) => dispatch({ type: 'REMOVE_TOAST', payload: id })}

View File

@@ -0,0 +1,40 @@
import React from 'react';
import { TaskMasterKanban } from './TaskMasterKanban';
import TaskDetailsView from '@/components/TaskDetailsView';
import { ConfigView } from '@/components/ConfigView';
import { useVSCodeContext } from '../contexts/VSCodeContext';
export const AppContent: React.FC = () => {
const { state, dispatch, sendMessage } = useVSCodeContext();
console.log(
'🎯 AppContent render - currentView:',
state.currentView,
'selectedTaskId:',
state.selectedTaskId
);
if (state.currentView === 'config') {
return (
<ConfigView
sendMessage={sendMessage}
onNavigateBack={() => dispatch({ type: 'NAVIGATE_TO_KANBAN' })}
/>
);
}
if (state.currentView === 'task-details' && state.selectedTaskId) {
return (
<TaskDetailsView
taskId={state.selectedTaskId}
onNavigateBack={() => dispatch({ type: 'NAVIGATE_TO_KANBAN' })}
onNavigateToTask={(taskId: string) =>
dispatch({ type: 'NAVIGATE_TO_TASK', payload: taskId })
}
/>
);
}
// Default to Kanban view
return <TaskMasterKanban />;
};

View File

@@ -53,9 +53,25 @@ export const TaskCard: React.FC<TaskCardProps> = ({
#{task.id} #{task.id}
</span> </span>
{task.dependencies && task.dependencies.length > 0 && ( {task.dependencies && task.dependencies.length > 0 && (
<span className="text-vscode-foreground/50 flex-shrink-0 ml-2"> <div className="flex items-center gap-1 text-vscode-foreground/50 flex-shrink-0 ml-2">
Deps: {task.dependencies.length} <span>Deps:</span>
</span> <div className="flex items-center gap-1">
{task.dependencies.map((depId, index) => (
<React.Fragment key={depId}>
<button
className="font-mono hover:text-vscode-link-activeForeground hover:underline transition-colors"
onClick={(e) => {
e.stopPropagation();
onViewDetails?.(depId);
}}
>
#{depId}
</button>
{index < task.dependencies!.length - 1 && <span>,</span>}
</React.Fragment>
))}
</div>
</div>
)} )}
</div> </div>
</div> </div>

View File

@@ -3,6 +3,8 @@
*/ */
import React, { useState, useCallback, useEffect } from 'react'; import React, { useState, useCallback, useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { RefreshCw } from 'lucide-react';
import { import {
type DragEndEvent, type DragEndEvent,
KanbanBoard, KanbanBoard,
@@ -19,15 +21,16 @@ import { useVSCodeContext } from '../contexts/VSCodeContext';
import { import {
useTasks, useTasks,
useUpdateTaskStatus, useUpdateTaskStatus,
useUpdateTask useUpdateTask,
taskKeys
} from '../hooks/useTaskQueries'; } from '../hooks/useTaskQueries';
import { kanbanStatuses, HEADER_HEIGHT } from '../constants'; import { kanbanStatuses, HEADER_HEIGHT } from '../constants';
import type { TaskMasterTask, TaskUpdates } from '../types'; import type { TaskMasterTask, TaskUpdates } from '../types';
export const TaskMasterKanban: React.FC = () => { export const TaskMasterKanban: React.FC = () => {
const { state, dispatch, sendMessage, availableHeight } = useVSCodeContext(); const { state, dispatch, sendMessage, availableHeight } = useVSCodeContext();
const queryClient = useQueryClient();
const { const {
loading: legacyLoading,
error: legacyError, error: legacyError,
editingTask, editingTask,
polling, polling,
@@ -35,16 +38,28 @@ export const TaskMasterKanban: React.FC = () => {
availableTags availableTags
} = state; } = state;
const [activeTask, setActiveTask] = useState<TaskMasterTask | null>(null); const [activeTask, setActiveTask] = useState<TaskMasterTask | null>(null);
const [isRefreshing, setIsRefreshing] = useState(false);
// Use React Query to fetch tasks // Use React Query to fetch tasks
const { const {
data: serverTasks = [], data: serverTasks = [],
isLoading, isLoading,
error error,
isFetching,
isSuccess
} = useTasks({ tag: currentTag }); } = useTasks({ tag: currentTag });
const updateTaskStatus = useUpdateTaskStatus(); const updateTaskStatus = useUpdateTaskStatus();
const updateTask = useUpdateTask(); const updateTask = useUpdateTask();
// Debug logging
console.log('🔍 TaskMasterKanban Query State:', {
isLoading,
isFetching,
isSuccess,
tasksCount: serverTasks?.length,
error
});
// Temporary state only for active drag operations // Temporary state only for active drag operations
const [tempReorderedTasks, setTempReorderedTasks] = useState< const [tempReorderedTasks, setTempReorderedTasks] = useState<
TaskMasterTask[] | null TaskMasterTask[] | null
@@ -178,6 +193,18 @@ export const TaskMasterKanban: React.FC = () => {
sendMessage({ type: 'retryConnection' }); sendMessage({ type: 'retryConnection' });
}, [sendMessage]); }, [sendMessage]);
// Handle refresh
const handleRefresh = useCallback(async () => {
setIsRefreshing(true);
try {
// Invalidate all task queries
await queryClient.invalidateQueries({ queryKey: taskKeys.all });
} finally {
// Reset after a short delay to show the animation
setTimeout(() => setIsRefreshing(false), 500);
}
}, [queryClient]);
// Handle tag switching // Handle tag switching
const handleTagSwitch = useCallback( const handleTagSwitch = useCallback(
async (tagName: string) => { async (tagName: string) => {
@@ -192,14 +219,13 @@ export const TaskMasterKanban: React.FC = () => {
); );
// Use React Query loading state // Use React Query loading state
const loading = isLoading || legacyLoading;
const displayError = error const displayError = error
? error instanceof Error ? error instanceof Error
? error.message ? error.message
: String(error) : String(error)
: legacyError; : legacyError;
if (loading) { if (isLoading) {
return ( return (
<div <div
className="flex items-center justify-center" className="flex items-center justify-center"
@@ -243,6 +269,16 @@ export const TaskMasterKanban: React.FC = () => {
sendMessage={sendMessage} sendMessage={sendMessage}
dispatch={dispatch} dispatch={dispatch}
/> />
<button
onClick={handleRefresh}
disabled={isRefreshing}
className="p-1.5 rounded hover:bg-vscode-button-hoverBackground transition-colors"
title="Refresh tasks"
>
<RefreshCw
className={`w-4 h-4 text-vscode-foreground/70 ${isRefreshing ? 'animate-spin' : ''}`}
/>
</button>
<PollingStatus polling={polling} onRetry={handleRetry} /> <PollingStatus polling={polling} onRetry={handleRetry} />
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div <div

View File

@@ -19,6 +19,7 @@ export function useTasks(options?: { tag?: string; status?: string }) {
return useQuery({ return useQuery({
queryKey: taskKeys.list(options || {}), queryKey: taskKeys.list(options || {}),
queryFn: async () => { queryFn: async () => {
console.log('🔍 Fetching tasks with options:', options);
const response = await sendMessage({ const response = await sendMessage({
type: 'getTasks', type: 'getTasks',
data: { data: {
@@ -26,8 +27,10 @@ export function useTasks(options?: { tag?: string; status?: string }) {
withSubtasks: true withSubtasks: true
} }
}); });
console.log('📋 Tasks fetched:', response);
return response as TaskMasterTask[]; return response as TaskMasterTask[];
} },
staleTime: 0 // Consider data stale immediately
}); });
} }
@@ -141,17 +144,36 @@ export function useUpdateTask() {
updates: TaskUpdates | { description: string }; updates: TaskUpdates | { description: string };
options?: { append?: boolean; research?: boolean }; options?: { append?: boolean; research?: boolean };
}) => { }) => {
await sendMessage({ console.log('🔄 Updating task:', taskId, updates, options);
const response = await sendMessage({
type: 'updateTask', type: 'updateTask',
data: { taskId, updates, options } data: { taskId, updates, options }
}); });
console.log('📥 Update task response:', response);
// Check for error in response
if (response && typeof response === 'object' && 'error' in response) {
throw new Error(response.error || 'Failed to update task');
}
return response;
}, },
onSuccess: (_, variables) => { onSuccess: async (data, variables) => {
// Invalidate the specific task and all lists console.log('✅ Task update successful, invalidating all task queries');
queryClient.invalidateQueries({ console.log('Response data:', data);
queryKey: taskKeys.detail(variables.taskId) console.log('Task ID:', variables.taskId);
// Invalidate ALL task-related queries (same as handleRefresh)
await queryClient.invalidateQueries({
queryKey: taskKeys.all
}); });
queryClient.invalidateQueries({ queryKey: taskKeys.lists() });
console.log(
'🔄 All task queries invalidated for task:',
variables.taskId
);
} }
}); });
} }
@@ -171,19 +193,37 @@ export function useUpdateSubtask() {
prompt: string; prompt: string;
options?: { research?: boolean }; options?: { research?: boolean };
}) => { }) => {
await sendMessage({ console.log('🔄 Updating subtask:', taskId, prompt, options);
const response = await sendMessage({
type: 'updateSubtask', type: 'updateSubtask',
data: { taskId, prompt, options } data: { taskId, prompt, options }
}); });
console.log('📥 Update subtask response:', response);
// Check for error in response
if (response && typeof response === 'object' && 'error' in response) {
throw new Error(response.error || 'Failed to update subtask');
}
return response;
}, },
onSuccess: (_, variables) => { onSuccess: async (data, variables) => {
// Extract parent task ID from subtask ID (e.g., "1.2" -> "1") console.log(
const parentTaskId = variables.taskId.split('.')[0]; '✅ Subtask update successful, invalidating all task queries'
// Invalidate the parent task details and all lists );
queryClient.invalidateQueries({ console.log('Subtask ID:', variables.taskId);
queryKey: taskKeys.detail(parentTaskId)
// Invalidate ALL task-related queries (same as handleRefresh)
await queryClient.invalidateQueries({
queryKey: taskKeys.all
}); });
queryClient.invalidateQueries({ queryKey: taskKeys.lists() });
console.log(
'🔄 All task queries invalidated for subtask:',
variables.taskId
);
} }
}); });
} }

View File

@@ -96,23 +96,6 @@ export const useVSCodeMessages = (
dispatch({ type: 'SET_TASKS', payload: message.data }); dispatch({ type: 'SET_TASKS', payload: message.data });
break; break;
case 'tasksUpdated':
console.log('📋 Tasks updated:', message.data);
// Extract tasks from the data object
const tasks = message.data?.tasks || message.data;
if (Array.isArray(tasks)) {
dispatch({ type: 'SET_TASKS', payload: tasks });
}
break;
case 'taskStatusUpdated':
console.log('✅ Task status updated:', message);
break;
case 'taskUpdated':
console.log('✅ Task content updated:', message);
break;
case 'pollingStatus': case 'pollingStatus':
dispatch({ dispatch({
type: 'SET_POLLING_STATUS', type: 'SET_POLLING_STATUS',