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

feat: stream maintenance progress with active agent notifications

[._.]/ Adam Eivya85e87ab385c
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 6fa6174d2b..e07ad82f9b 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -309,6 +309,7 @@ export default function App() {
<Route path="cos" element={<Navigate to="/cos/tasks" replace />} />
<Route path="cos/mind/tools" element={<Navigate to="/cos/mind?panel=tools" replace />} />
<Route path="cos/tools" element={<Navigate to="/cos/mind?panel=tools" replace />} />
+ <Route path="cos/:tab/:agentId" element={<ChiefOfStaff />} />
<Route path="cos/:tab" element={<ChiefOfStaff />} />
<Route path="calendar" element={<Navigate to="/calendar/agenda" replace />} />
<Route path="calendar/:tab" element={<CalendarPage />} />
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 9d5679b7d9..84d1bf96d6 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -214,8 +214,8 @@ function GoalFidelityPanel({ review }) {
);
}
-export default function AgentCard({ agent, onPause, onKill, onDelete, onResume, onRelaunch, completed, paused = false, liveOutput, durations, onFeedbackChange, remote, peerName }) {
- const [expanded, setExpanded] = useState(false);
+export default function AgentCard({ agent, onPause, onKill, onDelete, onResume, onRelaunch, completed, paused = false, liveOutput, durations, onFeedbackChange, remote, peerName, initiallyExpanded = false }) {
+ const [expanded, setExpanded] = useState(initiallyExpanded);
const [now, setNow] = useState(Date.now());
const [fullOutput, setFullOutput] = useState(null);
const [loadingOutput, setLoadingOutput] = useState(false);
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index d3c1ed0228..40256b19f7 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo, useCallback } from 'react';
-import { useSearchParams } from 'react-router';
+import { useParams, useSearchParams } from 'react-router';
import { Trash2, Search, X, ChevronDown, MessageSquare } from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
@@ -40,6 +40,18 @@ const needsAgentFeedback = (agent) => {
};
export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, providersLoaded, apps }) {
+ const { agentId } = useParams();
+ const [focusedAgent, setFocusedAgent] = useState(null);
+ const [focusLoading, setFocusLoading] = useState(false);
+ useEffect(() => {
+ if (!agentId) return;
+ let cancelled = false;
+ setFocusedAgent(null);
+ setFocusLoading(true);
+ api.getCosAgent(agentId, { silent: true }).then(agent => { if (!cancelled) setFocusedAgent(agent); })
+ .catch(() => {}).finally(() => { if (!cancelled) setFocusLoading(false); });
+ return () => { cancelled = true; };
+ }, [agentId]);
const [searchParams, setSearchParams] = useSearchParams();
const [resumingAgent, setResumingAgent] = useState(null);
const [relaunchingAgent, setRelaunchingAgent] = useState(null);
@@ -241,6 +253,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
[allCompleted]
);
+ const selectedAgent = agents.find(agent => agent.id === agentId) || (focusedAgent?.id === agentId ? focusedAgent : null);
const hasMoreDates = dateBuckets.some(d => !loadedDates.has(d.date));
const remainingCount = dateBuckets
.filter(d => !loadedDates.has(d.date))
@@ -248,6 +261,14 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, p
return (
<div className="space-y-6">
+ {agentId && <section aria-label="Selected agent" className="space-y-2">
+ <h3 className="text-lg font-semibold">Selected agent</h3>
+ {selectedAgent ? <AgentCard key={agentId} agent={selectedAgent}
+ initiallyExpanded liveOutput={liveOutputs[agentId]} completed={selectedAgent.status === 'completed'}
+ paused={selectedAgent.status === 'paused'} durations={durations} onFeedbackChange={handleFeedbackChange}
+ onPause={handlePause} onKill={handleKill} onResume={handleResumeClick} onDelete={handleDelete} onRelaunch={handleRelaunchClick} />
+ : <p role="status">{focusLoading ? 'Loading agent…' : 'Agent not found or unavailable.'}</p>}
+ </section>}
{/* Active Agents */}
<div>
<div className="flex items-center justify-between mb-3">
diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsx
index 80e3efc9e4..71d9e68b33 100644
--- a/client/src/components/cos/tabs/AgentsTab.test.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.test.jsx
@@ -2,10 +2,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { act } from 'react';
-import { MemoryRouter } from 'react-router';
+import { MemoryRouter, Routes, Route } from 'react-router';
vi.mock('../../../services/api', () => ({
getCosLearningDurations: vi.fn(),
+ getCosAgent: vi.fn(),
getCosAgentDates: vi.fn(),
getCosAgentsByDate: vi.fn(),
clearCompletedCosAgents: vi.fn(),
@@ -332,3 +333,12 @@ describe('AgentsTab feedback review queue', () => {
expect(onRefresh).toHaveBeenCalledTimes(1);
});
});
+
+it('opens an agent deep link even after it has left the recent agent list', async () => {
+ api.getCosAgent.mockResolvedValue({ id: 'archived-example', status: 'completed', metadata: { taskDescription: 'Example maintenance audit' } });
+ render(<MemoryRouter initialEntries={['/cos/agents/archived-example']}><Routes>
+ <Route path="/cos/:tab/:agentId" element={<AgentsTab agents={[]} onRefresh={vi.fn()} liveOutputs={{}} providers={[]} apps={[]} />} />
+ </Routes></MemoryRouter>);
+ expect(await screen.findByTestId('agent-archived-example')).toBeInTheDocument();
+ expect(api.getCosAgent).toHaveBeenCalledWith('archived-example', { silent: true });
+});
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
index fb428a2991..48296dae41 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
@@ -1,5 +1,7 @@
-import { useCallback, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { Link } from 'react-router';
+import socket from '../../../../services/socket';
+import MaintenanceRunStatus from './MaintenanceRunStatus';
import ProviderModelSelector from '../../../ProviderModelSelector';
import * as api from '../../../../services/api';
import { useAutoRefetch } from '../../../../hooks/useAutoRefetch';
@@ -11,15 +13,6 @@ import { familyForProvider } from '../../../../../../server/lib/providerFamilies
const RUNS_POLL_MS = 15_000;
const FINISHED_RUNS_SHOWN = 3;
-/** Step progress as the user reads it: audits and drains done, out of the ladder. */
-const progressOf = run => ({ done: Object.keys(run.completed || {}).length, total: run.steps?.length || 0 });
-
-const currentStepOf = run => {
- if (run.active?.taskType) return run.active.taskType;
- const next = (run.steps || []).find(step => !run.completed?.[step.id]);
- return next?.taskRef?.taskType || null;
-};
-
export default function MaintenanceRunForm({ schedule, apps = [], providers = [], providersLoaded, improvementDisabled, daemonRunning, onRefresh }) {
const [appId, setAppId] = useState('');
const [providerId, setProviderId] = useState('');
@@ -32,6 +25,7 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
// `null` = not read yet, `[]` = read and empty — the first read must happen
// even when there is nothing to show.
const [runs, setRuns] = useState(null);
+ const revision = useRef(0);
const availableProviders = providers.filter(provider => provider.enabled && isProcessProvider(provider) && familyForProvider(provider));
const provider = availableProviders.find(entry => entry.id === providerId);
const groups = buildQuotaBurnTaskCatalog({ schedule, apps });
@@ -40,16 +34,36 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
const blocked = improvementDisabled || daemonRunning === false;
const fetchRuns = useCallback(async () => {
+ const requestedRevision = revision.current;
const response = await api.getMaintenanceRuns({ silent: true }).catch(() => null);
// A failed read stays `null` so the poll keeps trying; only a real answer
// settles the list.
- if (response) setRuns(response.runs || []);
+ if (response && requestedRevision === revision.current) setRuns(response.runs || []);
}, []);
const anyRunning = (runs || []).some(run => run.status === 'running');
// One read on mount, then polling only while a run is in flight — an idle
// form costs nothing, and a start/resume already holds the fresh record.
const { refetch: refreshRuns } = useAutoRefetch(fetchRuns, RUNS_POLL_MS, { pollOnly: true, enabled: runs === null || anyRunning, immediate: runs === null });
+ useEffect(() => {
+ const subscribe = () => { socket.emit('cos:subscribe'); fetchRuns(); };
+ const update = updated => {
+ revision.current += 1;
+ setRuns(current => {
+ const previous = (current || []).find(entry => entry.id === updated.id);
+ if (previous?.updatedAt > updated.updatedAt) return current;
+ return [updated, ...(current || []).filter(entry => entry.id !== updated.id)];
+ });
+ };
+ socket.on('cos:maintenance:updated', update);
+ socket.on('connect', subscribe);
+ socket.emit('cos:subscribe');
+ return () => {
+ socket.off('cos:maintenance:updated', update);
+ socket.off('connect', subscribe);
+ };
+ }, [fetchRuns]);
+
const prepare = async () => {
if (busy || !onRefresh || !prerequisites.length || prerequisites.some(item => item.unavailable)) return;
setBusy(true);
@@ -95,6 +109,7 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
return null;
});
if (response?.run) {
+ revision.current += 1;
setRuns(current => [response.run, ...(current || []).filter(entry => entry.id !== response.run.id)]);
setMessage(describe(response.result));
setConsent(false);
@@ -104,6 +119,7 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
const applyRun = (updated, result) => {
if (!updated) return;
+ revision.current += 1;
setRuns(current => (current || []).map(entry => (entry.id === updated.id ? updated : entry)));
if (result) setMessage(describe(result));
};
@@ -180,13 +196,10 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
{message && <p role="status">{message}</p>}
{visibleRuns.length > 0 && <ul aria-label="Maintenance runs" className="space-y-2">
{visibleRuns.map(entry => {
- const { done, total } = progressOf(entry);
- const step = currentStepOf(entry);
return <li key={entry.id} className="border border-port-border rounded p-2 flex flex-wrap items-center gap-x-3 gap-y-1">
<span className="font-medium">{getAppName(entry.appId, apps, entry.appId)}</span>
<span className="text-xs">{entry.providerId}{entry.model ? ` · ${entry.model}` : ''}</span>
- <span className="text-xs">{entry.status} · {done}/{total} steps{entry.status === 'running' && step ? ` · ${step}` : ''}</span>
- {entry.reason && <span className="text-xs basis-full">{entry.reason}</span>}
+ <MaintenanceRunStatus run={entry} />
{entry.status === 'running'
? <button type="button" onClick={() => stop(entry.id)} className="px-2 py-1 text-xs bg-port-border rounded">Stop</button>
: entry.status === 'stopped' && <button type="button" onClick={() => resume(entry.id)} className="px-2 py-1 text-xs bg-port-border rounded">Resume</button>}
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
index 7b2b142c01..facb1076f5 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
@@ -1,12 +1,14 @@
import { useState } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router';
import { MAINTENANCE_TASK_ORDER } from '../../../../lib/quotaBurnTasks';
import { MAINTENANCE_SEQUENCE_TYPES } from '../../../../../../server/lib/maintenanceSequence';
import MaintenanceRunForm from './MaintenanceRunForm';
+const socket = vi.hoisted(() => ({ on: vi.fn(), off: vi.fn(), emit: vi.fn() }));
+vi.mock('../../../../services/socket', () => ({ default: socket }));
const api = vi.hoisted(() => ({
getMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn(), resumeMaintenanceRun: vi.fn(),
updateCosTaskInterval: vi.fn(), updateAppTaskTypeOverride: vi.fn(),
@@ -145,3 +147,30 @@ it('refreshes partial setup after failure without starting work', async () => {
expect(screen.getByRole('button', { name: 'Run now' })).toBeDisabled();
expect(api.startMaintenanceRun).not.toHaveBeenCalled();
});
+
+it('streams agent activity and completed steps, and removes listeners on unmount', async () => {
+ api.getMaintenanceRuns.mockResolvedValue({ runs: [runRecord({ completed: {} })] });
+ const view = show();
+ await screen.findByRole('list', { name: 'Maintenance runs' });
+ const update = socket.on.mock.calls.find(([name]) => name === 'cos:maintenance:updated')[1];
+ act(() => update(runRecord({ completed: {}, active: { taskType: 'better-structural-drift', status: 'running', agentId: 'agent-example' } })));
+ expect(screen.getByRole('link', { name: 'Open agent in new tab' })).toHaveAttribute('href', '/cos/agents/agent-example');
+ expect(screen.getByRole('link', { name: 'Open agent in new tab' })).toHaveAttribute('target', '_blank');
+ act(() => update(runRecord()));
+ expect(screen.getByRole('progressbar')).toHaveAttribute('value', '1');
+ view.unmount();
+ expect(socket.off).toHaveBeenCalledWith('cos:maintenance:updated', update);
+});
+
+it('keeps a newer live update when an older initial fetch resolves late, and refreshes on reconnect', async () => {
+ let resolveRead;
+ api.getMaintenanceRuns.mockReturnValueOnce(new Promise(resolve => { resolveRead = resolve; }));
+ show();
+ const update = socket.on.mock.calls.find(([name]) => name === 'cos:maintenance:updated')[1];
+ act(() => update(runRecord()));
+ await act(async () => resolveRead({ runs: [runRecord({ completed: {} })] }));
+ expect(screen.getByRole('progressbar')).toHaveAttribute('value', '1');
+ api.getMaintenanceRuns.mockResolvedValue({ runs: [runRecord({ status: 'completed', active: null })] });
+ await act(async () => socket.on.mock.calls.find(([name]) => name === 'connect')[1]());
+ expect(screen.getByText(/completed · 1\/13 steps/)).toBeInTheDocument();
+});
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
new file mode 100644
index 0000000000..b3161abc55
--- /dev/null
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunStatus.jsx
@@ -0,0 +1,16 @@
+/** Shared live progress content for the schedule card and corner notification. */
+export default function MaintenanceRunStatus({ run }) {
+ const done = Object.keys(run.completed || {}).length;
+ const total = run.steps?.length || 0;
+ const step = run.active?.taskType || run.steps?.find(entry => !run.completed?.[entry.id])?.taskRef?.taskType;
+ return <div className="space-y-1 text-xs" role="status">
+ <p>{run.status} · {done}/{total} steps{run.status === 'running' && step ? ` · ${step}` : ''}</p>
+ <progress aria-label="Maintenance steps completed" value={done} max={total || 1} className="w-full h-1 accent-port-accent" />
+ {run.active && <p className="flex items-center gap-2">
+ {run.active.status === 'running' && <span aria-hidden="true" className="w-2 h-2 rounded-full bg-port-accent motion-safe:animate-pulse" />}
+ {run.active.status || 'queued'}
+ {run.active.agentId && <a className="underline" href={`/cos/agents/${encodeURIComponent(run.active.agentId)}`} target="_blank" rel="noopener noreferrer">Open agent in new tab</a>}
+ </p>}
+ {run.reason && <p>{run.reason}</p>}
+ </div>;
+}
diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.js
index 16451448cc..2f1b1576e6 100644
--- a/client/src/hooks/useOnDemandTaskToast.js
+++ b/client/src/hooks/useOnDemandTaskToast.js
@@ -1,4 +1,5 @@
-import { useEffect } from 'react';
+import { createElement, useEffect } from 'react';
+import MaintenanceRunStatus from '../components/cos/tabs/schedule/MaintenanceRunStatus';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
import { timeUntil } from '../utils/formatters';
@@ -45,7 +46,22 @@ const PR_REVIEWER_REASON_LABELS = {
*/
export function useOnDemandTaskToast() {
useEffect(() => {
- socket.emit('cos:subscribe');
+ const subscribe = () => socket.emit('cos:subscribe');
+ subscribe();
+ socket.on('connect', subscribe);
+ const maintenanceStates = new Map();
+ const handleMaintenance = run => {
+ const label = `Maintenance · ${Object.keys(run.completed || {}).length}/${run.steps?.length || 0} · ${run.status}`;
+ const signature = JSON.stringify([run.status, run.completed, run.active, run.reason]);
+ if (maintenanceStates.get(run.id) === signature) return;
+ maintenanceStates.set(run.id, signature);
+ if (maintenanceStates.size > 100) maintenanceStates.delete(maintenanceStates.keys().next().value);
+ if (run.status !== 'running') toast.dismiss(`maintenance-${run.id}`);
+ toast(() => createElement(MaintenanceRunStatus, { run }), {
+ id: run.status === 'running' ? `maintenance-${run.id}` : `maintenance-${run.id}-${run.updatedAt}`, label, duration: run.status === 'running' ? Infinity : 8000,
+ });
+ };
+ socket.on('cos:maintenance:updated', handleMaintenance);
const handleEmpty = (data) => {
const task = data?.taskType || 'task';
@@ -146,6 +162,8 @@ export function useOnDemandTaskToast() {
socket.on('cos:schedule:on-demand-empty', handleEmpty);
socket.on('cos:schedule:on-demand-handled', handleHandled);
return () => {
+ socket.off('connect', subscribe);
+ socket.off('cos:maintenance:updated', handleMaintenance);
socket.off('cos:schedule:on-demand-empty', handleEmpty);
socket.off('cos:schedule:on-demand-handled', handleHandled);
// Don't unsubscribe from cos — other components share the room.
diff --git a/client/src/hooks/useOnDemandTaskToast.test.jsx b/client/src/hooks/useOnDemandTaskToast.test.jsx
index f144532c6f..bc2ff3dc25 100644
--- a/client/src/hooks/useOnDemandTaskToast.test.jsx
+++ b/client/src/hooks/useOnDemandTaskToast.test.jsx
@@ -13,7 +13,7 @@ vi.mock('../services/socket', () => ({
}));
const toastSpy = vi.fn();
-vi.mock('../components/ui/Toast', () => ({ default: (...a) => toastSpy(...a) }));
+vi.mock('../components/ui/Toast', () => ({ default: Object.assign((...a) => toastSpy(...a), { dismiss: vi.fn() }) }));
const { useOnDemandTaskToast } = await import('./useOnDemandTaskToast.js');
const fire = (payload) => handlers.get('cos:schedule:on-demand-empty')?.(payload);
@@ -225,3 +225,19 @@ describe('useOnDemandTaskToast — programmatic handler results', () => {
expect(opts.icon).toBe('💤');
});
});
+
+it('updates one maintenance notification with an agent link and expires terminal progress', () => {
+ toastSpy.mockClear();
+ const { unmount } = renderHook(() => useOnDemandTaskToast());
+ const update = handlers.get('cos:maintenance:updated');
+ const run = { id: 'maint-example', status: 'running', completed: {}, steps: [{ id: 'step-1' }], active: { agentId: 'agent-example', status: 'running' } };
+ update(run);
+ update(run);
+ expect(toastSpy).toHaveBeenCalledTimes(1);
+ expect(toastSpy.mock.calls[0][1]).toMatchObject({ id: 'maintenance-maint-example', duration: Infinity });
+ expect(toastSpy.mock.calls[0][0]().props.run.active.agentId).toBe('agent-example');
+ update({ ...run, status: 'completed', active: null, completed: { 'step-1': 'done' }, updatedAt: 'finished' });
+ expect(toastSpy.mock.calls[1][1]).toMatchObject({ duration: 8000, label: 'Maintenance · 1/1 · completed' });
+ unmount();
+ expect(handlers.has('cos:maintenance:updated')).toBe(false);
+});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 0d07a70392..34d60919f2 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -185,7 +185,7 @@ export const forceHealthCheck = (options = {}) => request('/cos/health/check', {
export const getCosAgents = (options) => request('/cos/agents', options);
export const getCosAgentDates = () => request('/cos/agents/history');
export const getCosAgentsByDate = (date) => request(`/cos/agents/history/${date}`);
-export const getCosAgent = (id) => request(`/cos/agents/${id}`);
+export const getCosAgent = (id, options) => request(`/cos/agents/${id}`, options);
export const pauseCosAgent = (id, reason, options = {}) => request(`/cos/agents/${id}/pause`, {
method: 'POST',
body: JSON.stringify({ reason }),
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index f3a98c4d30..a8c98c6b75 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -91,6 +91,7 @@ async function writeRuns(runs) {
const insertRun = (run) => writeQueue(async () => {
await writeRuns([run, ...(await listMaintenanceRuns())]);
+ cosEvents.emit('maintenance:updated', run);
return run;
});
@@ -113,6 +114,7 @@ const patchRun = (id, patch) => writeQueue(async () => {
updatedAt: new Date().toISOString(),
};
await writeRuns(runs.map((entry) => (entry.id === id ? updated : entry)));
+ cosEvents.emit('maintenance:updated', updated);
return updated;
});
@@ -231,7 +233,14 @@ async function evaluate(id, { ignoreTaskId }) {
const { user, cos } = await getAllTasks();
const ownTask = [...(user?.tasks || []), ...(cos?.tasks || [])].find((task) => task.id !== ignoreTaskId
&& quotaBurnProvenance(task.metadata).maintenanceRunId === id && ACTIVE_TASK_STATUSES.has(task.status));
- if (ownTask) return hold(`waiting for ${ownTask.status.replace('_', ' ')} task ${ownTask.id}`);
+ if (ownTask) {
+ const { loadState } = await import('./cosState.js');
+ const state = await loadState();
+ const agent = Object.values(state.agents || {}).find(entry => entry.taskId === ownTask.id && entry.status === 'running');
+ return hold(`waiting for ${ownTask.status.replace('_', ' ')} task ${ownTask.id}`, {
+ active: { ...run.active, taskId: ownTask.id, agentId: agent?.id || run.active?.agentId || null, status: ownTask.status },
+ });
+ }
const queued = (await getOnDemandRequests()).find((request) => request?.burn?.maintenanceRunId === id);
if (queued) return hold(`waiting for the CoS daemon to accept request ${queued.id} (${queued.taskType})`);
@@ -255,7 +264,7 @@ async function evaluate(id, { ignoreTaskId }) {
await patchRun(id, {
completed,
reason: null,
- active: { stepId: step.id, taskType, requestId: result.awaiting?.requestId ?? null, at: new Date().toISOString() },
+ active: { stepId: step.id, taskType, status: 'queued', requestId: result.awaiting?.requestId ?? null, at: new Date().toISOString() },
});
console.log(`🧹 Maintenance run ${id}: dispatched ${taskType} (${step.id})`);
return { dispatched: true, stepId: step.id, taskType, summary: result.summary };
@@ -289,6 +298,19 @@ function onMaintenanceAgentCompleted(agent) {
.catch((err) => console.error(`❌ Maintenance run ${id} continuation failed: ${err.message}`));
}
+function onMaintenanceAgentSpawned(agent) {
+ const id = agent?.metadata?.taskQuotaBurnMaintenanceRunId;
+ if (!id) return;
+ return perRun(id, async () => {
+ const run = await getMaintenanceRun(id);
+ if (!run) return;
+ await patchRun(id, {
+ active: { ...run.active, stepId: agent.metadata.taskQuotaBurnStepId, agentId: agent.id, taskId: agent.taskId, status: 'running' },
+ reason: run.status === MAINTENANCE_RUN_STATUS.RUNNING ? null : run.reason,
+ });
+ }).catch(err => console.error(`❌ Maintenance agent status update failed: ${err.message}`));
+}
+
async function retryRunningRuns() {
const running = (await listMaintenanceRuns()).filter((run) => run.status === MAINTENANCE_RUN_STATUS.RUNNING);
for (const run of running) {
@@ -302,6 +324,7 @@ export function startMaintenanceRunScheduler() {
// Both run outside the request lifecycle: the listener never rethrows and the
// timer's callback owns its rejections, so neither can take the process down.
cosEvents.on('agent:completed', onMaintenanceAgentCompleted);
+ cosEvents.on('agent:spawned', onMaintenanceAgentSpawned);
retryTimer = setInterval(() => {
retryRunningRuns().catch((err) => console.error(`❌ Maintenance run retry sweep failed: ${err.message}`));
}, RETRY_MS);
@@ -310,11 +333,13 @@ export function startMaintenanceRunScheduler() {
}
/** Test seams. */
+export const __onMaintenanceAgentSpawned = onMaintenanceAgentSpawned;
export const __onMaintenanceAgentCompleted = onMaintenanceAgentCompleted;
export const __retryMaintenanceRuns = retryRunningRuns;
export function __resetMaintenanceRunScheduler() {
if (retryTimer) clearInterval(retryTimer);
retryTimer = null;
cosEvents.off('agent:completed', onMaintenanceAgentCompleted);
+ cosEvents.off('agent:spawned', onMaintenanceAgentSpawned);
perRun.clear();
}
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
index 279a1a965a..9f0470dda7 100644
--- a/server/services/maintenanceRun.test.js
+++ b/server/services/maintenanceRun.test.js
@@ -8,6 +8,7 @@ const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-mai
vi.mock('../lib/fileUtils.js', async () => makeProxy(await vi.importActual('../lib/fileUtils.js')));
const state = vi.hoisted(() => ({ tasks: [], requests: [], invoked: [], dispatch: null, probe: null }));
+vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => ({ agents: {} })) }));
vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ cos: { tasks: state.tasks }, user: { tasks: [] } })) }));
vi.mock('./taskSchedule.js', () => ({ getOnDemandRequests: vi.fn(async () => state.requests) }));
vi.mock('./apps.js', () => ({ getAppById: vi.fn(async (id) => (id === 'app-1' ? { id, name: 'Example App' } : null)) }));
@@ -31,7 +32,7 @@ const { getQuotaBurnConfig } = await import('./quotaBurnStore.js');
const { invokeQuotaBurnStep } = await import('./quotaBurnInvoke.js');
const {
startMaintenanceRun, stopMaintenanceRun, resumeMaintenanceRun, evaluateMaintenanceRun, getMaintenanceRun, listMaintenanceRuns,
- __onMaintenanceAgentCompleted, __retryMaintenanceRuns, __resetMaintenanceRunScheduler,
+ __onMaintenanceAgentSpawned, __onMaintenanceAgentCompleted, __retryMaintenanceRuns, __resetMaintenanceRunScheduler,
} = await import('./maintenanceRun.js');
const start = () => startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high' });
@@ -165,3 +166,21 @@ describe('manual maintenance run', () => {
expect(state.invoked).toEqual([]);
});
});
+
+// Regression: queued maintenance must identify its real agent immediately and
+// publish persisted transitions, without waiting for the retry sweep.
+it('publishes queued, running, and completed progress with the active agent link identity', async () => {
+ const { cosEvents } = await import('./cosEvents.js');
+ const updates = [];
+ const listener = run => updates.push(run);
+ cosEvents.on('maintenance:updated', listener);
+ const { run } = await start();
+ expect(updates.at(-1).active.status).toBe('queued');
+ await __onMaintenanceAgentSpawned({ ...agentFor(run, 0), id: 'agent-example' });
+ expect(await getMaintenanceRun(run.id)).toMatchObject({ active: { agentId: 'agent-example', status: 'running' } });
+ expect(updates.at(-1).active.agentId).toBe('agent-example');
+ await __onMaintenanceAgentCompleted(agentFor(run, 0));
+ expect(updates.at(-1).completed).toHaveProperty(run.steps[0].id);
+ expect(updates.at(-1).active).not.toHaveProperty('agentId');
+ cosEvents.off('maintenance:updated', listener);
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index 8920a2a02b..5c60b70f11 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -344,6 +344,8 @@ function setupCosEventForwarding() {
cosEvents.on('tasks:user:completed', (data) => broadcastToCos('cos:tasks:user:completed', data));
cosEvents.on('tasks:cos:changed', (data) => broadcastToCos('cos:tasks:cos:changed', data));
+ cosEvents.on('maintenance:updated', (data) => broadcastToCos('cos:maintenance:updated', data));
+
// Agent events
cosEvents.on('agent:spawned', (data) => broadcastToCos('cos:agent:spawned', data));
cosEvents.on('agent:updated', (data) => broadcastToCos('cos:agent:updated', data));