Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: update CoS task state after unblock
[._.]/ Adam Eivy0d4f5d96264c
diff --git a/client/src/components/cos/ActionableInsightsBanner.jsx b/client/src/components/cos/ActionableInsightsBanner.jsxindex 9a5f35c619..f4d2027428 100644--- a/client/src/components/cos/ActionableInsightsBanner.jsx+++ b/client/src/components/cos/ActionableInsightsBanner.jsx@@ -141,11 +141,12 @@ export default function ActionableInsightsBanner({ insights, onTaskUnblocked, on});if (!result) return;toast.success('Task unblocked and moved to pending');- // Ask the parent to refetch — its fetchData re-pulls insights so the- // unblocked task drops out of the banner — and optimistically splice the- // task list for instant feedback.- onRefresh?.();+ // Update the parent-owned queue and insight snapshot before starting the+ // slower full refresh. That keeps both the banner and task list honest while+ // the refresh is in flight; the parent also guards the refresh from writing+ // an older pre-unblock snapshot over this state.onTaskUnblocked?.(taskId);+ onRefresh?.();};if (!insights) {diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 4aa5fa1021..025326c899 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -139,7 +139,7 @@ function getSuccessRateStyle(rate) {return { bg: 'bg-port-error/15', text: 'text-port-error', label: 'low' };}-export default function TaskItem({ task, isSystem, spawning = false, selected = false, onRefresh, providers, durations, dragHandleProps, apps, instances = null, onEditingChange }) {+export default function TaskItem({ task, isSystem, spawning = false, selected = false, onRefresh, onTaskUnblocked, providers, durations, dragHandleProps, apps, instances = null, onEditingChange }) {// System tasks are persisted in COS-TASKS.md. Every task// mutation must name that source; otherwise the API's user-queue default// searches TASKS.md and reports the system task as missing.@@ -265,6 +265,7 @@ export default function TaskItem({ task, isSystem, spawning = false, selected =const result = await api.updateCosTask(task.id, updates, { silent: true }).catch(err => { toast.error(err.message); return null; });if (!result) return false;toast.success(successMessage);+ if (task.status === 'blocked' && newStatus === 'pending') onTaskUnblocked?.(task.id);onRefresh();return true;};diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsxindex 2df64e32fa..a052f6ab7f 100644--- a/client/src/components/cos/tabs/TasksTab.jsx+++ b/client/src/components/cos/tabs/TasksTab.jsx@@ -38,7 +38,7 @@ function SectionGlyph({ status }) {return <MicroGlyph variant={spec.variant} state={spec.state} animated={spec.animated} size={13} />;}-export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, providers, apps }) {+export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, onTaskUnblocked, providers, apps }) {const [searchParams] = useSearchParams();const [userTasksLocal, setUserTasksLocal] = useState([]);const [durations, setDurations] = useState(null);@@ -279,7 +279,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, p</div><div className="p-2 space-y-1.5">{activeUserTasksLocal.map(task => (- <TaskItem key={task.id} task={task} spawning={isSpawning(task)} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} spawning={isSpawning(task)} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div></div>@@ -296,7 +296,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, p</div><div className="p-2 space-y-1.5">{blockedUserTasksLocal.map(task => (- <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div></div>@@ -319,7 +319,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, p{showCompletedUserTasks && (<div className="p-2 space-y-1.5">{completedUserTasksLocal.map(task => (- <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div>)}@@ -352,7 +352,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, p</div><div className="p-2 space-y-1.5">{pendingSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div></div>@@ -369,7 +369,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, p</div><div className="p-2 space-y-1.5">{activeSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem spawning={isSpawning(task)} selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} isSystem spawning={isSpawning(task)} selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div></div>@@ -386,7 +386,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, p</div><div className="p-2 space-y-1.5">{blockedSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div></div>@@ -409,7 +409,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, p{showCompletedSystemTasks && (<div className="p-2 space-y-1.5">{completedSystemTasks.map(task => (- <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />+ <TaskItem key={task.id} task={task} isSystem selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />))}</div>)}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 378e739853..a392e8824a 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -119,8 +119,8 @@ export default function ChiefOfStaff() {const [canScrollLeft, setCanScrollLeft] = useState(false);const [canScrollRight, setCanScrollRight] = useState(false);const tabsRef = useRef(null);- // Monotonic counter for queue-state writes, so a slow fetchData cannot overwrite- // a fresher fetchQueue result (see both functions below).+ // Monotonic counter for queue/insight-state writes, so a slow fetchData cannot+ // overwrite a fresher optimistic mutation or fetchQueue result.const queueSeqRef = useRef(0);const socket = useSocket();@@ -241,7 +241,7 @@ export default function ChiefOfStaff() {// Apply a real insights payload (including a legitimately-empty []); a null// from a failed/transient fetch preserves the last-good array so the banner// doesn't flicker empty on a blip.- if (insightsData?.insights) setInsights(insightsData.insights);+ if (insightsData?.insights && queueSeqRef.current === queueSeq) setInsights(insightsData.insights);const newState = deriveAgentState(statusData, agentsData, mergedHealth);setAgentState(newState);@@ -261,10 +261,14 @@ export default function ChiefOfStaff() {// endpoint runs a health check that auto-restarts errored PM2 processes (see// the note below), which must never ride the store's per-mutation task stream.const fetchQueue = useCallback(async () => {+ const queueSeq = queueSeqRef.current;const [tasksData, agentsData] = await Promise.all([api.getCosTasks({ silent: true }).catch(() => null),api.getCosAgents({ silent: true }).catch(() => null)]);+ // A confirmed local mutation can supersede this read while it is in flight;+ // never let its older task snapshot undo the optimistic state.+ if (queueSeqRef.current !== queueSeq) return;if (tasksData) setTasks(tasksData);if (Array.isArray(agentsData)) setAgents(agentsData);// Supersede any fetchData still in flight — see the guard in fetchData. Bumped@@ -532,24 +536,30 @@ export default function ChiefOfStaff() {}};- const handleTaskUnblocked = (taskId) => {+ const handleTaskUnblocked = useCallback((taskId) => {+ // A full refresh starts before its first await, so invalidate any read that+ // began before this confirmed mutation. Otherwise its pre-unblock snapshot+ // can put the task and insight back into the blocked state after our local+ // update has already rendered.+ queueSeqRef.current += 1;setTasks(prev => {const unblockSlice = (slice) => {if (!slice) return slice;const blockedTask = slice.grouped?.blocked?.find(t => t.id === taskId);- if (!blockedTask && !slice.tasks?.some(t => t.id === taskId)) return slice;- const unblocked = blockedTask- ? { ...blockedTask, status: 'pending', metadata: { ...blockedTask.metadata, blocker: undefined } }- : null;+ const existingTask = slice.tasks?.find(t => t.id === taskId) || blockedTask;+ if (!existingTask) return slice;+ const unblocked = { ...existingTask, status: 'pending', metadata: { ...existingTask.metadata, blocker: undefined, blockedReason: undefined } };const currentPending = slice.grouped?.pending || [];- const alreadyPending = currentPending.some(t => t.id === taskId);+ const pending = currentPending.some(t => t.id === taskId)+ ? currentPending.map(t => t.id === taskId ? unblocked : t)+ : [...currentPending, unblocked];return {...slice,- tasks: slice.tasks?.map(t => t.id === taskId ? { ...t, status: 'pending', metadata: { ...t.metadata, blocker: undefined } } : t),+ tasks: slice.tasks?.map(t => t.id === taskId ? unblocked : t),grouped: {...slice.grouped,blocked: slice.grouped?.blocked?.filter(t => t.id !== taskId) || [],- pending: alreadyPending ? currentPending : [...currentPending, ...(unblocked ? [unblocked] : [])]+ pending}};};@@ -559,7 +569,24 @@ export default function ChiefOfStaff() {cos: unblockSlice(prev.cos)};});- };+ setInsights(prev => {+ if (!Array.isArray(prev)) return prev;+ return prev.flatMap(insight => {+ if (insight.type !== 'blocked' || !Array.isArray(insight.tasks)) return [insight];+ const remaining = insight.tasks.filter(task => task.id !== taskId);+ if (remaining.length === insight.tasks.length) return [insight];+ if (remaining.length === 0) return [];+ const firstRemaining = remaining[0];+ return [{+ ...insight,+ title: `${remaining.length} blocked task${remaining.length > 1 ? 's' : ''}`,+ description: firstRemaining.blocker || firstRemaining.description || insight.description,+ count: remaining.length,+ tasks: remaining,+ }];+ });+ });+ }, []);// A successful task POST returns the persisted task synchronously. Insert it// into the queue right away so the user gets a durable pending indication@@ -1106,7 +1133,7 @@ export default function ChiefOfStaff() {{activeTab === 'tasks' && (<div role="tabpanel" id="tabpanel-tasks" aria-labelledby="tab-tasks"><ActionableInsightsBanner insights={insights} onTaskUnblocked={handleTaskUnblocked} onRefresh={fetchData} />- <TasksTab tasks={tasks} agents={agents} onRefresh={fetchData} onTaskAdded={handleUserTaskAdded} providers={providers} apps={apps} />+ <TasksTab tasks={tasks} agents={agents} onRefresh={fetchData} onTaskAdded={handleUserTaskAdded} onTaskUnblocked={handleTaskUnblocked} providers={providers} apps={apps} /></div>)}{activeTab === 'agents' && (diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 9798af404b..3b506eb1ef 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -17,6 +17,7 @@ const api = vi.hoisted(() => ({getCosBudgetUsage: vi.fn(),getPersistentMind: vi.fn(),forceCosEvaluate: vi.fn(),+ updateCosTask: vi.fn(),pauseCos: vi.fn(),resumeCos: vi.fn(),forceHealthCheck: vi.fn(),@@ -85,6 +86,7 @@ beforeEach(() => {api.getCosLearningSummary.mockResolvedValue(null);api.getCosActionableInsights.mockResolvedValue({ insights: [] });api.forceHealthCheck.mockResolvedValue({ metrics: { timestamp: 1 }, issues: [] });+ api.updateCosTask.mockResolvedValue({ id: 'task-updated', status: 'pending', metadata: {} });api.getCosTodayActivity.mockResolvedValue({ isRunning: false, stats: { completed: 0 } });api.getCosLearning.mockResolvedValue(null);api.getProviderStatuses.mockResolvedValue({ providers: {} });@@ -595,6 +597,81 @@ describe('ChiefOfStaff task-change subscriptions', () => {});});+describe('ChiefOfStaff task unblock freshness', () => {+ const blockedTask = {+ id: 'sys-blocked-immediate',+ description: 'Blocked task updates immediately',+ status: 'blocked',+ metadata: { blockedReason: 'Waiting for an operator' },+ };++ const blockedInsight = {+ type: 'blocked',+ priority: 'high',+ icon: 'XCircle',+ title: '1 blocked task',+ description: 'Waiting for an operator',+ action: { label: 'Unblock', route: '/cos/tasks' },+ count: 1,+ tasks: [{+ id: blockedTask.id,+ description: blockedTask.description,+ blocker: 'Waiting for an operator',+ taskType: 'internal',+ }],+ };++ const renderBlockedTask = (insights = []) => {+ api.getCosTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [blockedTask] } });+ api.getCosActionableInsights.mockResolvedValue({ insights });+ return render(+ <MemoryRouter initialEntries={['/cos/tasks']}>+ <Routes>+ <Route path="/cos/:tab" element={<ChiefOfStaff />} />+ </Routes>+ </MemoryRouter>,+ );+ };++ it('moves a banner-unblocked task and removes its insight before refresh settles', async () => {+ renderBlockedTask([blockedInsight]);+ expect(await screen.findByText('1 blocked task')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'View Tasks' }));+ const banner = screen.getByText('1 blocked task').closest('.border');+ // Keep the post-mutation reads pending so this assertion only passes when+ // the successful banner action updates both parent-owned surfaces directly.+ api.getCosTasks.mockReturnValue(new Promise(() => {}));+ api.getCosActionableInsights.mockReturnValue(new Promise(() => {}));+ fireEvent.click(within(banner).getByRole('button', { name: 'Unblock' }));++ await waitFor(() => expect(api.updateCosTask).toHaveBeenCalledWith(+ blockedTask.id,+ { status: 'pending', type: 'internal' },+ { silent: true },+ ));+ expect(await screen.findByText('Pending (1)')).toBeInTheDocument();+ expect(screen.queryByText('Blocked (1)')).not.toBeInTheDocument();+ expect(screen.queryByText('1 blocked task')).not.toBeInTheDocument();+ });++ it('moves a card-unblocked task before its follow-up refresh settles', async () => {+ renderBlockedTask();+ expect(await screen.findByText('Blocked (1)')).toBeInTheDocument();+ // Keep the post-mutation read pending so this assertion only passes when the+ // card uses the shared optimistic update rather than waiting for onRefresh.+ api.getCosTasks.mockReturnValue(new Promise(() => {}));+ fireEvent.click(screen.getByRole('button', { name: `Unblock task ${blockedTask.id} and move it to pending` }));++ await waitFor(() => expect(api.updateCosTask).toHaveBeenCalledWith(+ blockedTask.id,+ { status: 'pending', type: 'internal' },+ { silent: true },+ ));+ expect(await screen.findByText('Pending (1)')).toBeInTheDocument();+ expect(screen.queryByText('Blocked (1)')).not.toBeInTheDocument();+ });+});+// fetchData reads 8 endpoints, one of which runs a server-side health check, so a// queue refresh started LATER routinely resolves FIRST. Without a guard, the slow// batch's pre-flip task payload lands last and restores the pending-AND-active