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
refactor: lift CoS actionable-insights fetch into ChiefOfStaff.fetchData (#2654)
[._.]/ Adam Eivyfc7d19bdc753
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 50912e53dc..e13a2aa0f4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -116,3 +116,5 @@- **SongBook — a Brain repertoire for guitar tabs, chord sheets, and sheet music with learning-stage tracking and an autoscrolling play view.** New `/songbook` index (filter by stage/instrument/tag/search, all URL-addressable) and `/songbook/:id` full-bleed viewer: tab/chord/ChordPro content renders with highlighted chord tokens, section headers, and horizontally-scrollable tab staffs; an Ultimate-Guitar-style autoscroll (play/pause, speed slider, keyboard shortcuts, screen wake-lock) paces long charts, with non-destructive transpose and font-size controls persisted per song. Each song tracks a learning stage (`new → learning → learned → memorized`) flippable from the card or viewer. Songs import by paste (auto-cleanup of HTML remnants + format detection) or by URL — a server-side SSRF-guarded fetch with an Ultimate Guitar extractor and generic `<pre>`/plain-text fallbacks returns an editable draft, never auto-saving. Sheet-music/MIDI/image attachments upload per song: metadata (name, size, SHA-256) lives in the synced record while bytes stay machine-local under `data/brain/songbook/` (peers show "not on this machine"). Songs are a first-class Brain entity type (`data/brain/songs.json`), so they federate across machines with LWW sync, tombstone deletes, and reconcile coverage automatically — and they're reachable from ⌘K and voice nav (`nav.brain.songbook`). New pure `tabNotation` lib (line classification, ChordPro, transpose with column preservation, paste normalization) with extensive unit tests. Ships three public-domain seed songs — "House of the Rising Sun" arranged for guitar, piano, and ukulele — seeded into existing installs by migration 190 (never overwriting a user-edited, synced, or deleted copy). The parser also handles dash-joined chord changes (`Am-Am7` classifies, renders, and transposes as one token) and Unicode accidentals (♯/♭ normalize to #/b on paste so `F♯m` transposes correctly).- **Fix the app-manager Git tab's "Clean N merged" button counting worktree-locked branches, so cleanup deleted zero and toasted "No merged branches to clean up".** `getBranches` marked a local branch `merged: true` from `git branch --merged` alone, but `deleteMergedBranches` (correctly) skips branches checked out in a worktree — `git branch -d` can't delete them. On any install with active CoS-agent/claim worktrees, those merged-but-locked branches inflated the button's count while yielding no deletions. `getBranches` now also returns a `worktree` flag (branch checked out in another worktree), the Git tab's `localMergedCount` counts only `merged && !worktree` so the button reflects what the server will actually delete, and locked branches render a `worktree` badge next to `merged` so the user sees why they linger. Server + client tests cover the count and badge.++- **[issue-2654] Lift the CoS actionable-insights fetch into `ChiefOfStaff.fetchData` so the banner refreshes for the whole staleness class.** `ActionableInsightsBanner` owned its own `/cos/actionable-insights` fetch on a 60s `useAutoRefetch` poll, decoupled from the parent's 30s task poll, so its server-derived counts (blocked, approvals, "N health issues") lagged any parent-owned data change until that poll. A prior fix bridged only the TasksTab mutation path via an `insightsRefreshKey` counter; socket-driven task changes, agent spawn/completion, and health checks stayed stale. Insights are now fetched inside `ChiefOfStaff.fetchData`'s `Promise.all` and passed down as an `insights` prop, making the banner presentational (it keeps only dismiss/expand/unblock UI state); its unblock path calls `onRefresh` up instead of owning a `refetch()`. Because agent spawn/completion already call `fetchData`, they refresh the banner for free; the two paths that intentionally do a targeted `setState` rather than a full refetch — the `cos:health:check`/manual health-check handlers (to preserve their own status messaging) and the `cos:tasks:user:changed` socket handler — call a lightweight insights-only `refreshInsights()` so a newly-found or cleared health issue / daemon-driven task change reflects immediately. A failed/transient insights fetch (`null`) preserves the last-good array (matching the retired poll's behavior); a legitimately-empty `[]` clears the banner. Retires `insightsRefreshKey`, `refreshTasks`'s signal bump, the banner's `refreshKey` prop, its `didMountRef` skip-mount effect, and its `useAutoRefetch` self-poll. Tests cover the prop-driven render, null/empty gating, the unblock-up path, and the health/task socket refreshes.diff --git a/client/src/components/cos/ActionableInsightsBanner.jsx b/client/src/components/cos/ActionableInsightsBanner.jsxindex beb5a814a2..19b101055e 100644--- a/client/src/components/cos/ActionableInsightsBanner.jsx+++ b/client/src/components/cos/ActionableInsightsBanner.jsx@@ -1,6 +1,5 @@-import { useState, useEffect, useRef } from 'react';+import { useState } from 'react';import { useNavigate } from 'react-router-dom';-import { useAutoRefetch } from '../../hooks/useAutoRefetch';import toast from '../ui/Toast';import {AlertCircle,@@ -89,33 +88,18 @@ const PRIORITY_STYLES = {}};-export default function ActionableInsightsBanner({ onTaskUnblocked, refreshKey = 0 }) {+// `ChiefOfStaff.fetchData` now owns the actionable-insights fetch and passes the+// result down as `insights`, so this banner is presentational — it holds only+// dismiss/expand UI state. Every parent trigger that refetches CoS data (task+// mutations, socket-driven changes, health checks, the 30s poll) refreshes the+// banner for free, and the unblock path calls `onRefresh` up instead of owning+// its own poll. `insights` is null until the first parent fetch resolves; the+// parent preserves the last-good array across transient fetch failures.+export default function ActionableInsightsBanner({ insights, onTaskUnblocked, onRefresh }) {const [dismissed, setDismissed] = useState([]);const [expanded, setExpanded] = useState({});const navigate = useNavigate();- // Let errors throw — `useAutoRefetch` preserves the last-good insights on- // transient failures. `silent: true` keeps the 60s poll quiet on blips.- const { data, loading, refetch } = useAutoRefetch(- () => api.getCosActionableInsights({ silent: true }),- 60_000,- );-- // Insights (blocked count, approvals, etc.) are derived server-side from the- // task list, so a task-list mutation in the parent must re-derive them here —- // otherwise deleting a blocked task leaves a stale "N blocked tasks" alert up- // until the 60s poll or a manual dismiss. The parent bumps `refreshKey` on- // every task mutation; skip the initial mount since the hook fetches then.- // `refetch` is stable, so this only fires on a real key change.- const didMountRef = useRef(false);- useEffect(() => {- if (!didMountRef.current) {- didMountRef.current = true;- return;- }- refetch();- }, [refreshKey, refetch]);-const handleDismiss = (type) => {setDismissed(prev => [...prev, type]);};@@ -138,19 +122,18 @@ export default function ActionableInsightsBanner({ onTaskUnblocked, refreshKey =});if (!result) return;toast.success('Task unblocked and moved to pending');- // Re-fetch insights so the unblocked task drops out of the banner. The- // hook owns `data`, so we can't optimistically splice it here — the- // server already persisted the unblock, so a refetch reflects it.- refetch();- // Notify parent to update task list reactively+ // 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?.();onTaskUnblocked?.(taskId);};- if (loading || !data?.insights) {+ if (!insights) {return null;}- const visibleInsights = data.insights.filter(i => !dismissed.includes(i.type));+ const visibleInsights = insights.filter(i => !dismissed.includes(i.type));if (visibleInsights.length === 0) {return null;diff --git a/client/src/components/cos/ActionableInsightsBanner.test.jsx b/client/src/components/cos/ActionableInsightsBanner.test.jsxindex 544e09458b..d4ef751fb6 100644--- a/client/src/components/cos/ActionableInsightsBanner.test.jsx+++ b/client/src/components/cos/ActionableInsightsBanner.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, waitFor } from '@testing-library/react';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';import { insightProvenance } from './ActionableInsightsBanner';@@ -30,65 +30,86 @@ describe('ActionableInsightsBanner insightProvenance', () => {});});-// Regression: deleting a blocked task from the tasks page used to leave the-// "N blocked tasks" alert bar up until the 60s poll or a manual dismiss, because-// the banner owns its own insights fetch (decoupled from the task list). The-// parent now bumps `refreshKey` on every task mutation so the banner-// re-derives immediately. These tests pin that bridge.-const api = vi.hoisted(() => ({ getCosActionableInsights: vi.fn() }));+// The banner is now presentational (#2654): ChiefOfStaff.fetchData owns the+// actionable-insights fetch and passes the result down as `insights`, so every+// parent trigger that refetches CoS data refreshes the banner for free. These+// tests pin the prop-driven render, the null/empty gating, and the unblock path+// calling `onRefresh` up instead of owning its own poll.+const api = vi.hoisted(() => ({ updateCosTask: vi.fn() }));vi.mock('../../services/api', () => api);vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));const ActionableInsightsBanner = (await import('./ActionableInsightsBanner')).default;-const renderBanner = (refreshKey) =>+const renderBanner = (props) =>render(<MemoryRouter>- <ActionableInsightsBanner refreshKey={refreshKey} />+ <ActionableInsightsBanner {...props} /></MemoryRouter>,);-describe('ActionableInsightsBanner refreshKey', () => {+describe('ActionableInsightsBanner (presentational)', () => {beforeEach(() => {vi.clearAllMocks();- api.getCosActionableInsights.mockResolvedValue({+ });++ it('renders nothing before the first parent fetch resolves (null insights)', () => {+ const { container } = renderBanner({ insights: null });+ expect(container).toBeEmptyDOMElement();+ });++ it('renders nothing when insights is a legitimately-empty array', () => {+ // Empty (all-clear) must render nothing — distinct from null (not-yet-fetched)+ // but visually identical, and never re-hitting the API to find that out.+ const { container } = renderBanner({ insights: [] });+ expect(container).toBeEmptyDOMElement();+ });++ it('renders the primary insight passed as a prop (no fetch of its own)', () => {+ renderBanner({insights: [- { type: 'blocked', priority: 'warning', icon: 'AlertTriangle', title: '2 blocked tasks', description: 'blocked', tasks: [] },+ { type: 'approval', priority: 'high', icon: 'AlertCircle', title: '3 approvals waiting', action: { label: 'Review', route: '/cos/tasks' } },],});+ expect(screen.getByText('3 approvals waiting')).toBeInTheDocument();+ // The banner never calls the API directly anymore — the parent owns fetching.+ expect(api.updateCosTask).not.toHaveBeenCalled();});- it('refetches insights when refreshKey changes (a task was deleted)', async () => {- const { rerender } = renderBanner(0);- // Mount must fetch exactly once — the hook's own immediate fetch. The- // refreshKey effect skips mount (the didMountRef guard), so a second fetch- // here would mean the guard was dropped and every mount double-fetches- // /cos/actionable-insights in production. Pinning the count catches that.- await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalledTimes(1));-- rerender(- <MemoryRouter>- <ActionableInsightsBanner refreshKey={1} />- </MemoryRouter>,- );-- // Key changed → exactly one more fetch (the refetch), not zero, not two.- await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalledTimes(2));+ it('hides insights the user dismisses', () => {+ renderBanner({+ insights: [+ { type: 'approval', priority: 'high', icon: 'AlertCircle', title: '3 approvals waiting', action: { label: 'Review', route: '/cos/tasks' } },+ ],+ });+ fireEvent.click(screen.getByTitle('Dismiss'));+ expect(screen.queryByText('3 approvals waiting')).not.toBeInTheDocument();});- it('does not refetch when re-rendered without a key change', async () => {- const { rerender } = renderBanner(3);- await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());- const before = api.getCosActionableInsights.mock.calls.length;+ it('unblocks a task and calls onRefresh + onTaskUnblocked up (no self-poll)', async () => {+ api.updateCosTask.mockResolvedValue({ id: 't1' });+ const onRefresh = vi.fn();+ const onTaskUnblocked = vi.fn();+ renderBanner({+ insights: [+ {+ type: 'blocked', priority: 'warning', icon: 'AlertTriangle', title: '1 blocked task',+ action: {}, tasks: [{ id: 't1', description: 'stuck task', taskType: 'user' }],+ },+ ],+ onRefresh,+ onTaskUnblocked,+ });+ // Expand to reveal the per-task Unblock button, then click it.+ fireEvent.click(screen.getByText('View Tasks'));+ fireEvent.click(screen.getByText('Unblock'));- // Same key → the refetch effect's deps are unchanged, so no extra fetch.- rerender(- <MemoryRouter>- <ActionableInsightsBanner refreshKey={3} />- </MemoryRouter>,+ await waitFor(() =>+ expect(api.updateCosTask).toHaveBeenCalledWith('t1', { status: 'pending', type: 'user' }, { silent: true }),);- await new Promise((r) => setTimeout(r, 0));-- expect(api.getCosActionableInsights.mock.calls.length).toBe(before);+ // The parent refetch (fetchData re-pulls insights) is how the unblocked task+ // drops out of the banner — the banner no longer owns a refetch.+ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));+ expect(onTaskUnblocked).toHaveBeenCalledWith('t1');});});diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex 0d5bb50fe3..71646bf5e7 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -85,12 +85,12 @@ export default function ChiefOfStaff() {);const [activeAgentMeta, setActiveAgentMeta] = useState(null);const [learningSummary, setLearningSummary] = useState(null);- // Bumped on every task-list mutation so the ActionableInsightsBanner (a- // decoupled sibling that owns its own insights fetch) re-derives "N blocked- // tasks" etc. immediately instead of lingering until its 60s poll. This covers- // only the TasksTab mutation path; socket/health-driven insight changes still- // rely on the banner's own poll.- const [insightsRefreshKey, setInsightsRefreshKey] = useState(0);+ // Actionable insights (blocked/approval/health counts) are fetched here in+ // fetchData and passed to ActionableInsightsBanner as a prop, so every trigger+ // that refetches CoS data — task mutations, socket-driven changes, health+ // checks, the 30s poll — refreshes the banner without a separate signal. null+ // until the first fetch resolves; preserved across transient fetch failures.+ const [insights, setInsights] = useState(null);const [canScrollLeft, setCanScrollLeft] = useState(false);const [canScrollRight, setCanScrollRight] = useState(false);const tabsRef = useRef(null);@@ -126,14 +126,17 @@ export default function ChiefOfStaff() {}, []);const fetchData = useCallback(async () => {- const [statusData, tasksData, agentsData, healthData, providersData, appsData, learningSummaryData] = await Promise.all([+ const [statusData, tasksData, agentsData, healthData, providersData, appsData, learningSummaryData, insightsData] = await Promise.all([api.getCosStatus().catch(() => null),api.getCosTasks().catch(() => ({ user: null, cos: null })),api.getCosAgents().catch(() => []),api.getCosHealth().catch(() => null),api.getProviders().catch(() => ({ providers: [] })),api.getApps().catch(() => []),- api.getCosLearningSummary().catch(() => null)+ api.getCosLearningSummary().catch(() => null),+ // `silent: true` keeps transient poll blips quiet, matching the banner's+ // retired 60s poll; `.catch(() => null)` → preserve last-good below.+ api.getCosActionableInsights({ silent: true }).catch(() => null)]);setStatus(statusData);setTasks(tasksData);@@ -143,6 +146,10 @@ export default function ChiefOfStaff() {// Filter out PortOS Autofixer (it's part of PortOS project)setApps(appsData.filter(a => a.id !== 'portos-autofixer'));setLearningSummary(learningSummaryData);+ // 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);setLoading(false);const newState = deriveAgentState(statusData, agentsData, healthData);@@ -155,15 +162,16 @@ export default function ChiefOfStaff() {setActiveAgentMeta(runningAgent?.metadata || null);}, [deriveAgentState]);- // Task-mutation refresh: refetch the task list AND signal the insights banner- // to re-derive. Deleting a blocked task, for example, must drop it from both- // the list and the banner's "N blocked tasks" alert — the banner owns its own- // fetch, so bumping the signal is how the delete reaches it. The background- // 30s poll calls fetchData directly (not this), so it doesn't over-refetch.- const refreshTasks = useCallback(() => {- setInsightsRefreshKey(v => v + 1);- return fetchData();- }, [fetchData]);+ // Targeted insights-only refresh for parent state changes that DON'T route+ // through fetchData — health checks and socket-driven task changes update+ // `health`/`tasks` locally (to keep their own status messaging / avoid a full+ // refetch) rather than calling fetchData. The banner's server-derived counts+ // (blocked, health issues) would otherwise lag those until the 30s poll, so we+ // re-pull just insights here. Same last-good/silent semantics as fetchData.+ const refreshInsights = useCallback(async () => {+ const insightsData = await api.getCosActionableInsights({ silent: true }).catch(() => null);+ if (insightsData?.insights) setInsights(insightsData.insights);+ }, []);// Redirect unknown tab IDs to the default tab — `activeTab !== tab` only// when the param failed validation and fell back.@@ -204,6 +212,9 @@ export default function ChiefOfStaff() {const handleTasksUserChanged = (data) => {setTasks(prev => ({ ...prev, user: data }));+ // Socket-driven task changes (daemon status flips, blocks/unblocks) don't+ // go through fetchData, so refresh the banner's blocked/approval counts.+ refreshInsights();};socket.on('cos:tasks:user:changed', handleTasksUserChanged);@@ -265,6 +276,9 @@ export default function ChiefOfStaff() {const handleHealthCheck = (data) => {setHealth({ lastCheck: data.metrics?.timestamp, issues: data.issues });+ // Health feeds the banner's "N health issues" insight; refresh it so a+ // newly-found (or cleared) issue reflects immediately, not on the 30s poll.+ refreshInsights();if (data.issues?.length > 0) {setAgentState('investigating');setStatusMessage(`Health check: ${data.issues.length} issue${data.issues.length > 1 ? 's' : ''} found`);@@ -313,7 +327,7 @@ export default function ChiefOfStaff() {socket.off('cos:log', handleCosLog);socket.off('apps:changed', handleAppsChanged);};- }, [socket, fetchData]);+ }, [socket, fetchData, refreshInsights]);const handleStart = async () => {const result = await api.startCos({ silent: true }).catch(err => {@@ -398,6 +412,9 @@ export default function ChiefOfStaff() {setSpeaking(false);if (result) {setHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues });+ // Refresh the banner's health-issue count without a full fetchData (which+ // would clobber the health-specific status message set below).+ refreshInsights();toast.success('Health check complete');if (result.issues?.length > 0) {setStatusMessage(`Health: ${result.issues.length} issue${result.issues.length > 1 ? 's' : ''} detected`);@@ -872,9 +889,9 @@ export default function ChiefOfStaff() {<div role="tabpanel" id="tabpanel-tasks" aria-labelledby="tab-tasks">{/* Tasks-only widgets live under the tab nav so they don't stretch abovetabs that don't surface this data. */}- <ActionableInsightsBanner onTaskUnblocked={handleTaskUnblocked} refreshKey={insightsRefreshKey} />+ <ActionableInsightsBanner insights={insights} onTaskUnblocked={handleTaskUnblocked} onRefresh={fetchData} /><QuickSummary />- <TasksTab tasks={tasks} onRefresh={refreshTasks} providers={providers} apps={apps} />+ <TasksTab tasks={tasks} onRefresh={fetchData} providers={providers} apps={apps} /></div>)}{activeTab === 'agents' && (diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 0e75b8f333..493f593cb7 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, waitFor, fireEvent } from '@testing-library/react';+import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';import { MemoryRouter, Routes, Route } from 'react-router-dom';// Regression coverage for #2519 — the page-level Force Evaluate handler must@@ -13,6 +13,7 @@ const api = vi.hoisted(() => ({getProviders: vi.fn(),getApps: vi.fn(),getCosLearningSummary: vi.fn(),+ getCosActionableInsights: vi.fn(),getCosBudgetUsage: vi.fn(),forceCosEvaluate: vi.fn(),updateCosConfig: vi.fn(),@@ -59,6 +60,7 @@ beforeEach(() => {api.getProviders.mockResolvedValue({ providers: [] });api.getApps.mockResolvedValue([]);api.getCosLearningSummary.mockResolvedValue(null);+ api.getCosActionableInsights.mockResolvedValue({ insights: [] });api.getCosBudgetUsage.mockResolvedValue({ usage: {} });});@@ -101,3 +103,50 @@ describe('ChiefOfStaff handleForceEvaluate', () => {expect(api.forceCosEvaluate).toHaveBeenCalledWith({ silent: true });});});++// #2654: the banner is now prop-driven, and paths that don't go through+// fetchData (socket-driven health checks / task changes) must still refresh the+// server-derived insight counts so the banner doesn't lag until the 30s poll.+describe('ChiefOfStaff insight freshness (#2654)', () => {+ const getSocketHandler = (event) => {+ const entry = socketStub.on.mock.calls.find(([evt]) => evt === event);+ return entry?.[1];+ };++ it('refreshes actionable insights when a socket health-check arrives', async () => {+ renderConfigTab();+ // The initial fetchData pulls insights once; wait for it before firing.+ await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());+ const before = api.getCosActionableInsights.mock.calls.length;++ const handleHealthCheck = getSocketHandler('cos:health:check');+ expect(handleHealthCheck).toBeTypeOf('function');+ // Empty issues avoids the >0 branch's setTimeout(setSpeaking) so no state+ // update escapes act; refreshInsights fires unconditionally either way.+ await act(async () => {+ handleHealthCheck({ metrics: { timestamp: 1 }, issues: [] });+ });++ // Health doesn't call fetchData (that would clobber its status message) — it+ // re-pulls just insights, so the call count must advance past the initial.+ await waitFor(() =>+ expect(api.getCosActionableInsights.mock.calls.length).toBeGreaterThan(before),+ );+ });++ it('refreshes actionable insights on a socket task change', async () => {+ renderConfigTab();+ await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());+ const before = api.getCosActionableInsights.mock.calls.length;++ const handleTasksUserChanged = getSocketHandler('cos:tasks:user:changed');+ expect(handleTasksUserChanged).toBeTypeOf('function');+ await act(async () => {+ handleTasksUserChanged({ tasks: [], grouped: {} });+ });++ await waitFor(() =>+ expect(api.getCosActionableInsights.mock.calls.length).toBeGreaterThan(before),+ );+ });+});