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: preserve Code Animation draft edits during async work
[._.]/ Adam Eivy80577fff5bb7
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsxindex d8b03e8816..931e56535f 100644--- a/client/src/pages/CodeAnimation.jsx+++ b/client/src/pages/CodeAnimation.jsx@@ -48,10 +48,56 @@ const DEFAULT_DRAFT = {interactive: false,};+const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);+const loadDraft = () => {const stored = safeReadJsonStorage(DRAFT_KEY, null);- if (!stored || typeof stored !== 'object') return DEFAULT_DRAFT;- return { ...DEFAULT_DRAFT, ...stored, format: { ...DEFAULT_DRAFT.format, ...(stored.format || {}) } };+ if (!isRecord(stored)) return DEFAULT_DRAFT;+ const format = isRecord(stored.format) ? stored.format : {};+ const referenceImages = Array.isArray(stored.referenceImages)+ ? stored.referenceImages+ .filter((image) => isRecord(image) && typeof image.filename === 'string' && image.filename.trim())+ .map((image) => ({+ filename: image.filename,+ label: typeof image.label === 'string' ? image.label : image.filename,+ note: typeof image.note === 'string' ? image.note : '',+ url: `/api/uploads/${encodeURIComponent(image.filename)}`,+ }))+ : [];+ const audio = isRecord(stored.audio)+ && typeof stored.audio.filename === 'string'+ && stored.audio.filename.trim()+ ? {+ filename: stored.audio.filename,+ label: typeof stored.audio.label === 'string' ? stored.audio.label : stored.audio.filename,+ durationSeconds: Number.isFinite(stored.audio.durationSeconds) ? stored.audio.durationSeconds : null,+ notes: typeof stored.audio.notes === 'string' ? stored.audio.notes : '',+ url: `/api/uploads/${encodeURIComponent(stored.audio.filename)}`,+ }+ : null;+ const stringField = (key) => typeof stored[key] === 'string' ? stored[key] : DEFAULT_DRAFT[key];+ return {+ ...DEFAULT_DRAFT,+ title: stringField('title'),+ seedIdea: stringField('seedIdea'),+ concept: stringField('concept'),+ onScreenText: stringField('onScreenText'),+ styleNotes: stringField('styleNotes'),+ universeId: stringField('universeId'),+ moodBoardChoice: stringField('moodBoardChoice'),+ includeMoodBoardImages: typeof stored.includeMoodBoardImages === 'boolean' ? stored.includeMoodBoardImages : DEFAULT_DRAFT.includeMoodBoardImages,+ referenceImages,+ audio,+ soundtrack: ['none', 'procedural'].includes(stored.soundtrack) ? stored.soundtrack : DEFAULT_DRAFT.soundtrack,+ format: {+ durationSeconds: Number.isFinite(format.durationSeconds) ? format.durationSeconds : DEFAULT_DRAFT.format.durationSeconds,+ aspectRatio: typeof format.aspectRatio === 'string' ? format.aspectRatio : DEFAULT_DRAFT.format.aspectRatio,+ resolution: typeof format.resolution === 'string' ? format.resolution : DEFAULT_DRAFT.format.resolution,+ fps: Number.isFinite(format.fps) ? format.fps : DEFAULT_DRAFT.format.fps,+ },+ renderer: stringField('renderer'),+ interactive: typeof stored.interactive === 'boolean' ? stored.interactive : DEFAULT_DRAFT.interactive,+ };};// The mood-board choice as the server reads it: an ABSENT moodBoardId follows@@ -202,6 +248,7 @@ export default function CodeAnimation() {const [preview, setPreview] = useState(null);const jobIdRef = useRef(jobId);const hydratedJobIdRef = useRef('');+ const locallyStartedJobIdRef = useRef('');const galleryRequestRef = useRef(0);const {providers,@@ -295,7 +342,9 @@ export default function CodeAnimation() {setSavedJobs((previous) => [galleryJob(next), ...previous.filter((item) => item.id !== requested)].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || '')));}- if (hydratedJobIdRef.current !== requested && next.input) {+ if (locallyStartedJobIdRef.current !== requested+ && hydratedJobIdRef.current !== requested+ && next.input) {hydratedJobIdRef.current = requested;const restoredDraft = draftFromJob(next);setDraft(restoredDraft);@@ -356,6 +405,12 @@ export default function CodeAnimation() {// builds the prompt.const handleWriteBrief = async () => {if (!canWriteBrief) return;+ const startingBrief = {+ title: draft.title,+ concept: draft.concept,+ onScreenText: draft.onScreenText,+ styleNotes: draft.styleNotes,+ };setWritingBrief(true);const result = await generateCodeAnimationBrief({...toBriefIdeaInput(draft),@@ -371,7 +426,13 @@ export default function CodeAnimation() {const { title, concept, onScreenText, styleNotes } = result.brief;// Style refinements live in the Style section, not the brief — only replace// the artist's own notes when the writer actually asked for a refinement.- update({ title, concept, onScreenText, ...(styleNotes ? { styleNotes } : {}) });+ setDraft((previous) => ({+ ...previous,+ ...(previous.title === startingBrief.title ? { title } : {}),+ ...(previous.concept === startingBrief.concept ? { concept } : {}),+ ...(previous.onScreenText === startingBrief.onScreenText ? { onScreenText } : {}),+ ...(styleNotes && previous.styleNotes === startingBrief.styleNotes ? { styleNotes } : {}),+ }));toast.success('Brief written — edit it before building the prompt');};@@ -401,6 +462,7 @@ export default function CodeAnimation() {});setStarting(false);if (!started) return;+ locallyStartedJobIdRef.current = started.id;setBuilt({ prompt: started.prompt, attachments: started.attachments, frame: started.frame, audioUrl: started.audioUrl, moodBoardId: started.moodBoardId, briefKey });setJob(started);setPreview(null);diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsxindex 6ce8993261..0c6cbc5e72 100644--- a/client/src/pages/CodeAnimation.test.jsx+++ b/client/src/pages/CodeAnimation.test.jsx@@ -1,7 +1,9 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { act, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { MemoryRouter } from 'react-router';+import { MemoryRouter, Route, Routes } from 'react-router';++const pollHarness = vi.hoisted(() => ({ callbacks: new Map() }));vi.mock('../services/api', () => ({buildCodeAnimationPrompt: vi.fn(),@@ -27,15 +29,23 @@ 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 {buildCodeAnimationPrompt,generateCodeAnimationBrief,+ getCodeAnimationJob,getCodeAnimationOptions,listMoodBoardNames,listUniverseNames,listUniverseStyles,+ startCodeAnimationGeneration,} from '../services/api';const OPTIONS = {@@ -48,8 +58,15 @@ const OPTIONS = {audioExtensions: ['mp3', 'wav'],};-const renderPage = async () => {- const result = render(<MemoryRouter initialEntries={['/code-animation']}><CodeAnimation /></MemoryRouter>);+const renderPage = async (initialEntry = '/code-animation') => {+ const result = render(+ <MemoryRouter initialEntries={[initialEntry]}>+ <Routes>+ <Route path="/code-animation" element={<CodeAnimation />} />+ <Route path="/code-animation/:jobId" element={<CodeAnimation />} />+ </Routes>+ </MemoryRouter>,+ );await act(async () => {});return result;};@@ -57,6 +74,7 @@ const renderPage = async () => {describe('Code Animation page', () => {beforeEach(() => {vi.clearAllMocks();+ pollHarness.callbacks.clear();localStorage.clear();getCodeAnimationOptions.mockResolvedValue(OPTIONS);listUniverseNames.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);@@ -71,6 +89,20 @@ describe('Code Animation page', () => {});});+ it('recovers from a parseable but malformed saved draft', async () => {+ localStorage.setItem('portos.codeAnimation.draft', JSON.stringify({+ title: { text: 'not a string' },+ audio: { filename: 42 },+ format: null,+ referenceImages: null,+ }));++ await renderPage();++ expect(screen.getByLabelText(/^title/i)).toHaveValue('');+ expect(screen.getByText('Reference images (0/8)')).toBeInTheDocument();+ });+it('builds a universe-styled prompt that follows the universe mood board by default', async () => {const user = userEvent.setup();await renderPage();@@ -145,6 +177,50 @@ describe('Code Animation page', () => {expect(screen.getByLabelText(/style refinements/i)).toHaveValue('more fog');});+ it('preserves brief fields edited while Write Brief is in flight', async () => {+ const user = userEvent.setup();+ let resolveBrief;+ generateCodeAnimationBrief.mockImplementationOnce(() => new Promise((resolve) => { resolveBrief = resolve; }));+ await renderPage();+ await user.type(screen.getByLabelText(/starting idea/i), 'A quiet departure');+ await user.click(screen.getByRole('button', { name: /write brief/i }));++ await user.type(screen.getByLabelText(/^title/i), 'My title');+ await user.type(screen.getByLabelText(/what happens/i), 'My concept');+ await user.type(screen.getByLabelText(/on-screen text/i), 'My text');+ await user.type(screen.getByLabelText(/style refinements/i), 'My style');++ await act(async () => resolveBrief({+ brief: { title: 'Generated title', concept: 'Generated concept', onScreenText: 'Generated text', styleNotes: 'Generated style' },+ }));++ expect(screen.getByLabelText(/^title/i)).toHaveValue('My title');+ expect(screen.getByLabelText(/what happens/i)).toHaveValue('My concept');+ expect(screen.getByLabelText(/on-screen text/i)).toHaveValue('My text');+ 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 () => {+ const user = userEvent.setup();+ startCodeAnimationGeneration.mockResolvedValueOnce({+ id: 'job-1', status: 'running', prompt: 'Built prompt', input: { title: '', concept: 'Original concept' },+ });+ getCodeAnimationJob.mockResolvedValueOnce({+ id: 'job-1', status: 'running', prompt: 'Built prompt', input: { title: '', concept: 'Original concept' },+ });+ await renderPage();+ await user.type(screen.getByLabelText(/what happens/i), 'Original concept');+ await user.click(screen.getByRole('button', { name: /build prompt/i }));+ await screen.findByLabelText('Generated prompt');+ await user.click(screen.getByRole('button', { name: /generate animation/i }));+ await waitFor(() => expect(startCodeAnimationGeneration).toHaveBeenCalledOnce());+ await user.type(screen.getByLabelText(/^title/i), 'Edited after submit');++ await act(async () => pollHarness.callbacks.get(3_000)());++ expect(screen.getByLabelText(/^title/i)).toHaveValue('Edited after submit');+ });+it('sends an explicit empty board when the user opts out of a mood board', async () => {const user = userEvent.setup();await renderPage();