Skip to content

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

perf: stop refetching the Chief of Staff page on every task selection

[._.]/ Adam Eivyb04b43f2e5c0
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 0530d32161..27dd094056 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -130,6 +130,11 @@ export default function ChiefOfStaff() {
const { tab } = useParams();
const [searchParams] = useSearchParams();
const selectedTask = searchParams.get('task') || undefined;
+ // The selection is read through a ref by the page-level reads and the socket
+ // handlers, so changing it changes none of their identities: a click on a
+ // task must not refetch the page or re-register fourteen listeners (#12032).
+ const selectedTaskRef = useRef(selectedTask);
+ selectedTaskRef.current = selectedTask;
const navigate = useNavigate();
const activeTab = useValidTab(TABS, 'tasks');
const { isFeatureEnabled } = useInstanceFeatures();
@@ -141,7 +146,8 @@ export default function ChiefOfStaff() {
const needsApps = needsProviders || activeTab === 'memory';
const routeRef = useRef(activeTab);
routeRef.current = activeTab;
- const queryKey = `${activeTab}:${selectedTask || ''}`;
+ // Page-level reads are keyed on the tab alone; the selection is not a page.
+ const queryKey = activeTab;
const queryRef = useRef(queryKey);
queryRef.current = queryKey;
const inFlight = useRef(null);
@@ -150,6 +156,8 @@ export default function ChiefOfStaff() {
const [status, setStatus] = useState(null);
const [tasks, setTasks] = useState({ user: null, cos: null });
+ const tasksRef = useRef(tasks);
+ tasksRef.current = tasks;
const [agents, setAgents] = useState([]);
const [agentsLoaded, setAgentsLoaded] = useState(false);
const [agentsError, setAgentsError] = useState(null);
@@ -365,7 +373,7 @@ export default function ChiefOfStaff() {
// Paint the visible queue before ancillary summaries and references settle.
const coreRead = Promise.all([
api.getCosStatus().catch(() => null),
- needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTask, signal: controller.signal, silent: true }).catch(() => null) : Promise.resolve(null),
+ needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTaskRef.current, signal: controller.signal, silent: true }).catch(() => null) : Promise.resolve(null),
readAgents(controller),
]);
const healthObservation = healthObservationRef.current;
@@ -449,7 +457,7 @@ export default function ChiefOfStaff() {
if (pending.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshPageData();
});
return pending.promise;
- }, [activeTab, queryKey, selectedTask, needsTasks, needsAgents, needsProviders, needsApps, deriveAgentState, applyHealth, markHealthUnavailable, applyProviders, applyApps, readAgents]);
+ }, [activeTab, queryKey, needsTasks, needsAgents, needsProviders, needsApps, deriveAgentState, applyHealth, markHealthUnavailable, applyProviders, applyApps, readAgents]);
// Coalesce event bursts into a read of the visible queue and scalar shell
// status. Insights use persisted health; invalidation never runs PM2 repair.
@@ -468,7 +476,7 @@ export default function ChiefOfStaff() {
: Promise.resolve(null);
request.promise = Promise.all([
api.getCosStatus().catch(() => null),
- needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTask, signal: controller.signal, silent: true }).catch(() => null) : null,
+ needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTaskRef.current, signal: controller.signal, silent: true }).catch(() => null) : null,
readAgents(controller),
]).then(async ([summary, tasksData]) => {
if (controller.signal.aborted || queryRef.current !== queryKey || queueSeqRef.current !== queueSeq) return;
@@ -481,7 +489,7 @@ export default function ChiefOfStaff() {
if (request.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshQueueData();
});
return request.promise;
- }, [queryKey, needsTasks, selectedTask, readAgents]);
+ }, [queryKey, needsTasks, readAgents]);
// All page insight reads use cached health. Explicit Run Check owns repairs;
// task invalidations must never trigger a health-check/socket feedback loop.
@@ -500,6 +508,29 @@ export default function ChiefOfStaff() {
return () => { inFlight.current?.controller.abort(); queuePending.current?.controller.abort(); };
}, [fetchData]);
+ // The selection-dependent read. The mount read already carries `selected`,
+ // so a deep link costs nothing extra; a later selection that is not in the
+ // loaded lists (a historical task opened from a summary link) costs exactly
+ // one record read, merged into the list it belongs to.
+ useEffect(() => {
+ if (!selectedTask || !needsTasks) return undefined;
+ const { user, cos } = tasksRef.current;
+ if (!user && !cos) return undefined;
+ const loaded = [...(user?.tasks || []), ...(cos?.tasks || [])];
+ if (loaded.some(task => task.id === selectedTask)) return undefined;
+ let active = true;
+ api.getCosTask(selectedTask, { silent: true }).then((found) => {
+ if (!active || !found?.task) return;
+ const key = found.source === 'internal' ? 'cos' : 'user';
+ setTasks(prev => {
+ const list = prev[key];
+ if (!list) return prev;
+ return { ...prev, [key]: { ...list, tasks: [...(list.tasks || []).filter(task => task.id !== found.task.id), found.task] } };
+ });
+ }).catch(() => {});
+ return () => { active = false; };
+ }, [selectedTask, needsTasks]);
+
useEffect(() => {
if (!socket) return;
@@ -526,7 +557,7 @@ export default function ChiefOfStaff() {
const handleTasksUserChanged = (data) => {
if (!needsTasks) return;
- if (data?.tasks) setTasks(prev => ({ ...prev, user: { ...data, tasks: data.tasks.filter(task => task.status !== 'completed' || task.id === selectedTask), completedCount: data.tasks.filter(task => task.status === 'completed').length } }));
+ if (data?.tasks) setTasks(prev => ({ ...prev, user: { ...data, tasks: data.tasks.filter(task => task.status !== 'completed' || task.id === selectedTaskRef.current), completedCount: data.tasks.filter(task => task.status === 'completed').length } }));
else refreshQueue();
};
socket.on('cos:tasks:user:changed', handleTasksUserChanged);
@@ -537,7 +568,7 @@ export default function ChiefOfStaff() {
// around. Same full-list payload as the user event, so swap it in directly.
const handleTasksCosChanged = (data) => {
if (!needsTasks) return;
- if (data?.tasks) setTasks(prev => ({ ...prev, cos: { ...data, tasks: data.tasks.filter(task => task.status !== 'completed' || task.id === selectedTask), completedCount: data.tasks.filter(task => task.status === 'completed').length } }));
+ if (data?.tasks) setTasks(prev => ({ ...prev, cos: { ...data, tasks: data.tasks.filter(task => task.status !== 'completed' || task.id === selectedTaskRef.current), completedCount: data.tasks.filter(task => task.status === 'completed').length } }));
else refreshQueue();
};
socket.on('cos:tasks:cos:changed', handleTasksCosChanged);
@@ -694,7 +725,7 @@ export default function ChiefOfStaff() {
socket.off('apps:changed', handleAppsChanged);
refreshQueue.cancel();
};
- }, [socket, fetchData, fetchQueue, needsAgents, needsTasks, selectedTask, needsApps, needsProviders, applyApps, applyProviders, setSpeakingFor]);
+ }, [socket, fetchData, fetchQueue, needsAgents, needsTasks, needsApps, needsProviders, applyApps, applyProviders, setSpeakingFor]);
const handleStart = async () => {
const result = await api.startCos({ silent: true }).catch(err => {
diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsx
index f65ea95881..b0de159ba8 100644
--- a/client/src/pages/ChiefOfStaff.test.jsx
+++ b/client/src/pages/ChiefOfStaff.test.jsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent, act, within } from '@testing-library/react';
-import { MemoryRouter, Routes, Route } from 'react-router';
+import { MemoryRouter, Routes, Route, useNavigate } from 'react-router';
// Regression coverage for #2519 — the page-level Force Evaluate handler must
// only toast success after the request resolves, and must toast the error
@@ -9,6 +9,7 @@ vi.mock('../hooks/useAssignableInstances', () => ({ default: () => ({ instances:
const api = vi.hoisted(() => ({
getCosStatus: vi.fn(),
getCosTasks: vi.fn(),
+ getCosTask: vi.fn(),
getCosAgents: vi.fn(),
getCosHealth: vi.fn(),
getProviders: vi.fn(),
@@ -714,6 +715,55 @@ describe('ChiefOfStaff insight freshness (#2654)', () => {
// running BEFORE flipping its task off `pending`, the fetch fired by
// `cos:agent:spawned` always reads the task as still-queued, which is what left
// the row showing as pending AND active for up to a poll interval.
+// #12032 — the selection is a URL param. Folding it into the page's query key
+// made every click re-run the full read fan-out and tear down and re-register
+// every socket listener. Selecting a task outside the loaded lists now costs
+// one record read and nothing else.
+describe('ChiefOfStaff task selection', () => {
+ function SelectProbe() {
+ const navigate = useNavigate();
+ return <button type="button" onClick={() => navigate('/cos/tasks?task=task-old&source=user')}>Select archived task</button>;
+ }
+
+ it('reads one record for a selection and leaves page reads and socket listeners alone', async () => {
+ api.getCosTasks.mockImplementation(async ({ view } = {}) => (view === 'completed'
+ ? { items: [], total: 1, nextCursor: null }
+ : { user: { tasks: [], grouped: {}, completedCount: 1 }, cos: { tasks: [], grouped: {}, completedCount: 0 } }));
+ api.getCosTask.mockResolvedValue({
+ task: { id: 'task-old', description: 'An archived example task', status: 'completed', metadata: {} },
+ source: 'user',
+ });
+ render(
+ <MemoryRouter initialEntries={['/cos/tasks']}>
+ <Routes>
+ <Route path="/cos/:tab" element={<><ChiefOfStaff /><SelectProbe /></>} />
+ </Routes>
+ </MemoryRouter>,
+ );
+ await waitForPageShell();
+ await screen.findByRole('button', { name: 'Add test task' });
+ await waitFor(() => expect(api.getCosActionableInsights).toHaveBeenCalled());
+
+ const pageReads = () => [
+ api.getCosStatus, api.getCosAgents, api.getCosHealth, api.getProviders, api.getApps,
+ api.getCosLearningSummary, api.getCosActionableInsights,
+ ].map(fn => fn.mock.calls.length);
+ const queueReads = () => api.getCosTasks.mock.calls.filter(([args]) => args?.view === 'queue').length;
+ const before = { page: pageReads(), queue: queueReads(), on: socketStub.on.mock.calls.length, off: socketStub.off.mock.calls.length };
+
+ fireEvent.click(screen.getByRole('button', { name: 'Select archived task' }));
+
+ await waitFor(() => expect(api.getCosTask).toHaveBeenCalledTimes(1));
+ expect(api.getCosTask).toHaveBeenCalledWith('task-old', expect.objectContaining({ silent: true }));
+ expect(await screen.findByText('An archived example task')).toBeInTheDocument();
+
+ expect(pageReads()).toEqual(before.page);
+ expect(queueReads()).toBe(before.queue);
+ expect(socketStub.on.mock.calls.length).toBe(before.on);
+ expect(socketStub.off.mock.calls.length).toBe(before.off);
+ });
+});
+
describe('ChiefOfStaff task-change subscriptions', () => {
const getSocketHandler = (event) => socketStub.on.mock.calls.find(([evt]) => evt === event)?.[1];
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 60bddf9465..6f8ce411a4 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -167,6 +167,8 @@ export const updateCosConfig = (config, options = {}) => request('/cos/config',
});
// Today's per-domain autonomy usage (#711) for the Domain Budgets panel.
export const getCosBudgetUsage = (options = {}) => request('/cos/budget-usage', options);
+// One task plus its queue (`{ task, source }`), for a selection outside the lists a page holds.
+export const getCosTask = (id, options = {}) => request(`/cos/tasks/${encodeURIComponent(id)}`, options);
export const getCosTasks = ({ view, source, cursor, limit, selected, ...options } = {}) => request(`/cos/tasks${runEventQuery({ view, source, cursor, limit, selected })}`, options);
export const addCosTask = (task, options = {}) => request('/cos/tasks', {
method: 'POST',
diff --git a/docs/API.md b/docs/API.md
index 8b05b7fe4e..8f06bb061a 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -260,6 +260,7 @@ Context tools remain read-only. Semantic reads and writes are independent, defau
| GET | `/cos/tools/calls/:requestId` | Read a retained normalized tool result |
| PUT | `/cos/config` | Update configuration |
| GET | `/cos/tasks` | Bounded task list: all non-completed tasks plus the first 25 completed (`completedCount`, `completedNextCursor`); `view=queue`, `view=completed` (paged), `view=full` (raw unbounded store) |
+| GET | `/cos/tasks/:id` | One task as stored plus the queue it lives in: `{ task, source: 'user' \| 'internal' }`; 404 when unknown |
| POST | `/cos/evaluate` | Force task evaluation |
| GET | `/cos/health` | Get health status |
| POST | `/cos/health/check` | Run health check |
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index cc2f0c5648..96de327952 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -242,6 +242,16 @@ router.get('/tasks/internal', asyncHandler(async (req, res) => {
res.json(tasks);
}));
+// GET /api/cos/tasks/:id - One task with the queue it lives in. The Chief of
+// Staff page reads this when a selection lands outside the lists it already
+// holds, instead of re-reading the whole queue per click (#12032). Registered
+// after the literal /tasks/user and /tasks/internal routes so those still win.
+router.get('/tasks/:id', asyncHandler(async (req, res) => {
+ const found = await cos.findTaskWithSource(req.params.id);
+ if (!found) throw new ServerError('Task not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(found);
+}));
+
// POST /api/cos/tasks/refresh - Force refresh tasks
router.post('/tasks/refresh', asyncHandler(async (req, res) => {
const tasks = await taskWatcher.refreshTasks();
diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.js
index d54eb44c58..ef86b678c2 100644
--- a/server/routes/cosTaskRoutes.test.js
+++ b/server/routes/cosTaskRoutes.test.js
@@ -49,6 +49,7 @@ vi.mock('../services/cos.js', () => ({
getUserTasks: vi.fn(),
getCosTasks: vi.fn(),
getTaskById: vi.fn(),
+ findTaskWithSource: vi.fn(),
deleteTask: vi.fn(),
reorderTasks: vi.fn(),
approveTask: vi.fn(),
@@ -146,6 +147,32 @@ describe('CoS task collection selectors', () => {
});
});
+describe('GET /api/cos/tasks/:id', () => {
+ it('returns the task as stored with its source queue', async () => {
+ const task = { id: 'task-old', description: 'Example archived task', status: 'completed', taskType: 'documentation' };
+ cos.findTaskWithSource.mockResolvedValue({ task, source: 'user' });
+
+ const res = await request(buildApp()).get('/api/cos/tasks/task-old');
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ task, source: 'user' });
+ expect(cos.findTaskWithSource).toHaveBeenCalledWith('task-old');
+ });
+
+ it('is a 404 for an unknown id and never shadows the literal list routes', async () => {
+ cos.findTaskWithSource.mockResolvedValue(null);
+ cos.getUserTasks.mockResolvedValue({ tasks: [] });
+
+ const missing = await request(buildApp()).get('/api/cos/tasks/no-such-task');
+ expect(missing.status).toBe(404);
+ expect(missing.body.code).toBe('NOT_FOUND');
+
+ const list = await request(buildApp()).get('/api/cos/tasks/user');
+ expect(list.status).toBe(200);
+ expect(cos.findTaskWithSource).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('CoS task responses after action-ledger failures', () => {
it.each(['post', 'delete'])('keeps a committed %s successful when the ledger cannot write', async (method) => {
const ledgerPath = join(tempRoot, 'user-action-events.json');
diff --git a/server/services/cos.js b/server/services/cos.js
index ff828a078f..d36fd02d0b 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -93,9 +93,9 @@ export { runHealthCheck, getHealthStatus };
// backward compat with `import * as cos` and the cos route handlers. The store
// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /
// dequeueNextTask so the spawn-side logic stays here, not in the store.
-import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';
+import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, findTaskWithSource, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';
export { getPendingTaskIds } from './cosTaskStore.js';
-export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };
+export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, findTaskWithSource, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };
import { ensureInstanceId } from './instanceIdentity.js';
import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';
import { retryTasksResolvedByInvestigation } from './investigationRetry.js';
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index acef90301a..8632cf38c9 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -444,19 +444,31 @@ export const getTasks = getUserTasks;
/**
* Get a specific task by ID from any task source
*/
-export async function getTaskById(taskId) {
+/**
+ * One task and the queue it lives in: `{ task, source: 'user' | 'internal' }`,
+ * or null. The record is returned as stored (its own `taskType` intact), which
+ * is what a client merging it into a list it already holds needs.
+ */
+export async function findTaskWithSource(taskId) {
const { config } = await loadState();
// Keep user-first precedence, including legacy/custom IDs. Do not infer the
// source from a prefix or prepare grouped copies of both queues for one ID.
const userTask = await findTaskInFile(join(ROOT_DIR, config.userTasksFile), taskId);
- if (userTask) return { ...userTask, taskType: 'user' };
+ if (userTask) return { task: userTask, source: 'user' };
const cosTask = await findTaskInFile(join(ROOT_DIR, config.cosTasksFile), taskId);
- if (cosTask) return { ...cosTask, taskType: 'internal' };
+ if (cosTask) return { task: cosTask, source: 'internal' };
return null;
}
+// Legacy shape: the source overwrites the record's `taskType`. Callers that
+// need the record as stored use findTaskWithSource.
+export async function getTaskById(taskId) {
+ const found = await findTaskWithSource(taskId);
+ return found ? { ...found.task, taskType: found.source } : null;
+}
+
/**
* Add a new task to the user or internal queue.
*