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
Code Animation: delete gallery items
Claude715fbf604694
diff --git a/client/src/components/codeAnimation/CodeAnimationGallery.jsx b/client/src/components/codeAnimation/CodeAnimationGallery.jsxindex 16adcf1921..3bef8f7a72 100644--- a/client/src/components/codeAnimation/CodeAnimationGallery.jsx+++ b/client/src/components/codeAnimation/CodeAnimationGallery.jsx@@ -1,13 +1,16 @@import { useCallback, useEffect, useRef, useState } from 'react';-import { AlertTriangle, CheckCircle2, Clock3, FileCode2, ImageOff, LoaderCircle, Sparkles } from 'lucide-react';+import { AlertTriangle, CheckCircle2, Clock3, FileCode2, ImageOff, LoaderCircle, Sparkles, Trash2 } from 'lucide-react';import { Link } from 'react-router';import useMounted from '../../hooks/useMounted';+import { useConfirmDelete } from '../../hooks/useConfirmDelete';import { usePagedCollection } from '../../hooks/usePagedCollection';import { useSocketSubscription } from '../../hooks/useSocketSubscription';import socket from '../../services/socket';-import { codeAnimationPosterUrl, listCodeAnimationJobPage, requestCodeAnimationPoster } from '../../services/api';+import { codeAnimationPosterUrl, deleteCodeAnimationJob, listCodeAnimationJobPage, requestCodeAnimationPoster } from '../../services/api';import { formatCount, timeAgo } from '../../utils/formatters';import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';+import InlineConfirmRow from '../ui/InlineConfirmRow';+import toast from '../ui/Toast';const STATUS = {running: { icon: Clock3, label: 'In progress', tone: 'text-port-accent' },@@ -30,32 +33,53 @@ function PosterPlaceholder({ item, capturing }) {return <ImageOff className="h-8 w-8 text-gray-600" aria-hidden="true" />;}-function GalleryCard({ item, capturing }) {+function GalleryCard({ item, capturing, confirming, deleting, onRequestDelete, onCancelDelete, onConfirmDelete }) {const status = STATUS[item.status] || STATUS.failed;const StatusIcon = status.icon;+ const title = item.title || 'Untitled animation';return (- <Link- to={`/code-animation/${encodeURIComponent(item.id)}`}- className="group min-w-0 overflow-hidden rounded-xl border border-port-border bg-port-card transition-colors hover:border-port-accent"- >- <div className="relative flex aspect-video items-center justify-center bg-black">- {item.posterVersion- ? <img src={codeAnimationPosterUrl(item.id, item.posterVersion)} alt="" loading="lazy" className="h-full w-full object-contain" />- : <PosterPlaceholder item={item} capturing={capturing} />}- {item.status !== 'completed' && (- <span className="port-media-overlay absolute left-2 top-2 inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs">- <StatusIcon className={`h-3 w-3 ${status.tone}`} aria-hidden="true" /> {status.label}- </span>- )}- </div>- <div className="space-y-1 p-3">- <p className="truncate text-sm font-medium text-white group-hover:text-port-accent">{item.title || 'Untitled animation'}</p>- <div className="flex items-center justify-between gap-2 text-xs text-gray-500">- <span className="min-w-0 truncate">{item.status === 'completed' ? (item.model || 'Completed') : status.label}</span>- <span className="shrink-0">{timeAgo(item.createdAt)}</span>+ <div className="relative min-w-0">+ <Link+ to={`/code-animation/${encodeURIComponent(item.id)}`}+ className="group block min-w-0 overflow-hidden rounded-xl border border-port-border bg-port-card transition-colors hover:border-port-accent"+ >+ <div className="relative flex aspect-video items-center justify-center bg-black">+ {item.posterVersion+ ? <img src={codeAnimationPosterUrl(item.id, item.posterVersion)} alt="" loading="lazy" className="h-full w-full object-contain" />+ : <PosterPlaceholder item={item} capturing={capturing} />}+ {item.status !== 'completed' && (+ <span className="port-media-overlay absolute left-2 top-2 inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs">+ <StatusIcon className={`h-3 w-3 ${status.tone}`} aria-hidden="true" /> {status.label}+ </span>+ )}</div>- </div>- </Link>+ <div className="space-y-1 p-3">+ <p className="truncate text-sm font-medium text-white group-hover:text-port-accent">{title}</p>+ <div className="flex items-center justify-between gap-2 text-xs text-gray-500">+ <span className="min-w-0 truncate">{item.status === 'completed' ? (item.model || 'Completed') : status.label}</span>+ <span className="shrink-0">{timeAgo(item.createdAt)}</span>+ </div>+ </div>+ </Link>+ {/* A generating animation can't be deleted until it finishes. */}+ {item.status !== 'running' && !confirming && (+ <button type="button" onClick={() => onRequestDelete(item.id)} disabled={deleting}+ aria-label={`Delete ${title}`}+ className="port-media-overlay absolute right-2 top-2 inline-flex h-11 w-11 items-center justify-center rounded-lg text-gray-200 hover:text-port-error disabled:opacity-40">+ {deleting ? <LoaderCircle className="h-4 w-4 animate-spin" aria-hidden="true" /> : <Trash2 className="h-4 w-4" aria-hidden="true" />}+ </button>+ )}+ {confirming && (+ <InlineConfirmRow+ className="mt-2"+ autoFocus+ aria-label={`Delete ${title}?`}+ question={`Delete “${title}”? Its files go to the Trash.`}+ onConfirm={() => onConfirmDelete(item)}+ onCancel={onCancelDelete}+ />+ )}+ </div>);}@@ -104,6 +128,19 @@ export default function CodeAnimationGallery() {}}, [items, setItems, mounted]);+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();+ const [deleting, setDeleting] = useState(() => new Set());+ const handleDelete = (item) => confirmDelete(async () => {+ setDeleting((previous) => new Set(previous).add(item.id));+ const done = await deleteCodeAnimationJob(item.id, { silent: true })+ .catch((error) => { toast.error(error.message || 'Could not delete the animation'); return null; });+ if (!mounted.current) return;+ setDeleting((previous) => { const next = new Set(previous); next.delete(item.id); return next; });+ if (!done) return;+ setItems((previous) => previous.filter((entry) => entry.id !== item.id));+ toast.success(`Deleted ${item.title || 'the animation'}`);+ });+const counts = gallery.meta || { running: 0, completed: 0 };return (<div className="space-y-4">@@ -128,7 +165,9 @@ export default function CodeAnimationGallery() {{items.length > 0 && (<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">{items.map((item) => (- <GalleryCard key={item.id} item={item} capturing={capturing.has(item.id)} />+ <GalleryCard key={item.id} item={item} capturing={capturing.has(item.id)}+ confirming={isConfirming(item.id)} deleting={deleting.has(item.id)}+ onRequestDelete={requestDelete} onCancelDelete={cancelDelete} onConfirmDelete={handleDelete} />))}</div>)}diff --git a/client/src/components/codeAnimation/CodeAnimationGallery.test.jsx b/client/src/components/codeAnimation/CodeAnimationGallery.test.jsxnew file mode 100644index 0000000000..a7b8c790b6--- /dev/null+++ b/client/src/components/codeAnimation/CodeAnimationGallery.test.jsx@@ -0,0 +1,57 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';++vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));+vi.mock('../../hooks/useSocketSubscription', () => ({ useSocketSubscription: vi.fn() }));+vi.mock('../../services/api', () => ({+ listCodeAnimationJobPage: vi.fn(),+ deleteCodeAnimationJob: vi.fn(),+ requestCodeAnimationPoster: vi.fn(),+ codeAnimationPosterUrl: (id) => `/posters/${id}.jpg`,+}));+import { deleteCodeAnimationJob, listCodeAnimationJobPage } from '../../services/api';+import CodeAnimationGallery from './CodeAnimationGallery';++const item = (id, title, status = 'completed') => ({ id, title, status, posterVersion: 1, createdAt: '2026-01-01T00:00:00.000Z' });++beforeEach(() => {+ vi.clearAllMocks();+ listCodeAnimationJobPage.mockResolvedValue({+ items: [item('a', 'Station boot'), item('b', 'Still generating', 'running')],+ nextCursor: null, counts: { running: 1, completed: 1 },+ });+ deleteCodeAnimationJob.mockResolvedValue({ id: 'a', deleted: true });+});++describe('CodeAnimationGallery', () => {+ it('deletes an animation only after the inline confirm, and never offers it while generating', async () => {+ const user = userEvent.setup();+ render(<MemoryRouter><CodeAnimationGallery /></MemoryRouter>);+ await screen.findByText('Station boot');+ expect(screen.queryByRole('button', { name: 'Delete Still generating' })).toBeNull();++ await user.click(screen.getByRole('button', { name: 'Delete Station boot' }));+ expect(deleteCodeAnimationJob).not.toHaveBeenCalled();+ await user.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(screen.getByText('Station boot')).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'Delete Station boot' }));+ expect(screen.getByText('Delete “Station boot”? Its files go to the Trash.')).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'Delete' }));+ expect(deleteCodeAnimationJob).toHaveBeenCalledWith('a', { silent: true });+ await waitFor(() => expect(screen.queryByText('Station boot')).toBeNull());+ expect(screen.getByText('Still generating')).toBeTruthy();+ });++ it('keeps the animation when the delete is refused', async () => {+ const user = userEvent.setup();+ deleteCodeAnimationJob.mockRejectedValue(new Error('Could not move the animation files to the Trash'));+ render(<MemoryRouter><CodeAnimationGallery /></MemoryRouter>);+ await user.click(await screen.findByRole('button', { name: 'Delete Station boot' }));+ await user.click(screen.getByRole('button', { name: 'Delete' }));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Delete Station boot' }).disabled).toBe(false));+ expect(screen.getByText('Station boot')).toBeTruthy();+ });+});diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex fd1da4b03d..2c8e0c984a 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -53,6 +53,10 @@ export const codeAnimationPosterUrl = (id, version) =>export const requestCodeAnimationPoster = (id, options) =>request(`/code-animation/jobs/${encodeURIComponent(id)}/poster`, { method: 'POST', ...options });+// Its HTML and poster go to the system Trash; Media History exports stay.+export const deleteCodeAnimationJob = (id, options) =>+ request(`/code-animation/jobs/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });+export const getCodeAnimationJob = (id, options) =>request(`/code-animation/generate/${encodeURIComponent(id)}`, options);diff --git a/docs/API.md b/docs/API.mdindex 3a81b4af3d..6dd9179a77 100644--- a/docs/API.md+++ b/docs/API.md@@ -829,7 +829,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/sprites` | Sprite catalog / export; `POST /import` is host control (it names a host source tree to copy from) || `/api/threejs-models` | Procedural Three.js models || `/api/film-styles` | Read-only film style grammar catalog: picker list (`GET /`), full grammar record (`GET /:id`) and rendered prompt-section preview (`GET /:id/prompt?parts=motion,camera`) |-| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building (a `baseJobId` forks a finished animation: its HTML rides the prompt as the cut to extend, refused whole above `baseHtmlMax`), persistent jobs gallery with poster thumbnails (`GET`/`POST /jobs/:id/poster`; captured in the jailed preview browser), generated HTML retrieval, frame-exact MP4 export (`POST /:id/export` → HTML-composition media job), a generated soundtrack for a finished animation (`POST /:id/soundtrack` → one local music-engine render at the film length onto a Music-library track that becomes the job audio; `POST /:id/soundtrack/track` returns that track, created on first use, for a coded score saved with `POST /api/music/code` + the track's code-take routes), the vendored three.js modules the `three` renderer's preview inlines (`GET /vendor/three`; the export stages the same files, hashed, beside the page), portable source download (`GET /:id/package`), and data-only package validation (`POST /packages/validate`; [contract](CODE_ANIMATION_PACKAGES.md)) |+| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building (a `baseJobId` forks a finished animation: its HTML rides the prompt as the cut to extend, refused whole above `baseHtmlMax`), persistent jobs gallery with poster thumbnails (`GET`/`POST /jobs/:id/poster`; captured in the jailed preview browser); `DELETE /jobs/:id` moves a finished item's HTML and poster to the system Trash, then removes it), generated HTML retrieval, frame-exact MP4 export (`POST /:id/export` → HTML-composition media job), a generated soundtrack for a finished animation (`POST /:id/soundtrack` → one local music-engine render at the film length onto a Music-library track that becomes the job audio; `POST /:id/soundtrack/track` returns that track, created on first use, for a coded score saved with `POST /api/music/code` + the track's code-take routes), the vendored three.js modules the `three` renderer's preview inlines (`GET /vendor/three`; the export stages the same files, hashed, beside the page), portable source download (`GET /:id/package`), and data-only package validation (`POST /packages/validate`; [contract](CODE_ANIMATION_PACKAGES.md)) || `/api/code-animation/execution` | Code Animation contained production execution: platform sandbox and lane readiness (`GET /`), operator-owned tool paths (`PUT /tools`, host control) and the on-demand adversarial containment check (`POST /probe`, host control) ([contract](CODE_ANIMATION_PACKAGES.md#contained-production-execution)) || `/api/image-to-3d` | Image-to-3D conversion || `/api/rigging` | Auto-skin rigging and animation retargeting for image-to-3D models |diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex 52a1921530..fa8a7b5c6d 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -36,6 +36,7 @@ import {buildCodeAnimationRequest,captureCodeAnimationJobPoster,codeAnimationPosterPath,+ deleteCodeAnimationJob,generateCodeAnimationBrief,getCodeAnimationJob,listCodeAnimationJobs,@@ -225,6 +226,12 @@ router.get('/generate/:id', asyncHandler(async (req, res) => {res.json(job);}));+// Delete a gallery item: its files go to the system Trash, then the row.+router.delete('/jobs/:id', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ res.json(await deleteCodeAnimationJob(id));+}));+const projectPageSchema = z.object({limit: z.coerce.number().int().min(1).max(100).default(50),cursor: z.string().regex(/^(0|[1-9][0-9]{0,8})$/).optional(),diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex 4c19d5b356..8b1548dd90 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -37,9 +37,12 @@ vi.mock('../services/codeAnimation/jobStore.js', () => ({readCodeAnimationHtml: vi.fn(async (id) => codeAnimationHtml.get(id)),saveCodeAnimationHtml: vi.fn(async (id, html) => codeAnimationHtml.set(id, html)),saveCodeAnimationJobRecord: vi.fn(async (job) => codeAnimationRecords.set(job.id, job)),+ deleteCodeAnimationJobRecord: vi.fn(async (id) => codeAnimationRecords.delete(id)),+ codeAnimationJobFiles: vi.fn(async (id) => (codeAnimationHtml.has(id) ? [`/animations/${id}.html`] : [])),codeAnimationPosterPath: (id) => `${process.env.PORTOS_TEST_POSTER_DIR}/${id}.jpg`,codeAnimationPosterVersions: vi.fn(async (ids) => new Map(ids.filter((id) => codeAnimationPosters.has(id)).map((id) => [id, codeAnimationPosters.get(id)]))),}));+vi.mock('../lib/nativeTrash.js', () => ({ moveToNativeTrash: vi.fn(async () => {}) }));vi.mock('../services/codeAnimation/poster.js', () => ({captureCodeAnimationPoster: vi.fn(async (id) => {writeFileSync(`${process.env.PORTOS_TEST_POSTER_DIR}/${id}.jpg`, 'jpeg-bytes');@@ -81,6 +84,7 @@ vi.mock('../services/trackAlbumMembership.js', () => ({}));import { emitCodeAnimationChanged } from '../services/socket.js';+import { moveToNativeTrash } from '../lib/nativeTrash.js';import { isEngineHealthy } from '../services/pipeline/musicGen.js';import { queueMusicGeneration } from '../services/musicGeneration.js';import { createTrackWithAlbum } from '../services/trackAlbumMembership.js';@@ -183,6 +187,34 @@ describe('Code Animation fast-export audio notes', () => {});});+describe('DELETE /api/code-animation/jobs/:id', () => {+ const id = '00000000-0000-4000-8000-000000000004';+ const finished = { id, status: 'completed', title: 'Station boot', input: {}, frame: { durationSeconds: 20 } };++ it('moves the files to the Trash before removing the gallery item', async () => {+ codeAnimationRecords.set(id, finished);+ codeAnimationHtml.set(id, '<!doctype html>');+ const app = makeApp();+ const res = await request(app).delete(`/api/code-animation/jobs/${id}`);+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ id, deleted: true });+ expect(moveToNativeTrash).toHaveBeenCalledWith([`/animations/${id}.html`]);+ expect(codeAnimationRecords.has(id)).toBe(false);+ expect(emitCodeAnimationChanged).toHaveBeenCalledWith(id, 'deleted');+ expect((await request(app).delete(`/api/code-animation/jobs/${id}`)).status).toBe(404);+ });++ it('keeps the item when the Trash refuses its files', async () => {+ codeAnimationRecords.set(id, finished);+ codeAnimationHtml.set(id, '<!doctype html>');+ moveToNativeTrash.mockRejectedValueOnce(Object.assign(new Error('refused'), { code: 'TRASH_REFUSED' }));+ const res = await request(makeApp()).delete(`/api/code-animation/jobs/${id}`);+ expect(res.status).toBe(500);+ expect(res.body.code).toBe('CODE_ANIMATION_TRASH_FAILED');+ expect(codeAnimationRecords.has(id)).toBe(true);+ });+});+describe('POST /api/code-animation/:id/soundtrack', () => {const id = '00000000-0000-4000-8000-000000000002';const finished = { id, status: 'completed', title: 'Lantern', input: { soundtrack: 'none' },diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.jsindex f64c9ce924..6682facaa1 100644--- a/server/services/codeAnimation/index.js+++ b/server/services/codeAnimation/index.js@@ -26,6 +26,8 @@ import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js'import { SUPPORTED_AUDIO_EXTENSIONS } from '../pipeline/musicLibrary.js';import { resolveMoodBoardStyleSource as resolveMoodBoard, resolveUniverseStyleSource as resolveUniverse } from '../creativeStyleSources.js';import {+ codeAnimationJobFiles,+ deleteCodeAnimationJobRecord,getCodeAnimationJobRecord,isCodeAnimationJobId,listCodeAnimationJobRecords,@@ -378,6 +380,33 @@ async function reconcileJob(job) {return interrupted;}+/**+ * Delete a gallery item. Its HTML and poster go to the system Trash (Finder+ * Put Back on macOS) before the row is removed, so a refused trash leaves the+ * item intact. Exports in Media History and its soundtrack track are separate+ * library items and stay.+ */+export async function deleteCodeAnimationJob(id, { moveToTrash } = {}) {+ const job = await getCodeAnimationJobRecord(id);+ if (!job) throw new ServerError('Code Animation job not found', { status: 404, code: 'NOT_FOUND' });+ if (job.status === 'running' && activeJobs.has(id)) {+ throw new ServerError('This animation is still generating. Delete it once it finishes.', { status: 409, code: 'CODE_ANIMATION_RUNNING' });+ }+ const files = await codeAnimationJobFiles(id);+ if (files.length) {+ const trash = moveToTrash || (await import('../../lib/nativeTrash.js')).moveToNativeTrash;+ await trash(files).catch((error) => {+ throw new ServerError(`Could not move the animation files to the Trash (${error.code || error.message}). Nothing was deleted.`, {+ status: 500, code: 'CODE_ANIMATION_TRASH_FAILED',+ });+ });+ }+ await deleteCodeAnimationJobRecord(id);+ emitCodeAnimationChanged(id, 'deleted');+ console.log(`🗑️ Code animation ${id.slice(0, 8)} deleted (${files.length} file(s) to Trash)`);+ return { id, deleted: true };+}+export async function listCodeAnimationJobs() {const records = await listCodeAnimationJobRecords();return Promise.all(records.map(async (job) => {diff --git a/server/services/codeAnimation/jobStore.js b/server/services/codeAnimation/jobStore.jsindex 481bab8914..38f988f77c 100644--- a/server/services/codeAnimation/jobStore.js+++ b/server/services/codeAnimation/jobStore.js@@ -87,6 +87,20 @@ export async function saveCodeAnimationJobRecord(job) {return job;}+/** Remove the job's row; the audit trigger keeps a copy of it. */+export async function deleteCodeAnimationJobRecord(id) {+ if (!isCodeAnimationJobId(id)) return false;+ const { rowCount } = await query('DELETE FROM code_animation_jobs WHERE id = $1', [id]);+ return rowCount > 0;+}++/** The job's on-disk files (HTML, poster) that exist. */+export async function codeAnimationJobFiles(id) {+ const paths = [htmlPath(id), codeAnimationPosterPath(id)];+ const found = await Promise.all(paths.map(async (path) => ((await stat(path).catch(() => null))?.isFile() ? path : null)));+ return found.filter(Boolean);+}+export async function saveCodeAnimationHtml(id, html) {const destination = htmlPath(id);await atomicWrite(destination, html);