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, afterEach } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes, Link, useLocation } from 'react-router';
const socketHandlers = vi.hoisted(() => new Map());
vi.mock('../services/socket', () => ({
default: {
on: (event, fn) => { if (!socketHandlers.has(event)) socketHandlers.set(event, new Set()); socketHandlers.get(event).add(fn); },
off: (event, fn) => socketHandlers.get(event)?.delete(fn),
emit: vi.fn(),
},
}));
const fireSocket = async (event, payload) => act(async () => {
for (const fn of socketHandlers.get(event) || []) fn(payload);
});
vi.mock('../services/apiCreativeDirector.js', () => ({
getCreativeDirectorProject: vi.fn(),
getCreativeDirectorVideoExecution: vi.fn(async () => ({ canStart: false, blockers: ['Configure a provider'], choices: null, limits: { maxClips: 60, maxRetries: 1, maxReplans: 2, maxAgentCalls: 100, spendCapUsd: null }, execution: null })),
startCreativeDirectorVideoExecution: vi.fn(),
getCreativeDirectorSources: vi.fn(async () => ({ draft: [], artifact: [] })),
deleteCreativeDirectorProject: vi.fn(),
startCreativeDirectorProject: vi.fn(),
pauseCreativeDirectorProject: vi.fn(),
stopCreativeDirectorProject: vi.fn(),
resumeCreativeDirectorProject: vi.fn(),
}));
vi.mock('../services/apiAgents.js', () => ({ getCosAgents: vi.fn(() => Promise.resolve([])) }));
vi.mock('../hooks/useMediaJobProgress', () => ({ default: () => ({ status: 'unknown', error: null }) }));
vi.mock('../components/creative-director/OverviewTab.jsx', () => ({ default: () => <div>Overview content</div> }));
vi.mock('../components/creative-director/TreatmentTab.jsx', () => ({ default: () => null }));
vi.mock('../components/creative-director/SegmentsTab.jsx', () => ({ default: () => null }));
vi.mock('../components/creative-director/PlanTab.jsx', () => ({ default: () => null }));
vi.mock('../components/creative-director/RunsTab.jsx', () => ({ default: () => null }));
vi.mock('../components/creative-director/ActiveAgentsBanner.jsx', () => ({ default: ({ agents }) => <div data-testid="agents">{agents.map(a => a.id).join(',')}</div> }));
vi.mock('../components/creative-director/CreativeDirectorModelsDrawer.jsx', () => ({ default: () => null }));
vi.mock('../components/ui/Toast', () => ({
default: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() },
}));
import * as cdApi from '../services/apiCreativeDirector.js';
import { getCosAgents } from '../services/apiAgents.js';
import CreativeDirectorDetail from './CreativeDirectorDetail';
const PROJECT = {
id: 'cd-example',
name: 'Example project',
status: 'draft',
treatment: null,
};
function LocationProbe() {
const { pathname } = useLocation();
return <div data-testid="location">{pathname}</div>;
}
const renderPage = async () => {
render(
<MemoryRouter initialEntries={['/creative-director/cd-example/overview']}>
<LocationProbe />
<Routes>
<Route path="/creative-director/:id/:tab" element={<CreativeDirectorDetail />} />
</Routes>
</MemoryRouter>,
);
await screen.findByRole('heading', { name: PROJECT.name });
await act(async () => {});
};
describe('CreativeDirectorDetail project deletion', () => {
beforeEach(() => {
vi.clearAllMocks();
cdApi.getCreativeDirectorProject.mockResolvedValue(PROJECT);
cdApi.deleteCreativeDirectorProject.mockResolvedValue({ ok: true });
});
it('requires confirmation before deleting the project', async () => {
const user = userEvent.setup();
await renderPage();
await user.click(screen.getByRole('button', { name: `Delete project ${PROJECT.name}` }));
expect(cdApi.deleteCreativeDirectorProject).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: 'Delete', exact: true })).toBeTruthy();
expect(screen.getByRole('button', { name: 'Cancel' })).toBeTruthy();
});
it('deletes the project and returns to the Creative Director list', async () => {
const user = userEvent.setup();
await renderPage();
await user.click(screen.getByRole('button', { name: `Delete project ${PROJECT.name}` }));
await user.click(screen.getByRole('button', { name: 'Delete', exact: true }));
await waitFor(() => expect(cdApi.deleteCreativeDirectorProject).toHaveBeenCalledWith(PROJECT.id, { silent: true }));
expect(screen.getByTestId('location')).toHaveTextContent('/creative-director');
});
});
describe('CreativeDirectorDetail route isolation', () => {
beforeEach(() => {
vi.clearAllMocks();
getCosAgents.mockResolvedValue([]);
});
it('keeps B and its agents when A requests finish last, and deletes only confirmed B', async () => {
const user = userEvent.setup();
let resolveA;
let resolveAgentsA;
const pendingA = new Promise(resolve => { resolveA = resolve; });
const pendingAgentsA = new Promise(resolve => { resolveAgentsA = resolve; });
const projectB = { ...PROJECT, id: 'cd-other', name: 'Other project' };
cdApi.getCreativeDirectorProject.mockImplementation(id => id === PROJECT.id ? pendingA : Promise.resolve(projectB));
getCosAgents.mockReturnValue(pendingAgentsA);
render(
<MemoryRouter initialEntries={['/creative-director/cd-example/overview']}>
<LocationProbe />
<Link to="/creative-director/cd-other/overview">Open B</Link>
<Routes><Route path="/creative-director/:id/:tab" element={<CreativeDirectorDetail />} /></Routes>
</MemoryRouter>,
);
await waitFor(() => expect(getCosAgents).toHaveBeenCalled());
getCosAgents.mockResolvedValue([{ id: 'agent-b', status: 'running', taskId: 'cd-cd-other-task' }]);
await user.click(screen.getByRole('link', { name: 'Open B' }));
await screen.findByRole('heading', { name: projectB.name });
await user.click(screen.getByRole('button', { name: 'Delete project Other project' }));
await act(async () => {
resolveA(PROJECT);
resolveAgentsA([{ id: 'agent-a', status: 'running', taskId: 'cd-cd-example-task' }]);
});
expect(screen.queryByRole('heading', { name: PROJECT.name })).not.toBeInTheDocument();
expect(screen.getByTestId('agents')).toHaveTextContent('agent-b');
expect(screen.getByTestId('agents')).not.toHaveTextContent('agent-a');
await user.click(screen.getByRole('button', { name: 'Delete', exact: true }));
expect(cdApi.deleteCreativeDirectorProject).toHaveBeenCalledWith(projectB.id, { silent: true });
});
it('loads only active CoS agents and shows a running agent for this project', async () => {
getCosAgents.mockImplementation(({ active } = {}) => Promise.resolve(active
? [{ id: 'agent-a', status: 'running', taskId: 'cd-cd-example-task' }]
: [{ id: 'agent-old', status: 'completed', taskId: 'cd-cd-example-old' }]));
render(
<MemoryRouter initialEntries={['/creative-director/cd-example/overview']}>
<Routes><Route path="/creative-director/:id/:tab" element={<CreativeDirectorDetail />} /></Routes>
</MemoryRouter>,
);
await waitFor(() => expect(screen.getByTestId('agents')).toHaveTextContent('agent-a'));
expect(getCosAgents).toHaveBeenCalledWith({ active: true });
expect(screen.getByTestId('agents')).not.toHaveTextContent('agent-old');
});
it('hides project actions when the response ID differs from the route', async () => {
cdApi.getCreativeDirectorProject.mockResolvedValue({ ...PROJECT, id: 'wrong-project' });
render(
<MemoryRouter initialEntries={['/creative-director/cd-example/overview']}>
<Routes><Route path="/creative-director/:id/:tab" element={<CreativeDirectorDetail />} /></Routes>
</MemoryRouter>,
);
await screen.findByText('Project not found.');
expect(screen.queryByRole('button', { name: /Delete|Start|Stop|Pause|Resume/ })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: PROJECT.name })).not.toBeInTheDocument();
});
});
describe('Video saved artifacts', () => {
const videoProject = {
...PROJECT, workspace: 'video', targetDurationSeconds: 120,
plan: { steps: [{
stepId: 'attach-series', toolName: 'series.create', status: 'blocked', dependsOn: ['outline'],
args: { privateReasoning: 'Hidden tool arguments' },
result: { seriesId: 'example-series', privateReasoning: 'Hidden result field' },
}] },
treatment: {
script: 'Example script.\nA traveler arrives.',
scenes: Array.from({ length: 20 }, (_, order) => ({ sceneId: order === 0 ? 'arrival' : `scene-${order}`, intent: 'A traveler arrives', order, durationSeconds: 6 })),
artifact: {
scriptId: 'script-cd-example', revision: 2, targetDurationSeconds: 120, aspectRatio: '16:9', stale: false,
shots: Array.from({ length: 20 }, (_, order) => ({ shotId: order === 0 ? 'shot-arrival' : `shot-scene-${order}`, sceneId: order === 0 ? 'arrival' : `scene-${order}`, startSeconds: order * 6, endSeconds: (order + 1) * 6, durationSeconds: 6 })),
references: [
{ referenceId: 'universe:example-universe', kind: 'universe', id: 'example-universe', revision: 'rev-4' },
{ referenceId: 'voice:example-voice', kind: 'voice', id: 'example-voice' },
],
},
},
};
function renderVideo(tab = 'artifacts') {
return render(
<MemoryRouter initialEntries={[`/video/cd-example/${tab}`]}>
<LocationProbe />
<Routes>
<Route path="/video/:id/:tab" element={<CreativeDirectorDetail basePath="/video" />} />
<Route path="/video/:id/:tab/:sceneId" element={<CreativeDirectorDetail basePath="/video" />} />
</Routes>
</MemoryRouter>,
);
}
beforeEach(() => {
vi.clearAllMocks();
cdApi.getCreativeDirectorProject.mockResolvedValue(videoProject);
});
it('restores a historical script from its URL without exposing current shot actions', async () => {
const user = userEvent.setup();
const previous = { ...videoProject.treatment, script: 'The original script.', artifact: { ...videoProject.treatment.artifact, revision: 1 } };
cdApi.getCreativeDirectorProject.mockResolvedValue({ ...videoProject, treatment: { ...videoProject.treatment, history: [previous] } });
const page = renderVideo('artifacts?revision=1');
expect(await screen.findByText('The original script.')).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'shot-arrival' })).not.toBeInTheDocument();
await user.selectOptions(screen.getByLabelText('View revision'), '');
expect(screen.getByText(/Example script/)).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'shot-arrival' })).toBeInTheDocument();
page.unmount();
renderVideo('artifacts?revision=999');
expect(await screen.findByRole('alert')).toHaveTextContent('Revision not found');
expect(cdApi.startCreativeDirectorProject).not.toHaveBeenCalled();
});
it('opens artifacts from Video navigation and restores the saved revision on a fresh deep link', async () => {
const user = userEvent.setup();
const page = renderVideo('overview');
await screen.findByRole('heading', { name: PROJECT.name });
await user.click(screen.getByRole('tab', { name: 'Artifacts', exact: true }));
expect(screen.getByTestId('location')).toHaveTextContent('/video/cd-example/artifacts');
expect(screen.getByText('Revision 2 · 120 seconds · 16:9')).toBeInTheDocument();
expect(screen.getByText(/Example script/)).toHaveTextContent('A traveler arrives.');
expect(screen.getByText('0:00.00–0:06.00 · 6s')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'shot-arrival' })).toHaveAttribute('href', '/video/cd-example/segments/arrival');
expect(screen.getByRole('link', { name: 'Open universe' })).toHaveAttribute('href', '/universes/example-universe');
expect(screen.getByText('Source revision: rev-4')).toBeInTheDocument();
expect(screen.getByText('Source revision: Not recorded')).toBeInTheDocument();
expect(screen.getByText('series.create · Blocked')).toBeInTheDocument();
expect(screen.getByText('Depends on: outline')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Open series' })).toHaveAttribute('href', '/pipeline/series/example-series');
expect(screen.queryByText(/Hidden tool arguments|Hidden result field/)).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Start|Resume|Approve|Render/ })).not.toBeInTheDocument();
page.unmount();
renderVideo();
expect(await screen.findByText('Revision 2 · 120 seconds · 16:9')).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'shot-arrival' }));
expect(screen.getByTestId('location')).toHaveTextContent('/video/cd-example/segments/arrival');
expect(cdApi.startCreativeDirectorProject).not.toHaveBeenCalled();
expect(cdApi.resumeCreativeDirectorProject).not.toHaveBeenCalled();
});
it('shows stale and missing-scene repair guidance while retaining original artifact timing', async () => {
cdApi.getCreativeDirectorProject.mockResolvedValue({
...videoProject, targetDurationSeconds: 180,
treatment: { ...videoProject.treatment, scenes: [], artifact: { ...videoProject.treatment.artifact, stale: true } },
});
renderVideo();
await screen.findByText(/This artifact is out of date/);
expect(screen.getByText(/This artifact is out of date/)).toHaveAttribute('role', 'status');
expect(screen.getByText('Revision 2 · 120 seconds · 16:9')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Review the current draft' })).toHaveAttribute('href', '/video/cd-example/overview');
expect(screen.getAllByText(/Scene missing/)).toHaveLength(20);
expect(screen.queryByRole('link', { name: 'shot-arrival' })).not.toBeInTheDocument();
});
it('keeps drafts without compiled artifacts usable', async () => {
cdApi.getCreativeDirectorProject.mockResolvedValue({ ...videoProject, treatment: null, plan: null });
renderVideo();
expect(await screen.findByText(/No compiled artifact yet/)).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Review the brief' })).toHaveAttribute('href', '/video/cd-example/overview');
expect(screen.getByText('No tool plan saved.')).toBeInTheDocument();
});
it('distinguishes changed, matching, and unknown source revisions without replacing saved labels', async () => {
const user = userEvent.setup();
cdApi.getCreativeDirectorSources.mockResolvedValueOnce({ draft: [], artifact: [
{ referenceId: 'universe:example-universe', available: true, revisionChanged: true },
{ referenceId: 'voice:example-voice', available: true, revisionChanged: null },
] });
renderVideo();
expect(await screen.findByText(/Source changed since this artifact was saved/)).toBeInTheDocument();
expect(screen.getByText(/Source revision freshness unknown/)).toBeInTheDocument();
cdApi.getCreativeDirectorSources.mockResolvedValueOnce({ draft: [], artifact: [
{ referenceId: 'universe:example-universe', available: true, revisionChanged: false },
] });
await user.click(screen.getByRole('button', { name: 'Check again' }));
expect(await screen.findByText('Source revision stamp matches the saved artifact')).toBeInTheDocument();
expect(screen.getByText('Source revision: rev-4')).toBeInTheDocument();
expect(cdApi.startCreativeDirectorProject).not.toHaveBeenCalled();
});
it('reports missing sources, links to repair, and retries failed checks without altering saved revisions', async () => {
const user = userEvent.setup();
cdApi.getCreativeDirectorSources.mockRejectedValueOnce(new Error('Unavailable'));
renderVideo();
expect(await screen.findByRole('alert')).toHaveTextContent('Availability is unknown');
cdApi.getCreativeDirectorSources.mockResolvedValueOnce({
draft: [{ referenceId: 'universe:example-universe', kind: 'universe', id: 'example-universe', available: false }],
artifact: [{ referenceId: 'universe:example-universe', kind: 'universe', id: 'example-universe', available: false }],
});
await user.click(screen.getByRole('button', { name: 'Check again' }));
expect(await screen.findByText('Missing universe: example-universe')).toBeInTheDocument();
expect(screen.getByText('Source revision: rev-4')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Edit source attachments' })).toHaveAttribute('href', '/video/cd-example/overview?draft=1&videoDraftTab=sources');
expect(cdApi.startCreativeDirectorProject).not.toHaveBeenCalled();
});
});
describe('CreativeDirectorDetail realtime project lifecycle', () => {
afterEach(() => vi.useRealTimers());
it('filters project events, reconciles reconnects and applies actions before older reads', async () => {
cdApi.getCreativeDirectorProject.mockResolvedValue(PROJECT);
await renderPage();
vi.useFakeTimers();
const calls = cdApi.getCreativeDirectorProject.mock.calls.length;
await act(async () => { await vi.advanceTimersByTimeAsync(30000); });
await fireSocket('creative-director:project:changed', { id: 'other' });
expect(cdApi.getCreativeDirectorProject).toHaveBeenCalledTimes(calls);
cdApi.getCreativeDirectorProject.mockResolvedValue({ ...PROJECT, name: 'Updated project' });
await fireSocket('creative-director:project:changed', { id: PROJECT.id });
expect(screen.getByRole('heading', { name: 'Updated project' })).toBeInTheDocument();
await fireSocket('connect');
expect(cdApi.getCreativeDirectorProject).toHaveBeenCalledTimes(calls + 2);
let resolveOld;
cdApi.getCreativeDirectorProject.mockReturnValue(new Promise(resolve => { resolveOld = resolve; }));
await fireSocket('creative-director:project:changed', { id: PROJECT.id });
cdApi.startCreativeDirectorProject.mockResolvedValue({ ok: true, project: { ...PROJECT, name: 'Started project', status: 'planning' } });
await act(async () => screen.getByRole('button', { name: 'Start' }).click());
expect(screen.getByRole('heading', { name: 'Started project' })).toBeInTheDocument();
await act(async () => resolveOld(PROJECT));
expect(screen.getByRole('heading', { name: 'Started project' })).toBeInTheDocument();
});
});
describe('CreativeDirectorDetail status line', () => {
const statusLine = () => screen.getByRole('status', { name: 'Record status' });
beforeEach(() => vi.clearAllMocks());
it('says a draft waits on the user and offers Start above the fold, with no Refresh button or raw id', async () => {
cdApi.getCreativeDirectorProject.mockResolvedValue(PROJECT);
await renderPage();
expect(statusLine()).toHaveTextContent('Draft · waiting for you to start');
expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Refresh/ })).not.toBeInTheDocument();
// The raw id is no longer part of the header (the location probe is the test's own).
expect(screen.getByRole('heading', { name: PROJECT.name }).closest('div[class*="border-b"]')).not.toHaveTextContent(PROJECT.id);
});
it('names a running project and its scene progress without offering a start action', async () => {
cdApi.getCreativeDirectorProject.mockResolvedValue({
...PROJECT, status: 'rendering', treatment: { scenes: [{ status: 'accepted' }, { status: 'rendering' }] },
});
await renderPage();
expect(statusLine()).toHaveTextContent('Rendering · 1 of 2 scenes accepted');
expect(screen.queryByRole('button', { name: /^(Start|Resume|Retry)$/ })).not.toBeInTheDocument();
});
it('reports a failed project with its reason and retries through the same start action', async () => {
const user = userEvent.setup();
cdApi.getCreativeDirectorProject.mockResolvedValue({ ...PROJECT, status: 'failed', failureReason: 'Render queue unavailable' });
cdApi.startCreativeDirectorProject.mockResolvedValue({ ok: true, project: { ...PROJECT, status: 'planning' } });
await renderPage();
expect(statusLine()).toHaveTextContent('Failed · Render queue unavailable');
await user.click(screen.getByRole('button', { name: 'Retry' }));
expect(cdApi.startCreativeDirectorProject).toHaveBeenCalledWith(PROJECT.id, { silent: true });
});
it('keeps the assembled video in view on every tab once a cut exists', async () => {
const cut = { videoId: 'job-example', filename: 'example.mp4', durationSeconds: 12, audioMode: 'music' };
cdApi.getCreativeDirectorProject.mockResolvedValue({ ...PROJECT, workspace: 'video', status: 'stitching', videoRoughCut: cut });
render(
<MemoryRouter initialEntries={['/video/cd-example/runs']}>
<Routes><Route path="/video/:id/:tab" element={<CreativeDirectorDetail basePath="/video" />} /></Routes>
</MemoryRouter>,
);
expect(await screen.findByRole('region', { name: 'Assembled video' })).toBeInTheDocument();
expect(statusLine()).toHaveTextContent('Cut ready · waiting for your review');
expect(screen.getByRole('button', { name: 'Review the cut' })).toBeInTheDocument();
});
});