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
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { fireEvent, render, screen, waitFor, act, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
vi.mock('../../../hooks/useAssignableInstances', () => ({ default: () => ({ instances: [], isFederated: false }) }));
const api = vi.hoisted(() => ({
getCosTasks: vi.fn(),
getCosLearningDurations: vi.fn(),
}));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
vi.mock('../../../services/api', () => api);
vi.mock('../../ui/Toast', () => ({ default: toast }));
// TaskAddForm pulls in provider/model plumbing not under test — stub it out.
vi.mock('./AgentCard', () => ({ default: ({ agent, liveOutput }) => <div>Active agent {agent.id}{liveOutput?.map((entry, i) => <p key={i}>{entry.line}</p>)}</div> }));
vi.mock('../TaskAddForm', () => ({ default: () => null }));
const TasksTab = (await import('./TasksTab')).default;
const emptyTasks = { user: { tasks: [] }, cos: { tasks: [] } };
const renderTab = (props = {}, route = '/cos/tasks') => render(
<MemoryRouter initialEntries={[route]}>
<TasksTab tasks={emptyTasks} onRefresh={vi.fn()} providers={[]} apps={[]} {...props} />
</MemoryRouter>,
);
beforeEach(() => {
vi.clearAllMocks();
api.getCosLearningDurations.mockResolvedValue(null);
});
it('opens and focuses the task identified by the queue deep link', async () => {
const task = { id: 'task-example', description: 'Review an example task', status: 'completed', metadata: {} };
renderTab({ tasks: { user: { tasks: [task] }, cos: { tasks: [] } } }, '/cos/tasks?task=task-example&source=user');
await waitFor(() => expect(document.getElementById('cos-task-user-task-example')).not.toBeNull());
const row = document.getElementById('cos-task-user-task-example');
expect(row).toHaveAttribute('aria-current', 'true');
expect(row).toHaveFocus();
});
// The server registers an agent as `running` BEFORE it flips the agent's task
// off `pending`, so between those two writes a task legitimately reads as
// pending on one list and running on the other. The tab must settle that from
// the agent list rather than rendering the task in both sections at once.
describe('TasksTab spawning window', () => {
const pendingTask = (id, extra = {}) => ({ id, description: `Task ${id}`, status: 'pending', metadata: {}, ...extra });
// `startedAt` is how the settlement tells a live spawn from a zombie record —
// registerAgent always stamps it. See server/lib/cosSpawnWindow.js.
const liveAgent = (id, taskId, ageMs = 0) => ({ id, status: 'running', taskId, startedAt: new Date(Date.now() - ageMs).toISOString() });
it('separates cleanup-held user and system tasks from running work', async () => {
const heldTask = id => ({ id, description: `Finalize ${id}`, status: 'in_progress',
metadata: { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: `agent-${id}` } });
renderTab({
tasks: { user: { tasks: [heldTask('task-example')] }, cos: { tasks: [heldTask('sys-rl-example')] } },
agents: [{ id: 'agent-sys-rl-example', taskId: 'sys-rl-example', status: 'completed' }],
});
const user = await screen.findByRole('region', { name: 'User tasks finalizing delivery' });
const system = screen.getByRole('region', { name: 'System tasks finalizing delivery' });
expect(within(user).getByText('Finalize task-example')).toBeInTheDocument();
expect(within(system).getByText('Finalize sys-rl-example')).toBeInTheDocument();
expect(within(system).getByRole('button', { name: /Status: finalizing/ })).toBeInTheDocument();
expect(screen.queryByText(/^Active \(/)).toBeNull();
expect(screen.queryByText(/^Active agent /)).toBeNull();
});
it('keeps an actual running agent active even if an old cleanup marker remains', async () => {
renderTab({
tasks: { user: { tasks: [] }, cos: { tasks: [{ ...pendingTask('sys-running'), status: 'in_progress',
metadata: { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: 'agent-older' } }] } },
agents: [liveAgent('agent-current', 'sys-running')],
});
expect(await screen.findByText('Active (1)')).toBeInTheDocument();
expect(screen.getByText('Active agent agent-current')).toBeInTheDocument();
expect(screen.queryByRole('region', { name: /finalizing delivery/ })).toBeNull();
});
it('shows the exact cleanup owner, last check and retry gate, and animates only live recovery', async () => {
const task = { id: 'task-held', description: 'Deliver example change', status: 'in_progress',
metadata: { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: 'agent-owner' } };
const owner = { id: 'agent-owner', taskId: task.id, status: 'completed', metadata: {
repoStateVerification: { checkedAt: '2026-01-01T12:00:00Z', reasons: ['cleanup-already-warned'] },
cleanupOutcome: { status: 'blocked', reason: 'preservation-unverified', taskId: 'task-recovery' },
}, result: { taskOutcome: { reason: 'The archive still needs verification.' } } };
const view = activity => <MemoryRouter><TasksTab tasks={{ user: { tasks: [task] }, cos: { tasks: [] } }}
agents={[{ ...owner, deliveryActivity: activity }, { id: 'agent-other', taskId: task.id, status: 'completed' }]}
completionRecovery={{ blockedReason: 'CoS is paused', nextRunAt: null, intervalMs: 1800000, batchSize: 10 }}
onRefresh={vi.fn()} providers={[]} apps={[]} /></MemoryRouter>;
const { rerender } = render(view(null));
expect(await screen.findByText(/Automatic recovery is waiting: CoS is paused/)).toBeInTheDocument();
expect(screen.getByText(/Waiting for delivery recovery — agent is not running/)).toBeInTheDocument();
expect(screen.getByText('Last check: preservation unverified.')).toBeInTheDocument();
expect(screen.getByText(/Last checked:/)).toBeInTheDocument();
expect(screen.getByRole('link', { name: /View recovery task/ })).toHaveAttribute('href', '/cos/tasks?task=task-recovery');
expect(screen.getByRole('link', { name: /View agent report/ })).toHaveAttribute('href', '/cos/agents/agent-owner');
expect(screen.getByLabelText('Delivery activity').querySelector('.animate-spin')).toBeNull();
rerender(view({ label: 'Checking repository preservation' }));
expect(screen.getByText('Checking repository preservation')).toBeInTheDocument();
expect(screen.getByLabelText('Delivery activity').querySelector('.animate-spin')).not.toBeNull();
rerender(view(null));
expect(screen.getByText(/agent is not running/)).toBeInTheDocument();
expect(screen.getByLabelText('Delivery activity').querySelector('.animate-spin')).toBeNull();
});
it('moves a pending task with a live agent out of Pending and into Active', async () => {
renderTab({
tasks: { user: { tasks: [pendingTask('task-spawning'), pendingTask('task-waiting')] }, cos: { tasks: [] } },
agents: [liveAgent('agent-1', 'task-spawning')],
liveOutputs: { 'agent-1': [{ line: 'Implementing the change' }] },
});
await waitFor(() => expect(screen.getByText(/^Pending \(/)).toBeInTheDocument());
expect(screen.getByText('Pending (1)')).toBeInTheDocument();
expect(screen.getByText('Active (1)')).toBeInTheDocument();
expect(screen.getByText(/Active agent agent-1/)).toBeInTheDocument();
expect(screen.getByText('Implementing the change')).toBeInTheDocument();
});
it('leaves a pending system task pending when its agent has already completed', async () => {
renderTab({
tasks: { user: { tasks: [] }, cos: { tasks: [pendingTask('cos-task-1')] } },
agents: [{ id: 'agent-1', status: 'completed', taskId: 'cos-task-1' }],
});
await waitFor(() => expect(screen.getByText('Pending (1)')).toBeInTheDocument());
expect(screen.queryByText(/^Active \(/)).not.toBeInTheDocument();
});
it('hands the task back to Pending once its holder is too old to be mid-spawn', async () => {
// Past SPAWN_CLAIM_GRACE_MS a `running` agent on a `pending` task is a zombie,
// not a spawn in flight — and `forceSpawnTask` supersedes it on the same
// bound. Keeping it under Active would hide the stuck task in a section whose
// rows are presented as work already underway.
renderTab({
tasks: { user: { tasks: [pendingTask('task-stuck')] }, cos: { tasks: [] } },
agents: [liveAgent('agent-1', 'task-stuck', 10 * 60 * 1000)],
});
await waitFor(() => expect(screen.getByText('Pending (1)')).toBeInTheDocument());
expect(screen.queryByText(/^Active \(/)).not.toBeInTheDocument();
});
it('keeps Process now reachable for a task whose agent record is stuck running', async () => {
renderTab({
tasks: { user: { tasks: [pendingTask('task-spawning')] }, cos: { tasks: [] } },
agents: [liveAgent('agent-1', 'task-spawning')],
});
await waitFor(() => expect(screen.getByText('Active (1)')).toBeInTheDocument());
fireEvent.click(screen.getByText('Task details and actions'));
// An agent stuck at `running` (the zombie state cleanupZombieAgents clears)
// would otherwise leave the row with no way to re-dispatch it. Duplicate
// dispatch is refused server-side by forceSpawnTask, not by hiding this.
expect(screen.getByRole('button', { name: /Process task now/i })).toBeInTheDocument();
});
it('still offers Process now for a genuinely queued task', async () => {
renderTab({
tasks: { user: { tasks: [pendingTask('task-waiting')] }, cos: { tasks: [] } },
agents: [],
});
await waitFor(() => expect(screen.getByText('Pending (1)')).toBeInTheDocument());
expect(screen.getByRole('button', { name: /Process task now/i })).toBeInTheDocument();
});
});
it('focuses a deep link when its task arrives, then preserves user focus on refresh', async () => {
const task = { id: 'task-example', description: 'Review an example task', status: 'completed', metadata: {} };
const view = (tasks) => <MemoryRouter initialEntries={['/cos/tasks?task=task-example&source=user']}>
<input aria-label="Draft" />
<TasksTab tasks={tasks} onRefresh={vi.fn()} providers={[]} apps={[]} />
</MemoryRouter>;
const { rerender } = render(view(emptyTasks));
rerender(view({ user: { tasks: [task] }, cos: { tasks: [] } }));
await waitFor(() => expect(document.getElementById('cos-task-user-task-example')).toHaveFocus());
const draft = screen.getByRole('textbox', { name: 'Draft' });
draft.focus();
const row = document.getElementById('cos-task-user-task-example');
const scroll = vi.spyOn(row, 'scrollIntoView');
rerender(view({ user: { tasks: [{ ...task }] }, cos: { tasks: [] } }));
await waitFor(() => expect(draft).toHaveFocus());
expect(scroll).not.toHaveBeenCalled();
});
it('refreshes expanded history on completed changes without fetching it for queue heartbeats', async () => {
const completed = id => ({ id, description: `Completed ${id}`, status: 'completed', metadata: {} });
api.getCosTasks.mockResolvedValueOnce({ items: [completed('old')], total: 1, nextCursor: null })
.mockResolvedValueOnce({ items: [completed('new'), completed('old')], total: 2, nextCursor: null })
.mockResolvedValueOnce({ items: [completed('replacement')], total: 1, nextCursor: null });
const view = (count, revision = 0) => <MemoryRouter><TasksTab tasks={{ user: { tasks: [], completedCount: count }, cos: { tasks: [], completedCount: 0 } }} completedRevision={revision} onRefresh={vi.fn()} providers={[]} apps={[]} /></MemoryRouter>;
const { rerender } = render(view(1));
expect(api.getCosTasks).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Completed (1)' }));
await screen.findByText('Completed old');
rerender(view(1));
expect(api.getCosTasks).toHaveBeenCalledTimes(1);
rerender(view(2));
await screen.findByText('Completed new');
rerender(view(1, 1));
await screen.findByText('Completed replacement');
expect(screen.queryByText('Completed old')).not.toBeInTheDocument();
expect(api.getCosTasks).toHaveBeenCalledTimes(3);
});
it('displays loading spinners while tasks are loading instead of empty messages', async () => {
renderTab({ tasks: { user: null, cos: null } });
await act(async () => {});
expect(screen.queryByText('No user tasks. Add one above or edit TASKS.md directly.')).not.toBeInTheDocument();
expect(screen.queryByText('No system tasks.')).not.toBeInTheDocument();
expect(screen.queryByText(/0 pending · 0 active · 0 blocked/)).not.toBeInTheDocument();
expect(screen.getAllByLabelText('Loading task queue…').length).toBeGreaterThanOrEqual(1);
expect(screen.getByLabelText('Loading system tasks…')).toBeInTheDocument();
});