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

fix: update code animation jobs from socket events (#8600)

[._.]/ Adam Eivy46613cc15748
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsx
index 8cc82c06e7..24e0a5b3d5 100644
--- a/client/src/pages/CodeAnimation.jsx
+++ b/client/src/pages/CodeAnimation.jsx
@@ -9,7 +9,7 @@ import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';
import useProviderModels from '../hooks/useProviderModels';
import { usePagedCollection } from '../hooks/usePagedCollection';
import { useSocketSubscription } from '../hooks/useSocketSubscription';
-import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { useSocketResource } from '../hooks/useSocketResource';
import socket from '../services/socket';
import toast from '../components/ui/Toast';
import {
@@ -31,7 +31,7 @@ import { readFileAsBase64, UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../uti
import { formatCount, timeAgo } from '../utils/formatters';
const DRAFT_KEY = 'portos.codeAnimation.draft';
-const JOB_POLL_MS = 3_000;
+const JOB_EVENTS = ['code-animation:changed'];
// Mood-board choice sentinels: follow the universe's linked board, or none.
const BOARD_FOLLOW_UNIVERSE = 'universe';
const BOARD_NONE = 'none';
@@ -296,7 +296,6 @@ export default function CodeAnimation() {
const [briefEffort, setBriefEffort] = useState('');
const [pastedHtml, setPastedHtml] = useState('');
const [preview, setPreview] = useState(null);
- const jobIdRef = useRef(jobId);
const hydratedJobIdRef = useRef('');
const locallyStartedJobIdRef = useRef('');
const {
@@ -366,25 +365,32 @@ export default function CodeAnimation() {
const inProgressCount = galleryCounts.running;
const completedCount = galleryCounts.completed;
- // Poll the generation job named in the URL until it settles. The ref drops a
- // response for a job the user has since replaced.
+ // Clear route-specific output before applying the newly selected resource.
useEffect(() => {
- jobIdRef.current = jobId;
hydratedJobIdRef.current = '';
setJob(null);
setPreview(null);
setBuilt(null);
}, [jobId]);
- const jobSettled = job?.id === jobId && job.status !== 'running';
- const pollJob = useCallback(async () => {
- const requested = jobId;
- // Only a 404 means the job is gone; any other failure rethrows so the
- // poller keeps trying on its next tick.
- const next = await getCodeAnimationJob(requested, { silent: true }).catch((error) => {
- if (error.status === 404) return { id: requested, status: 'missing', error: error.message };
+ const jobResource = useSocketResource(async () => {
+ if (!jobId) return null;
+ // Only a 404 means the job is gone. Transient failures retain the current
+ // output and recover on the next event, reconnect or tab re-show.
+ return getCodeAnimationJob(jobId, { silent: true }).catch((error) => {
+ if (error.status === 404) return { id: jobId, status: 'missing', error: error.message };
throw error;
});
- if (jobIdRef.current !== requested) return;
+ }, {
+ namespace: 'code-animation',
+ events: JOB_EVENTS,
+ resourceKey: jobId,
+ matchesEvent: (payload) => !!jobId && payload?.id === jobId,
+ });
+
+ useEffect(() => {
+ const next = jobResource.data;
+ if (!next) return;
+ const requested = jobId;
setJob(next);
if (next.status === 'completed' && next.html) setPreview({ html: next.html, audioUrl: next.audioUrl, frame: next.frame });
else setPreview(null);
@@ -410,8 +416,7 @@ export default function CodeAnimation() {
briefKey: JSON.stringify(toBrief(restoredDraft)),
} : null);
}
- }, [jobId]);
- useAutoRefetch(pollJob, JOB_POLL_MS, { enabled: !!jobId && !jobSettled, pollOnly: true });
+ }, [jobId, jobResource.data]);
const handleImages = async (event) => {
const files = [...(event.target.files || [])];
diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsx
index ee4dcc2bbe..c21eb7d6e4 100644
--- a/client/src/pages/CodeAnimation.test.jsx
+++ b/client/src/pages/CodeAnimation.test.jsx
@@ -1,9 +1,8 @@
-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 } from 'react-router';
-const pollHarness = vi.hoisted(() => ({ callbacks: new Map() }));
const socketHarness = vi.hoisted(() => ({ handlers: new Map() }));
vi.mock('../services/socket', () => ({ default: {
@@ -41,12 +40,6 @@ vi.mock('../hooks/useProviderModels', () => ({
loading: false,
}),
}));
-vi.mock('../hooks/useAutoRefetch', () => ({
- useAutoRefetch: (callback, interval, { enabled }) => {
- if (enabled) pollHarness.callbacks.set(interval, callback);
- else pollHarness.callbacks.delete(interval);
- },
-}));
import CodeAnimation from './CodeAnimation';
import {
@@ -85,10 +78,34 @@ const renderPage = async (initialEntry = '/code-animation') => {
return result;
};
+const emitSocket = async (event, payload) => {
+ await act(async () => {
+ for (const handler of socketHarness.handlers.get(event) || []) handler(payload);
+ });
+};
+
+const changeVisibility = async (value) => {
+ await act(async () => {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+};
+
+const runningJob = {
+ id: 'job-1', status: 'running', title: 'Example animation',
+ input: { title: 'Example animation', concept: 'A lantern rises' },
+ prompt: 'Example prompt', createdAt: '2026-01-01T00:00:00.000Z',
+};
+const completedJob = {
+ ...runningJob, status: 'completed', html: '<html><body>Finished animation</body></html>',
+ audioUrl: '/api/uploads/example-audio.mp3',
+ frame: { width: 1280, height: 720, durationSeconds: 20, fps: 30 },
+};
+
describe('Code Animation page', () => {
beforeEach(() => {
vi.clearAllMocks();
- pollHarness.callbacks.clear();
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
socketHarness.handlers.clear();
listCodeAnimationJobPage.mockResolvedValue({ items: [], total: 0, counts: { running: 0, completed: 0 }, nextCursor: null });
localStorage.clear();
@@ -106,6 +123,76 @@ describe('Code Animation page', () => {
});
});
+ afterEach(() => vi.useRealTimers());
+
+ it('restores a routed job, updates its preview on its event, and never polls', async () => {
+ getCodeAnimationJob.mockResolvedValue(runningJob);
+ await renderPage('/code-animation/job-1');
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(1);
+ expect(screen.getByLabelText(/^title/i)).toHaveValue('Example animation');
+ expect(screen.getByLabelText(/what happens/i)).toHaveValue('A lantern rises');
+ expect(screen.getByLabelText('Generated prompt')).toHaveValue('Example prompt');
+ vi.useFakeTimers();
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(1);
+ vi.useRealTimers();
+
+ await emitSocket('code-animation:changed', { id: 'unrelated-job' });
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(1);
+ getCodeAnimationJob.mockResolvedValue(completedJob);
+ await emitSocket('code-animation:changed', { id: 'job-1' });
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
+ expect(screen.getByRole('button', { name: 'Run with audio' })).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: /Example animation/ })).toHaveTextContent('Completed');
+ await userEvent.setup().click(screen.getByRole('button', { name: 'Preview without audio' }));
+ expect(screen.getByTitle('Code animation preview')).toHaveAttribute('srcdoc', expect.stringContaining('Finished animation'));
+
+ // Terminal records still reconcile: a missing output can be discovered later.
+ getCodeAnimationJob.mockResolvedValue({ ...completedJob, status: 'failed', error: 'Output missing', html: null });
+ await emitSocket('code-animation:changed', { id: 'job-1' });
+ expect(screen.getByText('Generation failed: Output missing')).toBeInTheDocument();
+ expect(screen.queryByTitle('Code animation preview')).not.toBeInTheDocument();
+ });
+
+ it('reconciles once per reconnect and tab re-show, including transient errors and missing jobs', async () => {
+ getCodeAnimationJob.mockRejectedValueOnce(new Error('Temporary outage')).mockResolvedValue(runningJob);
+ await renderPage('/code-animation/job-1');
+ expect(screen.queryByText('That generation is no longer available.')).not.toBeInTheDocument();
+ await emitSocket('connect');
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
+ expect(screen.getByLabelText(/^title/i)).toHaveValue('Example animation');
+ await changeVisibility('hidden');
+ await emitSocket('code-animation:changed', { id: 'job-1' });
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
+ getCodeAnimationJob.mockRejectedValueOnce({ status: 404, message: 'Missing' });
+ await changeVisibility('visible');
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(3);
+ expect(screen.getByText('That generation is no longer available.')).toBeInTheDocument();
+ await changeVisibility('visible');
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(3);
+ });
+
+ it('drops a pending response after selecting another job and releases listeners on unmount', async () => {
+ let resolveFirst;
+ getCodeAnimationJob.mockImplementationOnce(() => new Promise(resolve => { resolveFirst = resolve; }))
+ .mockResolvedValue({ ...runningJob, id: 'job-2', title: 'Second animation',
+ input: { title: 'Second animation', concept: 'Another scene' } });
+ listCodeAnimationJobPage.mockResolvedValue({ items: [{ ...runningJob, id: 'job-2', title: 'Second animation' }],
+ total: 1, counts: { running: 1, completed: 0 }, nextCursor: null });
+ const view = await renderPage('/code-animation/job-1');
+ await userEvent.setup().click(screen.getByRole('link', { name: /Second animation/ }));
+ expect(screen.getByLabelText(/^title/i)).toHaveValue('Second animation');
+ await act(async () => resolveFirst(completedJob));
+ expect(screen.getByLabelText(/^title/i)).toHaveValue('Second animation');
+ expect(screen.queryByRole('button', { name: 'Run with audio' })).not.toBeInTheDocument();
+ await emitSocket('code-animation:changed', { id: 'job-1' });
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
+ view.unmount();
+ await emitSocket('code-animation:changed', { id: 'job-2' });
+ await emitSocket('connect');
+ expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);
+ });
+
it('recovers from a parseable but malformed saved draft', async () => {
localStorage.setItem('portos.codeAnimation.draft', JSON.stringify({
title: { text: 'not a string' },
@@ -129,7 +216,6 @@ describe('Code Animation page', () => {
await renderPage();
await waitFor(() => expect(screen.getAllByRole('link', { name: /Animation \d+/ })).toHaveLength(50));
expect(listCodeAnimationJobPage).toHaveBeenCalledTimes(1);
- expect(pollHarness.callbacks.has(10_000)).toBe(false);
expect(screen.getByText('0 in progress · 1,000 completed')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Load older animations' })).toBeInTheDocument();
vi.useFakeTimers();
@@ -243,12 +329,12 @@ describe('Code Animation page', () => {
expect(screen.getByLabelText(/style refinements/i)).toHaveValue('My style');
});
- it('keeps edits made after starting a generation when the first poll returns its input snapshot', async () => {
+ it('keeps edits made after starting a generation when an invalidation returns its input snapshot', async () => {
const user = userEvent.setup();
startCodeAnimationGeneration.mockResolvedValueOnce({
id: 'job-1', status: 'running', prompt: 'Built prompt', input: { title: '', concept: 'Original concept' },
});
- getCodeAnimationJob.mockResolvedValueOnce({
+ getCodeAnimationJob.mockResolvedValue({
id: 'job-1', status: 'running', prompt: 'Built prompt', input: { title: '', concept: 'Original concept' },
});
await renderPage();
@@ -259,7 +345,7 @@ describe('Code Animation page', () => {
await waitFor(() => expect(startCodeAnimationGeneration).toHaveBeenCalledOnce());
await user.type(screen.getByLabelText(/^title/i), 'Edited after submit');
- await act(async () => pollHarness.callbacks.get(3_000)());
+ await emitSocket('code-animation:changed', { id: 'job-1' });
expect(screen.getByLabelText(/^title/i)).toHaveValue('Edited after submit');
});
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index 7de2d19155..8bd78f6cad 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -86,7 +86,7 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
},
'code-animation:changed': {
direction: 'server-to-client',
- summary: 'Invalidate the bounded Code Animation gallery after a durable job change.',
+ summary: 'Invalidate the bounded Code Animation gallery and matching selected job after a durable job change.',
payloadSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false },
},
diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.js
index 63216ce8d0..9f31980527 100644
--- a/server/routes/codeAnimation.test.js
+++ b/server/routes/codeAnimation.test.js
@@ -31,6 +31,13 @@ vi.mock('../services/codeAnimation/jobStore.js', () => ({
saveCodeAnimationHtml: vi.fn(async (id, html) => codeAnimationHtml.set(id, html)),
saveCodeAnimationJobRecord: vi.fn(async (job) => codeAnimationRecords.set(job.id, job)),
}));
+vi.mock('../services/socket.js', () => ({
+ // Observe the persisted state at emit time: a notification before a save
+ // would make a socket-driven client read stale data with no later retry.
+ emitCodeAnimationChanged: vi.fn((id) => ({
+ id, status: codeAnimationRecords.get(id)?.status, html: codeAnimationHtml.get(id),
+ })),
+}));
vi.mock('../services/universeBuilder/crud.js', () => ({ getUniverse: vi.fn() }));
vi.mock('../services/moodBoard/db.js', () => ({ getBoard: vi.fn() }));
vi.mock('../services/providers.js', () => ({ getProviderById: vi.fn() }));
@@ -41,6 +48,7 @@ vi.mock('../services/promptRunner.js', () => ({
assertProvider: vi.fn(),
}));
+import { emitCodeAnimationChanged } from '../services/socket.js';
import { PATHS } from '../lib/paths.js';
import { getUniverse } from '../services/universeBuilder/crud.js';
import { getBoard } from '../services/moodBoard/db.js';
@@ -116,6 +124,9 @@ describe('GET /api/code-animation/jobs', () => {
expect(response.status).toBe(200);
expect(response.body.items).toMatchObject([{ id, status: 'failed' }]);
expect(response.body.counts).toEqual({ running: 0, completed: 0 });
+ expect(emitCodeAnimationChanged.mock.results.map(({ value }) => value)).toEqual([
+ { id, status: 'failed', html: undefined },
+ ]);
expect(listCodeAnimationJobRecords).not.toHaveBeenCalled();
expect((await request(makeApp()).get(`/api/code-animation/generate/${id}`)).body.error)
.toMatch(/interrupted by a server restart/);
@@ -370,6 +381,10 @@ describe('POST /api/code-animation/generate', () => {
const job = await pollUntilSettled(app, res.body.id);
expect(job).toMatchObject({ status: 'completed', providerId: 'api-1', model: 'example-model', runId: 'run-1' });
expect(job.html).toBe('<!DOCTYPE html><html><body><canvas></canvas></body></html>');
+ expect(emitCodeAnimationChanged.mock.results.map(({ value }) => value)).toEqual([
+ { id: job.id, status: 'running', html: undefined },
+ { id: job.id, status: 'completed', html: job.html },
+ ]);
const call = runPromptThroughProvider.mock.calls[0][0];
expect(call.source).toBe('code-animation-generation');
expect(call.cwd).toBe(PATHS.data);
@@ -390,6 +405,10 @@ describe('POST /api/code-animation/generate', () => {
const job = await pollUntilSettled(app, res.body.id);
expect(job.status).toBe('failed');
expect(job.error).toMatch(/did not contain an HTML document/);
+ expect(emitCodeAnimationChanged.mock.results.map(({ value }) => value)).toEqual([
+ { id: job.id, status: 'running', html: undefined },
+ { id: job.id, status: 'failed', html: undefined },
+ ]);
});
it('refuses a disabled provider before starting a job', async () => {