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
fix: refresh Creative Director views from project events (#8543)
[._.]/ Adam Eivy1a837a0cccb6
diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsxindex 94931971e9..b65f710595 100644--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { Link } from 'react-router';import { Film, ExternalLink, Loader2, Sparkles, AlertCircle, CheckCircle2 } from 'lucide-react';import toast from '../../ui/Toast';@@ -10,20 +10,11 @@ import { getSceneStatusBadge, PROJECT_STATUS_LABEL } from '../../creative-directimport ScenePreview from '../../creative-director/ScenePreview';import ModelSelect from '../../ModelSelect';import { useAsyncAction } from '../../../hooks/useAsyncAction';-import { useAutoRefetch } from '../../../hooks/useAutoRefetch';+import { useSocketResource } from '../../../hooks/useSocketResource';import { useVideoFileSrc } from '../../../hooks/useVideoFileSrc';import { sceneShotWarnings } from '../../../lib/shotContinuity';-// Monotonic snapshot: a poll is logically equivalent when the project's id,-// updatedAt, and status all match. Including `id` guards against the restart-// edge case where prev/next describe different projects with coincidentally-// matching keys.-const sameProjectSnapshot = (prev, next) =>- prev.id === next.id- && prev.updatedAt === next.updatedAt- && prev.status === next.status;--const POLL_INTERVAL_MS = 4000;+const PROJECT_EVENTS = ['creative-director:project:changed'];const isTerminalProjectStatus = (s) => s === 'complete' || s === 'failed';@@ -127,45 +118,16 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {return () => { cancelled = true; };}, []);- // Poll while a project id is bound. Pauses on hidden tab via the hook's- // visibility short-circuit; identical snapshots dedup via the compare option- // so terminal projects no longer trigger re-renders even though the poll- // continues. Single-user app on Tailscale — the small bandwidth cost of- // polling a complete project until the user navigates away is negligible.- //- // Errors are intentionally allowed to throw — the hook's catch logs the- // failure and preserves the previously-applied data, so a transient network- // blip doesn't wipe the currently-displayed project. (A `.catch(() => null)`- // here would make the poll "succeed" with null and clear cdProject.)- //- // `immediate: true` (default) — the hook owns the visibility-aware initial- // fetch on mount and on every enabled-toggle (null↔id). The useEffect below- // only covers truthy→truthy id swaps that the hook's enabled gate misses.- const { data: rawCdProject, refetch: refetchCdProject } = useAutoRefetch(- () => getCreativeDirectorProject(cdProjectId, { slim: true }),- POLL_INTERVAL_MS,- { enabled: !!cdProjectId, compare: sameProjectSnapshot },+ const { data: rawCdProject } = useSocketResource(+ () => cdProjectId ? getCreativeDirectorProject(cdProjectId, { slim: true }) : null,+ {+ events: PROJECT_EVENTS,+ resourceKey: cdProjectId,+ matchesEvent: event => !!cdProjectId && event?.id === cdProjectId,+ },);-- // After a restart the hook still holds the previous project's snapshot until- // the next fetch lands; filter by id so the stale view doesn't paint into the- // new context.const cdProject = rawCdProject?.id === cdProjectId ? rawCdProject : null;- // Fires only on truthy→truthy cdProjectId swaps (restart). The hook's own- // immediate fetch covers mount and null↔id transitions and respects the- // hidden-tab short-circuit. `refetch` bypasses visibility, so we gate the- // call on visibilityState — on hidden tab the hook's visibility-event- // listener will pick up the new closure when the tab is reactivated.- const prevCdProjectIdRef = useRef(cdProjectId);- useEffect(() => {- const prev = prevCdProjectIdRef.current;- prevCdProjectIdRef.current = cdProjectId;- if (!cdProjectId || !prev || prev === cdProjectId) return;- if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;- refetchCdProject();- }, [cdProjectId, refetchCdProject]);-const [runSubmit, submitting] = useAsyncAction(async ({ force }) => {const payload = { aspectRatio, quality };@@ -233,7 +195,7 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {});const isComplete = cdProject?.status === 'complete' && finalVideoId;const isFailed = cdProject?.status === 'failed';- const polling = cdProject && !isTerminalProjectStatus(cdProject.status);+ const generating = cdProject && !isTerminalProjectStatus(cdProject.status);return (<div className="space-y-4">@@ -338,7 +300,7 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {) : isFailed ? (<AlertCircle size={16} className="text-port-error" />) : (- <Loader2 size={16} className={polling ? 'animate-spin text-port-accent' : 'text-gray-500'} />+ <Loader2 size={16} className={generating ? 'animate-spin text-port-accent' : 'text-gray-500'} />)}<span className="text-white">{STATUS_LABEL[cdProject?.status || 'draft'] || cdProject?.status || 'Preparing'}diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.test.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.test.jsxnew file mode 100644index 0000000000..e78c220e96--- /dev/null+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.test.jsx@@ -0,0 +1,59 @@+import { act, render, screen, fireEvent } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import { afterEach, expect, it, vi } from 'vitest';+import EpisodeVideoStage from './EpisodeVideoStage';+import { getCreativeDirectorProject } from '../../../services/apiCreativeDirector';++const handlers = vi.hoisted(() => new Map());+vi.mock('../../../services/socket', () => ({ default: {+ on: (event, fn) => { if (!handlers.has(event)) handlers.set(event, new Set()); handlers.get(event).add(fn); },+ off: (event, fn) => handlers.get(event)?.delete(fn),+ emit: vi.fn(),+} }));+vi.mock('../../../services/api', () => ({ listVideoModels: vi.fn(async () => []), generatePipelineVisualImage: vi.fn() }));+vi.mock('../../../services/apiCreativeDirector', () => ({ getCreativeDirectorProject: vi.fn() }));+vi.mock('../../../hooks/useVideoFileSrc', () => ({ useVideoFileSrc: () => ({ src: null }) }));+vi.mock('../../creative-director/ScenePreview', () => ({ default: () => null }));+const fire = async (event, payload) => act(async () => {+ for (const fn of handlers.get(event) || []) fn(payload);+});+const view = id => <MemoryRouter><EpisodeVideoStage issue={{ id: 'issue-example', stages: { episodeVideo: { cdProjectId: id } } }} onStageUpdate={vi.fn()} /></MemoryRouter>;+afterEach(() => vi.useRealTimers());++it('refreshes only the bound project, including terminal updates, reconnect and tab re-show without polling', async () => {+ vi.useFakeTimers();+ getCreativeDirectorProject.mockResolvedValue({ id: 'cd-one', status: 'rendering' });+ await act(async () => render(view('cd-one')));+ expect(getCreativeDirectorProject).toHaveBeenCalledTimes(1);+ await act(async () => vi.advanceTimersByTimeAsync(30000));+ await fire('creative-director:project:changed', { id: 'cd-other' });+ expect(getCreativeDirectorProject).toHaveBeenCalledTimes(1);+ getCreativeDirectorProject.mockResolvedValue({ id: 'cd-one', status: 'failed', failureReason: 'Example failure' });+ await fire('creative-director:project:changed', { id: 'cd-one' });+ expect(screen.getByText('Example failure')).toBeInTheDocument();+ await act(async () => vi.advanceTimersByTimeAsync(30000));+ expect(getCreativeDirectorProject).toHaveBeenCalledTimes(2);+ await fire('connect');+ expect(getCreativeDirectorProject).toHaveBeenCalledTimes(3);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ fireEvent(document, new Event('visibilitychange'));+ await fire('creative-director:project:changed', { id: 'cd-one' });+ expect(getCreativeDirectorProject).toHaveBeenCalledTimes(3);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ await act(async () => fireEvent(document, new Event('visibilitychange')));+ expect(getCreativeDirectorProject).toHaveBeenCalledTimes(4);+});++it('drops late reads after the stage switches projects', async () => {+ let resolveOld;+ getCreativeDirectorProject.mockImplementation(id => id === 'cd-old'+ ? new Promise(resolve => { resolveOld = resolve; })+ : Promise.resolve({ id, status: 'failed', failureReason: 'Current project failure' }));+ let page;+ await act(async () => { page = render(view('cd-old')); });+ await act(async () => page.rerender(view('cd-new')));+ expect(screen.getByText('Current project failure')).toBeInTheDocument();+ await act(async () => resolveOld({ id: 'cd-old', status: 'failed', failureReason: 'Stale failure' }));+ expect(screen.queryByText('Stale failure')).not.toBeInTheDocument();+ expect(screen.getByText('Current project failure')).toBeInTheDocument();+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex c38b829e8b..05648d129d 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -88,7 +88,7 @@ grep -i "what you want to do" client/src/hooks/README.md| Hook | Purpose | Use when ||---|---|---|| `useCosTaskUpdates` | Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. |-| `useSocketResource` | Initial resource read plus room/broadcast event, reconnect and tab-show reconciliation; single-flight reads, identity guards and immediate mutation updates. | Views replacing content polls with existing socket invalidations. |+| `useSocketResource` | Initial resource read plus global/room-event, reconnect and tab-show reconciliation; single-flight reads, identity guards and immediate mutation updates. | Views replacing content polls with existing socket invalidations. || `useSocketSubscription` | Refcounted `<namespace>:subscribe`/`unsubscribe` for a `registerSubscriber` room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, and `onResubscribe` refetches whatever a consumer may have missed while disconnected. | Any hook/page that emits a literal `<ns>:subscribe` for `cos`/`errors`/`notifications`/`agents`/`instances`/`loops`/`beeper` — don't hand-roll the reconnect dance; `client/src/socketSubscriptionConventions.test.js` enforces this. || `useAccountSyncStatus` | Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. || `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |diff --git a/client/src/hooks/useSocketResource.js b/client/src/hooks/useSocketResource.jsindex 3f9843bda7..fdee28c054 100644--- a/client/src/hooks/useSocketResource.js+++ b/client/src/hooks/useSocketResource.js@@ -75,7 +75,7 @@ export function useSocketResource(fetchFn, { namespace, events, resourceKey = nukey: resourceKey,update: updater => {revision += 1;- setState(previous => ({ key: resourceKey, data: updater(previous.data), loading: false, error: null }));+ setState(previous => ({ key: resourceKey, data: typeof updater === 'function' ? updater(previous.data) : updater, loading: false, error: null }));},};setState({ key: resourceKey, data: null, loading: true, error: null });diff --git a/client/src/pages/CreativeCommissionDetail.jsx b/client/src/pages/CreativeCommissionDetail.jsxindex d173bbdde3..6d7f671d68 100644--- a/client/src/pages/CreativeCommissionDetail.jsx+++ b/client/src/pages/CreativeCommissionDetail.jsx@@ -13,9 +13,7 @@** A run's render materializes ASYNCHRONOUSLY — the fire creates the Creative* Director project and returns, then the planner/render loop fills it in over- * the following minutes. The page therefore polls the referenced projects while- * any of them is still generating (#4149) so a freshly-fired render appears in- * place; there is no server-side completion event to subscribe to today.+ * the following minutes. Project-change events refresh only the referenced batch.*/import { useEffect, useMemo, useRef, useState, useCallback } from 'react';@@ -25,7 +23,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';import toast from '../components/ui/Toast';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import { useConfirmDelete } from '../hooks/useConfirmDelete';-import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useSocketResource } from '../hooks/useSocketResource';import { timeAgo } from '../utils/formatters';import CommissionConfigForm from '../components/creative-commission/CommissionConfigForm.jsx';import RenderHistory from '../components/creative-commission/RenderHistory.jsx';@@ -39,81 +37,32 @@ import {submitCommissionFeedback, runCommissionNow, getCreativeDirectorProjectsByIds,} from '../services/api';-// A CD project's lifecycle status is the only completion signal this page can-// read (no socket channel, and a commission run row is written once and never-// updated). These are the statuses where more output can still show up.-//-// NOTE the difference from `CreativeDirectorDetail`'s terminal set, which counts-// 'draft' as settled: there, a draft is a project the user hasn't started. Here,-// a commission fire creates the project and advances it in the same breath, so a-// draft we observe is just the sliver before the planner's first status write.-const GENERATING_PROJECT_STATUSES = new Set(['draft', 'planning', 'rendering', 'stitching']);--// Hard ceiling on how long a `started` run is treated as still in flight. A run-// whose project stalled (crashed mid-plan) or was pruned would otherwise poll-// forever on a tab left open — bounding by run age stops that without needing a-// timer, and generously outlasts any real generation.-const IN_FLIGHT_RUN_MAX_AGE_MS = 6 * 60 * 60 * 1000;--const PROJECT_POLL_MS = 5000;+const PROJECT_EVENTS = ['creative-director:project:changed'];+const COMMISSION_EVENTS = ['commission:changed'];export default function CreativeCommissionDetail() {+ const { id } = useParams();+ return <CommissionDetail key={id} id={id} />;+}++function CommissionDetail({ id }) {const navigate = useNavigate();const location = useLocation();- const { id } = useParams();const [searchParams] = useSearchParams();// The run this page was deep-linked to (a scheduled-run notification carries// `?run=<runId>`), so the gallery can focus that render rather than whatever is// newest by the time the user opens it.const focusRunId = searchParams.get('run');- const [commission, setCommission] = useState(null);- const [loading, setLoading] = useState(true);- const [notFound, setNotFound] = useState(false);- const [loadError, setLoadError] = useState(null);- const [reloadNonce, setReloadNonce] = useState(0);+ const { data: commission, loading, error: loadError, refetch: reloadCommission, updateData: setCommission } = useSocketResource(+ () => getCommission(id, { silent: true }),+ { events: COMMISSION_EVENTS, resourceKey: `${id}:${location.key}`, matchesEvent: event => !event?.id || event.id === id },+ );+ const notFound = loadError?.status === 404;const [form, setForm] = useState(() => toForm({}));const [saving, setSaving] = useState(false);const [running, setRunning] = useState(false);- const [projectsById, setProjectsById] = useState(() => new Map());- const [projectsLoading, setProjectsLoading] = useState(false);- // When the project batch was last ATTEMPTED — the clock the in-flight run- // check reads, so it re-evaluates on every poll tick rather than freezing at- // whatever `Date.now()` was during the last render.- const [projectsFetchedAt, setProjectsFetchedAt] = useState(0);- // The id set the batch last resolved SUCCESSFULLY. Distinct from the- // attempted-key ref below: a failed fetch is an attempt but not a load, and- // the in-flight check has to keep the two apart — an id missing from a- // successful batch is a pruned project (settled), while the same id missing- // because the request failed is simply not known yet (retry).- const [projectsLoadedKey, setProjectsLoadedKey] = useState(null);const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();- // Load (and refresh) the deep-linked commission. `location.key` is a dep so a- // notification deep link to THIS already-open page (a same-path push) still- // refetches and pulls in a just-fired run. `reloadNonce` lets the error-state- // Retry button re-run the load.- useEffect(() => {- let cancelled = false;- setLoading(true);- getCommission(id, { silent: true })- .then((fresh) => {- if (cancelled) return;- setCommission(fresh);- setNotFound(false);- setLoadError(null);- })- .catch((err) => {- if (cancelled) return;- // Only a real 404 means the commission is gone. A transient failure- // (network, 5xx, auth) must NOT be misreported as "deleted" — surface it- // as a retryable error instead (absent-vs-unreachable, per AGENTS.md).- if (err?.status === 404) { setNotFound(true); setLoadError(null); }- else setLoadError(err?.message || 'Failed to load commission');- })- .finally(() => { if (!cancelled) setLoading(false); });- return () => { cancelled = true; };- }, [id, location.key, reloadNonce]);-// Sync the form to the loaded record ONLY when the target id first resolves —// never on the in-place record swaps that rating / Run Now / save trigger, or// they'd silently discard unsaved field edits. Keying on the last-synced id@@ -136,81 +85,16 @@ export default function CreativeCommissionDetail() {return [...new Set(ids)].sort().join(',');}, [commission]);- // ONE fetch path, shared by the id-set change and the generation poll below- // (#4149). `seq` supersedes an in-flight response another call has already- // replaced — a poll tick that resolves after the id set changed must not- // reinstate the previous set's projects.- const projectsFetchSeqRef = useRef(0);- const projectsAttemptedKeyRef = useRef(null);- const fetchProjects = useCallback(async () => {- const seq = (projectsFetchSeqRef.current += 1);- if (!projectIdsKey) {- setProjectsById(new Map());- setProjectsLoading(false);- projectsAttemptedKeyRef.current = '';- setProjectsLoadedKey('');- return null;- }- // Only the FIRST attempt at a given id set shows "loading…" — a poll tick- // must not flash an already-resolved (or known-pruned) card back to the- // loading placeholder every few seconds.- if (projectsAttemptedKeyRef.current !== projectIdsKey) setProjectsLoading(true);- const projects = await getCreativeDirectorProjectsByIds(projectIdsKey.split(','), { silent: true })- .catch(() => null); // null = fetch failed; [] = resolved-but-empty (keep the two apart)- if (seq !== projectsFetchSeqRef.current) return null;- // Index by id, not position: an id that no longer resolves (pruned project)- // is absent from the response, and its card degrades to the status-only- // placeholder. A FAILED fetch keeps the last good map instead of blanking it.- if (Array.isArray(projects)) {- setProjectsById(new Map(projects.map((p) => [p.id, p])));- setProjectsLoadedKey(projectIdsKey);- }- projectsAttemptedKeyRef.current = projectIdsKey;- setProjectsLoading(false);- // Stamped on every ATTEMPT, not just a successful one, so the in-flight age- // bound below keeps re-evaluating even while the endpoint is failing.- setProjectsFetchedAt(Date.now());- return null;- }, [projectIdsKey]);-- // Is any run still producing? A run row is written once with status 'started'- // and never revisited, so "still generating" has to come from the project it- // points at, in a non-terminal CD status.- const hasGeneratingRun = useMemo(() => {- // The freshness of the data we're judging, not wall-clock render time.- const now = projectsFetchedAt || Date.now();- // Has the CURRENT id set come back from a successful batch? Until it has, an- // unresolved id means "not known yet" (initial load, or a failed attempt- // worth retrying) — after it has, the same id means the project was pruned,- // and no amount of polling brings it back.- const batchIsAuthoritative = projectsLoadedKey === projectIdsKey;- return (commission?.runs || []).some((r) => {- if (r?.status !== 'started' || !r.projectId) return false;- const ranAt = Date.parse(r.ranAt);- if (!Number.isFinite(ranAt) || now - ranAt > IN_FLIGHT_RUN_MAX_AGE_MS) return false;- const project = projectsById.get(r.projectId);- if (!project) return !batchIsAuthoritative;- return GENERATING_PROJECT_STATUSES.has(project.status);- });- }, [commission, projectsById, projectsFetchedAt, projectsLoadedKey, projectIdsKey]);-- // Poll only while something is actually generating; the hook also pauses while- // the tab is hidden and re-fires on return. `immediate: false` because the- // id-set effect below already owns the first fetch.- const { refetch: refetchProjects } = useAutoRefetch(fetchProjects, PROJECT_POLL_MS, {- enabled: hasGeneratingRun,- immediate: false,- pollOnly: true,- });-- // Fetch whenever the referenced id set changes (including the initial load and- // a Run Now appending a render) — the poll is gated on in-flight work, so it- // can't be responsible for the first read. The newest run id is a dep too: a- // fire always mints a NEW project today, so the id set moves on its own, but a- // run that ever REUSED a project id would otherwise be judged against the- // cached 'complete' snapshot and never start polling.- const latestRunId = commission?.runs?.length ? commission.runs[commission.runs.length - 1].id : null;- useEffect(() => { refetchProjects(); }, [projectIdsKey, latestRunId, refetchProjects]);+ const latestRunId = commission?.runs?.at(-1)?.id || '';+ const { data: projects, loading: projectsLoading } = useSocketResource(+ () => projectIdsKey ? getCreativeDirectorProjectsByIds(projectIdsKey.split(','), { silent: true }) : [],+ {+ events: PROJECT_EVENTS,+ resourceKey: `${id}:${projectIdsKey}:${latestRunId}`,+ matchesEvent: event => projectIdsKey.split(',').includes(event?.id),+ },+ );+ const projectsById = useMemo(() => new Map((projects || []).map(project => [project.id, project])), [projects]);const patchForm = useCallback((path, value) => setForm((prev) => patchFormState(prev, path, value)), []);@@ -311,10 +195,10 @@ export default function CreativeCommissionDetail() {return (<div className="max-w-6xl mx-auto text-center py-16"><p className="text-gray-300 mb-1">Couldn’t load this commission.</p>- <p className="text-gray-500 text-sm mb-4">{loadError || 'Please try again.'}</p>+ <p className="text-gray-500 text-sm mb-4">{loadError?.message || 'Please try again.'}</p><div className="flex items-center justify-center gap-2"><button- onClick={() => setReloadNonce((n) => n + 1)}+ onClick={() => reloadCommission()}className="inline-flex items-center gap-2 bg-port-accent text-white px-3 py-1.5 rounded text-sm">Retrydiff --git a/client/src/pages/CreativeCommissionDetail.test.jsx b/client/src/pages/CreativeCommissionDetail.test.jsxindex de09d107ad..3611435e59 100644--- a/client/src/pages/CreativeCommissionDetail.test.jsx+++ b/client/src/pages/CreativeCommissionDetail.test.jsx@@ -10,7 +10,19 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { render, screen, waitFor, act, fireEvent } from '@testing-library/react';-import { MemoryRouter, Route, Routes } from 'react-router';+import { MemoryRouter, Route, Routes, Link } 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/api', async (importOriginal) => ({...(await importOriginal()),@@ -117,12 +129,11 @@ describe('CreativeCommissionDetail render-history project resolution (#4148)', (** A commission fire creates the CD project and returns; the render lands minutes* later. The page used to sit on the stale "no render yet" card until a reload,- * and the Run-now toast said as much. It now polls the referenced projects while- * any `started` run still points at one that hasn't settled — and stops as soon- * as they all have, so an idle detail page issues no traffic.+ * and the Run-now toast said as much. Project invalidations now refresh the+ * referenced batch while idle detail pages issue no recurring traffic.*/describe('CreativeCommissionDetail live render refresh (#4149)', () => {- // Drain pending promises (and optionally advance the poll clock) inside act.+ // Drain pending promises (and advance beyond the former polling interval) inside act.const settle = async (ms = 0) => { await act(async () => { await vi.advanceTimersByTimeAsync(ms); }); };const mountLoaded = async () => {render(<MemoryRouter><CreativeCommissionDetail /></MemoryRouter>);@@ -153,12 +164,18 @@ describe('CreativeCommissionDetail live render refresh (#4149)', () => {expect(screen.getByTestId('preview-cd-1').textContent).toBe('rendering');const beforePoll = api.getCreativeDirectorProjectsByIds.mock.calls.length;- await settle(5000);- expect(api.getCreativeDirectorProjectsByIds.mock.calls.length).toBeGreaterThan(beforePoll);+ await settle(30000);+ expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalledTimes(beforePoll);+ await fireSocket('creative-director:project:changed', { id: 'unrelated' });+ expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalledTimes(beforePoll);+ const commissionCalls = api.getCommission.mock.calls.length;+ await fireSocket('creative-director:project:changed', { id: 'cd-1' });+ expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalledTimes(beforePoll + 1);+ expect(api.getCommission).toHaveBeenCalledTimes(commissionCalls);expect(screen.getByTestId('preview-cd-1').textContent).toBe('complete');});- it('stops polling once every referenced project has settled', async () => {+ it('reconciles a terminal project once per tab re-show', async () => {vi.useFakeTimers();api.getCommission.mockResolvedValue(withRun(new Date().toISOString()));api.getCreativeDirectorProjectsByIds.mockResolvedValue([@@ -170,9 +187,18 @@ describe('CreativeCommissionDetail live render refresh (#4149)', () => {await settle(30000);expect(api.getCreativeDirectorProjectsByIds.mock.calls.length).toBe(settledCalls);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ fireEvent(document, new Event('visibilitychange'));+ await fireSocket('creative-director:project:changed', { id: 'cd-1' });+ expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalledTimes(settledCalls);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ await act(async () => { fireEvent(document, new Event('visibilitychange')); });+ expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalledTimes(settledCalls + 1);+ await act(async () => { fireEvent(document, new Event('visibilitychange')); });+ expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalledTimes(settledCalls + 1);});- it('never polls for a started run past the in-flight age ceiling', async () => {+ it('does not poll even when a project remains rendering', async () => {vi.useFakeTimers();// A run whose project stalled mid-render hours ago: polling it forever would// burn a request every 5s on any tab left open, and no poll can rescue it.@@ -202,18 +228,20 @@ describe('CreativeCommissionDetail live render refresh (#4149)', () => {expect(api.getCreativeDirectorProjectsByIds.mock.calls.length).toBe(prunedCalls);});- it('keeps retrying while the project batch request is failing', async () => {+ it('retries a failed project batch on reconnect without recurring reads', async () => {vi.useFakeTimers();// A FAILED fetch is not an authoritative "pruned" answer — an unresolved id- // still means "not known yet", so the poll has to stay armed.+ // still means "not known yet"; reconnect must retry the read.api.getCommission.mockResolvedValue(withRun(new Date().toISOString()));api.getCreativeDirectorProjectsByIds.mockRejectedValue(new Error('offline'));await mountLoaded();const failedCalls = api.getCreativeDirectorProjectsByIds.mock.calls.length;- await settle(5000);- expect(api.getCreativeDirectorProjectsByIds.mock.calls.length).toBeGreaterThan(failedCalls);+ await settle(30000);+ expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalledTimes(failedCalls);+ await fireSocket('connect');+ expect(api.getCreativeDirectorProjectsByIds).toHaveBeenCalledTimes(failedCalls + 1);});it('refetches the render batch for a new run and drops the reload advice', async () => {@@ -327,3 +355,29 @@ describe('CreativeCommissionDetail stop controls', () => {expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('still in flight'));});});++it('reconciles commission events and rejects project batches from a prior route', async () => {+ let resolveOld;+ const other = { ...COMMISSION, id: 'cc-other', name: 'Other commission', runs: [{ id: 'other-run', projectId: 'cd-other', status: 'started' }] };+ api.getCommission.mockImplementation(id => Promise.resolve(id === 'cc-other' ? other : COMMISSION));+ api.getCreativeDirectorProjectsByIds.mockImplementation(ids => ids.includes('cd-other')+ ? Promise.resolve([{ id: 'cd-other', status: 'complete' }])+ : new Promise(resolve => { resolveOld = resolve; }));+ render(<MemoryRouter initialEntries={['/creative-commission/cc-1']}>+ <Link to="/creative-commission/cc-other">Other</Link>+ <Routes><Route path="/creative-commission/:id" element={<CreativeCommissionDetail />} /></Routes>+ </MemoryRouter>);+ await screen.findByRole('heading', { name: COMMISSION.name });+ await waitFor(() => expect(resolveOld).toBeTypeOf('function'));+ await act(async () => screen.getByRole('link', { name: 'Other' }).click());+ await screen.findByTestId('preview-cd-other');+ await act(async () => resolveOld([{ id: 'cd-1', status: 'rendering' }]));+ expect(screen.queryByTestId('preview-cd-1')).not.toBeInTheDocument();+ expect(screen.getByTestId('preview-cd-other')).toHaveTextContent('complete');+ const calls = api.getCommission.mock.calls.length;+ await fireSocket('commission:changed', { id: 'cc-1' });+ expect(api.getCommission).toHaveBeenCalledTimes(calls);+ api.getCommission.mockResolvedValue({ ...other, name: 'Renamed commission' });+ await fireSocket('commission:changed', { id: 'cc-other' });+ expect(screen.getByRole('heading', { name: 'Renamed commission' })).toBeInTheDocument();+});diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxindex 22a01d7957..70a60abea0 100644--- a/client/src/pages/CreativeDirectorDetail.jsx+++ b/client/src/pages/CreativeDirectorDetail.jsx@@ -27,11 +27,12 @@ import RunsTab from '../components/creative-director/RunsTab.jsx';import ActiveAgentsBanner from '../components/creative-director/ActiveAgentsBanner.jsx';import CreativeDirectorModelsDrawer from '../components/creative-director/CreativeDirectorModelsDrawer.jsx';import { getCosAgents } from '../services/apiAgents.js';-import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useSocketResource } from '../hooks/useSocketResource';import { useValidTab } from '../hooks/useValidTab';import useMediaJobProgress from '../hooks/useMediaJobProgress';-const TERMINAL_PROJECT_STATUSES = new Set(['complete', 'failed', 'paused', 'draft']);+const PROJECT_EVENTS = ['creative-director:project:changed'];+const AGENT_EVENTS = ['cos:agent:spawned', 'cos:agent:completed', 'cos:agent:updated'];const VIDEO_DRAFT_TABS = [{ id: 'overview', label: 'Overview', icon: LayoutList }, { id: 'review', label: 'Review', icon: Eye }, { id: 'artifacts', label: 'Artifacts', icon: Package }, { id: 'segments', label: 'Shots', icon: Film }, { id: 'runs', label: 'Runs', icon: ScrollText }];@@ -60,7 +61,10 @@ function CreativeDirectorProject({ id, basePath }) {const [searchParams, setSearchParams] = useSearchParams();const editingDraft = searchParams.get('draft') === '1';const setEditingDraft = open => setSearchParams(prev => { const next = new URLSearchParams(prev); if (open) next.set('draft', '1'); else next.delete('draft'); return next; }, { replace: true });- const [project, setProject] = useState(null);+ const { data: project, loading, refetch: fetchProject, updateData: setProject } = useSocketResource(+ () => getCreativeDirectorProject(id, { silent: true }),+ { events: PROJECT_EVENTS, resourceKey: id, matchesEvent: event => event?.id === id },+ );const tabs = project?.workspace === 'video' ? VIDEO_DRAFT_TABS : TABS;const activeTab = useValidTab(tabs, 'overview');// Deep-linkable open state for the per-project AI models drawer (URL is the@@ -74,41 +78,26 @@ function CreativeDirectorProject({ id, basePath }) {return params;}, { replace: !next });}, [setSearchParams]);- const [loading, setLoading] = useState(true);- const [activeAgents, setActiveAgents] = useState([]);- // Extends polling past the terminal-status gate below for a bounded window- // after the Overview tab queues a first-pass portrait/music-bed render- // (#1818/#1928) — those attach asynchronously to a catalog ingredient or- // `project.musicBed` without changing the project's lifecycle status, so a- // still-'draft' project (no compose flip to escape TERMINAL_PROJECT_STATUSES)- // would otherwise never pick up the result without a manual Refresh.- const [pendingAsyncWork, setPendingAsyncWork] = useState(false);- const pendingAsyncWorkTimerRef = useRef(null);- // Watch the queued first-pass music-bed job (#1933). Its completion attaches- // to `project.musicBed` via a durable server-side hook (picked up by polling),- // but a FAILURE (engine crash/OOM/sidecar error) has no other client-visible- // signal — so subscribe to `audio-gen:*` for the single job id and toast the- // outcome. Held in a ref alongside the id so the terminal-state effect below- // only toasts once per render, even though polling keeps re-rendering.+ const { data: agents } = useSocketResource(+ async () => {+ const data = await getCosAgents();+ return (data || []).filter(a => a.status === 'running' && (a.taskId || '').startsWith(`cd-${id}-`));+ },+ { namespace: 'cos', events: AGENT_EVENTS, resourceKey: id,+ matchesEvent: event => (event?.taskId || '').startsWith(`cd-${id}-`) },+ );+ const activeAgents = agents || [];const [musicBedJobId, setMusicBedJobId] = useState(null);const musicBedToastedRef = useRef(null);- const extendPollingForAsyncWork = useCallback((opts) => {- setPendingAsyncWork(true);+ const watchAsyncWork = useCallback(opts => {if (opts?.musicBedJobId) {musicBedToastedRef.current = null;setMusicBedJobId(opts.musicBedJobId);}- clearTimeout(pendingAsyncWorkTimerRef.current);- // 3 minutes covers a cold model load + render for the local image/audio- // gen backends in the common case; if it runs longer the user can still- // hit the manual Refresh button. Not tied to a job-completion signal —- // this component has no socket/SSE channel into the media job queue.- pendingAsyncWorkTimerRef.current = setTimeout(() => setPendingAsyncWork(false), 3 * 60 * 1000);}, []);- useEffect(() => () => clearTimeout(pendingAsyncWorkTimerRef.current), []);// Toast the music-bed render's terminal state exactly once. Success is mostly- // cosmetic (polling already renders the Music bed field), but confirms the+ // cosmetic (project events update the Music bed field), but confirms the// background render the user opted into actually landed; failure is the whole// point of #1933 — otherwise a crashed render is silently invisible.const musicBed = useMediaJobProgress(musicBedJobId, { kind: 'audio' });@@ -128,58 +117,6 @@ function CreativeDirectorProject({ id, basePath }) {}}, [musicBedJobId, musicBed.status, musicBed.error]);- const fetchProject = useCallback(async () => {- const p = await getCreativeDirectorProject(id).catch(() => null);- if (!active.current) return null;- setProject(p?.id === id ? p : null);- setLoading(false);- return null;- }, [id]);-- // Poll CoS agents in parallel so the Segments tab can flag the scene that's- // currently being worked on, even before the agent PATCHes its status.- // Filter by `taskId` prefix `cd-<projectId>-` (agentBridge's id scheme).- const fetchAgents = useCallback(async () => {- const data = await getCosAgents().catch(() => []);- if (!active.current) return null;- const prefix = `cd-${id}-`;- const mine = (data || []).filter((a) => a.status === 'running' && (a.taskId || '').startsWith(prefix));- setActiveAgents(mine);- return null;- }, [id]);-- // Only poll while the agent could still mutate the project. Once the- // status reaches a terminal state, the visibility-paused hook stops firing- // — except during the bounded `pendingAsyncWork` window above, which- // overrides the terminal gate so a queued first-pass render still surfaces.- const pollEnabled = !project?.status || !TERMINAL_PROJECT_STATUSES.has(project.status) || pendingAsyncWork;- const poll = useCallback(async () => {- await Promise.all([fetchProject(), fetchAgents()]);- return null;- }, [fetchProject, fetchAgents]);- const { refetch: refetchPoll } = useAutoRefetch(poll, 5000, { enabled: pollEnabled });-- // Reset state ONLY when the route id changes, so navigating between- // projects (or hitting an error fetch) clears the prior project — but- // the 5s poll interval below doesn't keep nulling-and-re-setting the- // same project (which previously coupled with the `project?.status`- // dep on the polling effect to produce a tight refetch loop). Refetch- // immediately on id change so a project swap doesn't leave the previous- // project on screen for up to one tick.- useEffect(() => {- setLoading(true);- setProject(null);- // A pending-async-work window is per-project intent — don't carry it- // across a route swap (the new project has its own poll-gate state).- setPendingAsyncWork(false);- // Stop watching the prior project's music-bed job on a route swap so its- // late failure/completion toast can't land on the newly-opened project.- setMusicBedJobId(null);- musicBedToastedRef.current = null;- clearTimeout(pendingAsyncWorkTimerRef.current);- refetchPoll();- }, [id, refetchPoll]);-// Stop is destructive and irreversible (SIGKILLs a live agent, cancels queued// GPU renders) and sits beside Pause, so it takes the same two-step confirm// every other destructive action in the app uses.@@ -204,21 +141,15 @@ function CreativeDirectorProject({ id, basePath }) {start: 'Started', pause: 'Paused', resume: 'Resumed',stop: 'Stopped — agent, tasks and queued renders torn down',};- // Optimistic status: start kicks off planning or rendering depending on- // whether a treatment exists; the 5s poll will correct it if the server- // resolves to a different status (e.g. planning → rendering).- const optimisticStatus = (kind === 'pause' || kind === 'stop') ? 'paused'- : kind === 'resume' ? (project?.treatment ? 'rendering' : 'planning')- : kind === 'start' ? (project?.treatment ? 'rendering' : 'planning')- : null;try {- if (kind === 'start') await startCreativeDirectorProject(id, { silent: true });- else if (kind === 'pause') await pauseCreativeDirectorProject(id, { silent: true });- else if (kind === 'resume') await resumeCreativeDirectorProject(id, { silent: true });- else if (kind === 'stop') await stopCreativeDirectorProject(id, { silent: true });+ const actions = { start: startCreativeDirectorProject, pause: pauseCreativeDirectorProject,+ resume: resumeCreativeDirectorProject, stop: stopCreativeDirectorProject };+ const result = await actions[kind](id, { silent: true });if (!active.current) return;toast.success(successMessages[kind] || kind);- if (optimisticStatus) setProject((p) => p ? { ...p, status: optimisticStatus } : p);+ if (result?.id === id) setProject(result);+ else if (result?.project?.id === id) setProject(result.project);+ else await fetchProject();} catch (err) {if (active.current) toast.error(err.message || `Failed to ${kind}`);}@@ -363,7 +294,7 @@ function CreativeDirectorProject({ id, basePath }) {<OverviewTabproject={project}onProjectUpdate={(updates) => setProject((p) => p ? { ...p, ...updates } : p)}- onAsyncWorkQueued={extendPollingForAsyncWork}+ onAsyncWorkQueued={watchAsyncWork}/>)}{project.workspace !== 'video' && activeTab === 'plan' && (diff --git a/client/src/pages/CreativeDirectorDetail.test.jsx b/client/src/pages/CreativeDirectorDetail.test.jsxindex 5352ce6c5c..754180ec5f 100644--- a/client/src/pages/CreativeDirectorDetail.test.jsx+++ b/client/src/pages/CreativeDirectorDetail.test.jsx@@ -1,8 +1,20 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+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 })),@@ -269,3 +281,29 @@ describe('Video saved artifacts', () => {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();+ });+});diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 3bb33fd3bc..b9339d1f05 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -37,6 +37,16 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({payloadSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false },},+ 'creative-director:project:changed': Object.freeze({+ direction: 'server-to-client',+ summary: 'A Creative Director project changed after persistence; fetch only a referenced project.',+ payloadSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } }, additionalProperties: false },+ }),+ 'commission:changed': Object.freeze({+ direction: 'server-to-client',+ summary: 'A creative commission changed after persistence.',+ payloadSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } }, additionalProperties: false },+ }),'app:deploy': input(appDeploySchema, 'Deploy a managed app with allowlisted flags.'),'app:standardize': input(appStandardizeSchema, 'Standardize one registered app.'),'app:update': input(appUpdateSchema, 'Run the update lifecycle for one registered app.'),diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.jsindex 11ded3a0df..d9759d007a 100644--- a/server/routes/creativeDirector.js+++ b/server/routes/creativeDirector.js@@ -190,7 +190,7 @@ router.post('/:id/stop', asyncHandler(async (req, res) => {const project = await getProject(req.params.id);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });const result = await stopProject(project.id, { reason: 'Stopped by user' });- res.json(result);+ res.json({ ...result, project: await getProject(project.id) });}));router.delete('/:id', asyncHandler(async (req, res) => {@@ -443,7 +443,7 @@ router.post('/:id/start', asyncHandler(async (req, res) => {// agent (treatment / evaluate) or kick off a render directly. The route// returns immediately; the UI's polling reflects state changes.startCreativeDirectorProject(project.id).catch((e) => console.log(`⚠️ CD start failed: ${e.message}`));- res.json({ ok: true });+ res.json({ ok: true, project: await getProject(project.id) });}));// User-callable: pause. Stops the server from auto-enqueueing follow-up@@ -489,7 +489,7 @@ router.post('/:id/resume', asyncHandler(async (req, res) => {// reporting the stop the user just undid.await updateProject(project.id, { status: restored, failureReason: null });startCreativeDirectorProject(project.id).catch((e) => console.log(`⚠️ CD resume failed: ${e.message}`));- res.json({ ok: true });+ res.json({ ok: true, project: await getProject(project.id) });}));export default router;diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex f091811a21..9613e5ae21 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -439,11 +439,13 @@ describe('creativeDirector routes', () => {describe('POST /:id/start', () => {it('flips draft → planning and triggers the orchestrator', async () => {- cdService.getProject.mockResolvedValueOnce({ id: 'cd-1', name: 'A', status: 'draft' });+ cdService.getProject.mockResolvedValueOnce({ id: 'cd-1', name: 'A', status: 'draft' })+ .mockResolvedValue({ id: 'cd-1', name: 'A', status: 'planning' });cdService.updateProject.mockResolvedValue({});const r = await request(app).post('/api/creative-director/cd-1/start');expect(r.status).toBe(200);expect(r.body.ok).toBe(true);+ expect(r.body.project).toMatchObject({ id: 'cd-1', status: 'planning' });expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { status: 'planning' });expect(hook.startCreativeDirectorProject).toHaveBeenCalledWith('cd-1');});diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex cfd938f9e2..4fb1e29d99 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -69,7 +69,7 @@ import {withBaseHashFlushBatch,maybeJournalBeforeOverwrite,} from '../../lib/conflictJournal.js';-import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';+import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import { commissionToCron } from './directive.js';import { getAbilityAdapter } from './abilityAdapters.js';import { normalizeMusicTasteConfig, sanitizeMusicTasteRecipe, renderMusicTasteRecipePrompt } from './musicTasteRecipe.js';@@ -826,6 +826,7 @@ export async function recordCommissionRun(id, runEntry) {};const runs = [...(current.runs || []), run].slice(-MAX_PERSISTED_RUNS);await store.writeRaw(id, { ...current, runs, updatedAt: new Date().toISOString() });+ emitRecordInvalidated(CREATIVE_COMMISSION_KIND, id);return run;});}@@ -869,6 +870,7 @@ export async function recordCommissionMusicOutput(id, runId, output) {const runs = [...current.runs];runs[index] = { ...runs[index], musicOutput };await store.writeRaw(id, { ...current, runs, updatedAt: new Date().toISOString() });+ emitRecordInvalidated(CREATIVE_COMMISSION_KIND, id);return runs[index];});}@@ -913,6 +915,7 @@ export async function submitCommissionFeedback(id, input) {tags: input?.tags,});if (!rec) throw makeErr('Invalid feedback: a non-zero rating (up/down) is required', ERR_VALIDATION);+ emitRecordInvalidated(CREATIVE_COMMISSION_KIND, id);commission.feedback = await listFeedbackForCommission(id).catch(() => []);return commission;}@@ -997,6 +1000,7 @@ export async function mergeCommissionsFromSync(remoteRecords, { source = { via:await maybeJournalBeforeOverwrite({ kind: CREATIVE_COMMISSION_KIND, id: next.id, local, remote: next, source });}await store.writeRaw(id, next);+ emitRecordInvalidated(CREATIVE_COMMISSION_KIND, id);await setSyncBaseHash(CREATIVE_COMMISSION_KIND, next.id, contentHashForRecord(CREATIVE_COMMISSION_KIND, next));if (next.deleted === true && local?.deleted !== true) newlyDeleted.push(id);return true;diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex 3eae399348..956d8bbb0f 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -26,7 +26,7 @@ vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-test-data// Keep peer push inert, but model the conflict-journal batch boundary so the// prune test can assert that multiple evictions share one terminal flush.vi.mock('../sharing/recordEvents.js', () => ({- emitRecordUpdated: vi.fn(), emitRecordDeleted: vi.fn(),+ emitRecordUpdated: vi.fn(), emitRecordDeleted: vi.fn(), emitRecordInvalidated: vi.fn(),autoSubscribeRecordToAllPeers: vi.fn(() => Promise.resolve()),}));const conflictJournalMock = vi.hoisted(() => {diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsindex 0a4f6b6491..0dc5b1c870 100644--- a/server/services/creativeDirector/local.js+++ b/server/services/creativeDirector/local.js@@ -25,7 +25,7 @@*/import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';-import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';+import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import { resolveIngredientsByIds, linkIngredientsToCreativeDirector } from '../catalogDB.js';import { buildCastFromIngredients } from './catalogSeed.js';import { enqueueFirstPassSceneFrames } from './firstPassGen.js';@@ -174,7 +174,11 @@ export async function updateScene(id, sceneId, patch) {/** Merge an incoming batch of project records from a peer (LWW, tombstone-aware). */export async function mergeProjectsFromSync(remoteProjects, options = {}) {- return (await selectBackend()).mergeProjectsFromSync(remoteProjects, options);+ const result = await (await selectBackend()).mergeProjectsFromSync(remoteProjects, options);+ if (result.applied) {+ for (const project of remoteProjects) emitRecordInvalidated('creativeDirectorProject', project?.id);+ }+ return result;}/** Hard-remove project tombstones older than the cutoff (called by tombstone GC). */@@ -183,11 +187,15 @@ export async function pruneTombstonedProjects(olderThanMs) {}export async function recordRun(id, runEntry) {- return (await selectBackend()).recordRun(id, runEntry);+ const result = await (await selectBackend()).recordRun(id, runEntry);+ if (result) emitRecordInvalidated('creativeDirectorProject', id);+ return result;}export async function updateRun(id, runId, patch) {- return (await selectBackend()).updateRun(id, runId, patch);+ const result = await (await selectBackend()).updateRun(id, runId, patch);+ if (result) emitRecordInvalidated('creativeDirectorProject', id);+ return result;}/** Atomic Video owner/review mutations share the owning backend's write boundary. */diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.jsindex 8e805cb94f..d103d27f82 100644--- a/server/services/creativeDirector/local.test.js+++ b/server/services/creativeDirector/local.test.js@@ -300,3 +300,32 @@ describe('getProjectsByIds (#4148)', () => {expect(mockReadJSONFile).not.toHaveBeenCalled();});});++describe('project invalidation after persistence', () => {+ it('publishes run completion only after the write and never on a failed write', async () => {+ const { recordEvents } = await import('../sharing/recordEvents.js');+ const notifications = [];+ const listener = event => notifications.push(event);+ const federated = vi.fn();+ recordEvents.on('invalidated', listener);+ recordEvents.on('updated', federated);+ try {+ mockReadJSONFile.mockResolvedValue([{ id: 'cd-example', runs: [{ runId: 'run-example', status: 'running' }] }]);+ let releaseWrite;+ mockAtomicWrite.mockImplementationOnce(() => new Promise(resolve => { releaseWrite = resolve; }));+ const pending = updateRun('cd-example', 'run-example', { status: 'completed' });+ await vi.waitFor(() => expect(releaseWrite).toBeTypeOf('function'));+ expect(notifications).toEqual([]);+ releaseWrite();+ await pending;+ expect(notifications).toEqual([{ recordKind: 'creativeDirectorProject', recordId: 'cd-example' }]);+ expect(federated).not.toHaveBeenCalled();+ mockAtomicWrite.mockRejectedValueOnce(new Error('write failed'));+ await expect(recordRun('cd-example', { kind: 'evaluate', status: 'running' })).rejects.toThrow('write failed');+ expect(notifications).toHaveLength(1);+ } finally {+ recordEvents.off('invalidated', listener);+ recordEvents.off('updated', federated);+ }+ });+});diff --git a/server/services/sharing/recordEvents.js b/server/services/sharing/recordEvents.jsindex cee0a2b723..552b649f59 100644--- a/server/services/sharing/recordEvents.js+++ b/server/services/sharing/recordEvents.js@@ -22,6 +22,12 @@ export function emitRecordUpdated(recordKind, recordId) {recordEvents.emit('updated', { recordKind, recordId });}+/** UI-only invalidation after persistence; does not enqueue a federation push. */+export function emitRecordInvalidated(recordKind, recordId) {+ if (!recordKind || !recordId) return;+ recordEvents.emit('invalidated', { recordKind, recordId });+}+/** Local deletion of a subscribed record auto-unsubscribes via the listener. */export function emitRecordDeleted(recordKind, recordId) {if (!recordKind || !recordId) return;diff --git a/server/services/socket.js b/server/services/socket.jsindex fd6238e617..968ad44faf 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -1,3 +1,4 @@+import { recordEvents } from './sharing/recordEvents.js';import { cosEvents } from './cosEvents.js';import { toAgentListItem } from '../lib/cosAgentListProjection.js';import { appsEvents } from './apps.js';@@ -237,9 +238,27 @@ function setupEventForwarding() {setupPersistentMindEventForwarding();setupCallStateEventForwarding();setupBeeperEventForwarding();+ setupRecordEventForwarding();}let persistentMindEventForwardingSetup = false;+// Bounded invalidations only: records remain behind their existing HTTP gates.+let recordEventForwardingSetup = false;+function setupRecordEventForwarding() {+ if (recordEventForwardingSetup) return;+ recordEventForwardingSetup = true;+ const forward = ({ recordKind, recordId }) => {+ if (recordKind === 'creativeDirectorProject') {+ ioInstance?.emit('creative-director:project:changed', { id: recordId });+ } else if (recordKind === 'creativeCommission') {+ ioInstance?.emit('commission:changed', { id: recordId });+ }+ };+ recordEvents.on('updated', forward);+ recordEvents.on('deleted', forward);+ recordEvents.on('invalidated', forward);+}+function setupPersistentMindEventForwarding() {if (persistentMindEventForwardingSetup) return;persistentMindEventForwardingSetup = true;diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex cc949a367f..38c4715dfd 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -1,3 +1,4 @@+import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated } from './sharing/recordEvents.js';import { authEvents } from './auth.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';@@ -171,6 +172,20 @@ describe('socket.js — initSocket', () => {initSocket(io);});+ it('forwards bounded project and commission invalidations from structural and local-only writes', () => {+ emitRecordUpdated('creativeDirectorProject', 'cd-example');+ emitRecordDeleted('creativeDirectorProject', 'cd-example');+ emitRecordInvalidated('creativeDirectorProject', 'cd-example');+ emitRecordInvalidated('creativeCommission', 'cc-example');+ emitRecordUpdated('unrelated', 'example');+ expect(io.emitted.filter(([name]) => name === 'creative-director:project:changed')).toEqual(+ Array.from({ length: 3 }, () => ['creative-director:project:changed', { id: 'cd-example' }]),+ );+ expect(io.emitted.filter(([name]) => name === 'commission:changed')).toEqual([+ ['commission:changed', { id: 'cc-example' }],+ ]);+ });+it('sends compact task invalidations to opted-in pages while preserving legacy subscribers', () => {const compact = makeSocket('compact-cos');const legacy = makeSocket('legacy-cos');