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
feat: manage and publish game artwork
[._.]/ Adam Eivyfa77d564c346
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 525e596213..897a2cecee 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -41,6 +41,7 @@- **Agy's model field is now labeled for what it actually selects, and can be overridden per render.** The Image Gen settings field was labeled "Image model" while listing Gemini agent models, which read as the wrong list being loaded. It isn't: `agy models` is the catalog of *agent* models the CLI's `--model` flag accepts, and that agent is what drives the built-in `generate_image` tool. Agy exposes no knob for the underlying image model — its `generate_image` takes prompt, image name, aspect ratio, and reference paths and nothing else — so there is no `imagen-*` option to offer, and passing one makes agy exit before it generates. The field is now "Default agent model" with that explanation, and the Image Gen page adds an **Agent model** picker so a single queue item can run on a different agent model than the saved default without a settings round-trip. Leaving it blank inherits the Settings value; a pinned model that Google later drops from the catalog falls back to the default instead of failing the render. The retry editor on a failed Agy job now edits that same model field (it was bound to the local model-id field, which Agy never reads).## Game+- **Game workspaces now manage launch art, biome cards, and other game-facing artwork alongside sprites and music.** Choose any image from the PortOS gallery, assign its design role and game destination, generate a role-specific replacement in Image Gen, preview and edit the binding in place, then publish hash-verified bytes into the managed game with protection against overwriting outside changes; artwork also participates in bundle readiness and AI asset reviews.- **[issue-3228] Game detail workspaces keep asset blockers and controls in reach.** The compact header and section tabs stay pinned while each panel scrolls independently, blocked rows explain how to recover and link directly to surviving Sprite or Music records, and missing, malformed, and deleted music audio now report distinct causes.- **[issue-3177] Added a Game studio for assembling managed-app asset bundles.** Create a Game workspace, bind reusable Sprite records and Music tracks, compile an immutable versioned manifest with SHA-256 asset references, and request persisted AI feedback with any configured provider, model, and supported effort. The new `/game/:id` workspace is reachable from Create, Cmd+K, and voice navigation.- **Game workspaces now stay compact and verify assets before launch.** Bundle, Assets, and Feedback live in separate deep-linkable tabs; large sprite sets use a dense contained grid; imported prop atlases participate in bundles; and a preflight names every missing, stale, or hash-mismatched asset. A game can be started from its workspace only after the current manifest and all bound asset bytes pass verification.diff --git a/client/src/components/games/GameBindings.jsx b/client/src/components/games/GameBindings.jsxindex b279d0cbbd..234c647346 100644--- a/client/src/components/games/GameBindings.jsx+++ b/client/src/components/games/GameBindings.jsx@@ -1,10 +1,64 @@-import { useMemo, useState } from 'react';-import { AlertTriangle, ArrowUpRight, CheckCircle2, HelpCircle, Music2, PersonStanding, Plus, Unlink } from 'lucide-react';+import { useEffect, useMemo, useState } from 'react';+import {+ AlertTriangle,+ ArrowUpRight,+ CheckCircle2,+ HelpCircle,+ Image as ImageIcon,+ Music2,+ PersonStanding,+ Plus,+ Save,+ Send,+ Sparkles,+ Unlink,+} from 'lucide-react';import { Link } from 'react-router-dom';import Pill from '../ui/Pill.jsx';const selectClass = 'w-full min-h-[44px] rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white';const actionClass = 'inline-flex min-h-[44px] items-center justify-center gap-2 rounded-lg bg-port-accent px-3 py-2 text-sm font-medium text-white disabled:opacity-50';+const inputClass = 'w-full min-h-[44px] rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white';++const ARTWORK_ROLES = [+ {+ id: 'title-key-art',+ label: 'Title key art',+ destinationPath: 'game/assets/art/title/title-key-art.png',+ prompt: 'Premium cinematic 16:9 title-screen key art for a cozy science-fiction homesteading game, painterly stylized realism, rich alien world, sophisticated AAA composition, dark calm negative space for a menu, no text, no logo, no UI.',+ },+ {+ id: 'biome-luminous-wilds',+ label: 'Luminous Wilds',+ destinationPath: 'game/assets/art/biomes/luminous-wilds.png',+ prompt: 'Wide cinematic biome selection artwork for a luminous alien woodland, cyan bioluminescent grove, reflective stream, premium painterly game concept art, no text, no UI.',+ },+ {+ id: 'biome-mineral-steppe',+ label: 'Mineral Steppe',+ destinationPath: 'game/assets/art/biomes/mineral-steppe.png',+ prompt: 'Wide cinematic biome selection artwork for an alien mineral steppe, golden grass, violet crystals, monumental weathered stone arch, premium painterly game concept art, no text, no UI.',+ },+ {+ id: 'biome-tide-meadow',+ label: 'Tide Meadow',+ destinationPath: 'game/assets/art/biomes/tide-meadow.png',+ prompt: 'Wide cinematic biome selection artwork for a tranquil alien tide meadow, turquoise shallows, flowered islands, distant ringed planet, premium painterly game concept art, no text, no UI.',+ },+ {+ id: 'loading-screen',+ label: 'Loading screen',+ destinationPath: 'game/assets/art/loading/loading-screen.png',+ prompt: 'Premium cinematic loading-screen artwork for a cozy science-fiction frontier game, an inviting alien homestead and distant world, painterly stylized realism, no text, no logo, no UI.',+ },+ {+ id: 'other',+ label: 'Other artwork',+ destinationPath: 'game/assets/art/custom/artwork.png',+ prompt: 'Polished production-ready concept artwork for a cozy science-fiction homesteading game, painterly stylized realism, cohesive alien world, no text, no UI.',+ },+];+const roleFor = (role) => ARTWORK_ROLES.find((entry) => entry.id === role) || ARTWORK_ROLES.at(-1);// Sprites and music share this mapping so a new status can't render one way in// one list and another in the other. Three outcomes, deliberately distinct:@@ -132,19 +186,142 @@ function BindingSection({);}+function ArtworkCard({+ binding,+ image,+ health,+ busy,+ onUpdate,+ onPublish,+ onUnbind,+}) {+ const [label, setLabel] = useState(binding.label);+ const [role, setRole] = useState(binding.role);+ const [destinationPath, setDestinationPath] = useState(binding.destinationPath);+ useEffect(() => {+ setLabel(binding.label);+ setRole(binding.role);+ setDestinationPath(binding.destinationPath);+ }, [binding]);+ const dirty = label.trim() !== binding.label+ || role !== binding.role+ || destinationPath.trim() !== binding.destinationPath;+ const publicationCurrent = health?.publicationStatus === 'current';+ return (+ <article className="overflow-hidden rounded-xl border border-port-border bg-port-bg/55">+ <div className="relative aspect-[16/7] overflow-hidden bg-black/30">+ {image?.path ? (+ <img+ src={image.path}+ alt={`${binding.label} preview`}+ className="h-full w-full object-cover transition-transform duration-500 hover:scale-[1.02]"+ />+ ) : (+ <div className="flex h-full items-center justify-center text-sm text-gray-500">Gallery image unavailable</div>+ )}+ <div className="absolute inset-x-0 bottom-0 flex items-end justify-between gap-2 bg-gradient-to-t from-black/90 to-transparent px-3 pb-2 pt-8">+ <div className="min-w-0">+ <div className="truncate text-sm font-semibold text-white">{binding.label}</div>+ <div className="truncate text-[11px] uppercase tracking-[0.16em] text-cyan-200">{roleFor(binding.role).label}</div>+ </div>+ <Pill tone={publicationCurrent ? 'success' : 'warning'} bordered={false}>+ {publicationCurrent ? 'Published' : 'Publish pending'}+ </Pill>+ </div>+ </div>+ <div className="grid gap-3 p-3 sm:grid-cols-2">+ <div>+ <label htmlFor={`art-label-${binding.id}`} className="mb-1 block text-xs text-gray-400">Display name</label>+ <input+ id={`art-label-${binding.id}`}+ value={label}+ maxLength={120}+ onChange={(event) => setLabel(event.target.value)}+ className={inputClass}+ />+ </div>+ <div>+ <label htmlFor={`art-role-${binding.id}`} className="mb-1 block text-xs text-gray-400">Design role</label>+ <select+ id={`art-role-${binding.id}`}+ value={role}+ onChange={(event) => setRole(event.target.value)}+ className={selectClass}+ >+ {ARTWORK_ROLES.map((entry) => <option key={entry.id} value={entry.id}>{entry.label}</option>)}+ </select>+ </div>+ <div className="sm:col-span-2">+ <label htmlFor={`art-dest-${binding.id}`} className="mb-1 block text-xs text-gray-400">Game destination</label>+ <input+ id={`art-dest-${binding.id}`}+ value={destinationPath}+ maxLength={500}+ onChange={(event) => setDestinationPath(event.target.value)}+ className={`${inputClass} font-mono text-xs`}+ />+ </div>+ </div>+ <div className="flex flex-wrap gap-2 border-t border-port-border px-3 py-2.5">+ <button+ type="button"+ disabled={busy || !dirty || !label.trim() || !destinationPath.trim()}+ onClick={() => onUpdate(binding.id, {+ label: label.trim(),+ role,+ destinationPath: destinationPath.trim(),+ })}+ className="inline-flex min-h-[40px] items-center gap-2 rounded-lg border border-port-border px-3 text-xs font-medium text-gray-200 hover:border-port-accent/60 disabled:opacity-40"+ >+ <Save className="h-3.5 w-3.5" aria-hidden="true" />+ Save details+ </button>+ <button+ type="button"+ disabled={busy || dirty}+ onClick={() => onPublish(binding.id)}+ title={dirty ? 'Save destination changes before publishing' : undefined}+ className="inline-flex min-h-[40px] items-center gap-2 rounded-lg bg-port-accent px-3 text-xs font-semibold text-white disabled:opacity-40"+ >+ <Send className="h-3.5 w-3.5" aria-hidden="true" />+ {publicationCurrent ? 'Republish' : 'Publish to game'}+ </button>+ <button+ type="button"+ disabled={busy}+ onClick={() => onUnbind(binding.id)}+ className="ml-auto inline-flex min-h-[40px] items-center gap-2 rounded-lg px-3 text-xs text-gray-400 hover:text-port-error disabled:opacity-40"+ >+ <Unlink className="h-3.5 w-3.5" aria-hidden="true" />+ Unbind+ </button>+ </div>+ </article>+ );+}+export default function GameBindings({game,sprites,tracks,+ gallery = [],integrity,busy,onBindSprite,onUnbindSprite,onBindMusic,onUnbindMusic,+ onBindArtwork,+ onUpdateArtwork,+ onPublishArtwork,+ onUnbindArtwork,}) {const [spriteId, setSpriteId] = useState('');const [trackId, setTrackId] = useState('');+ const [artworkFilename, setArtworkFilename] = useState('');+ const [artworkRole, setArtworkRole] = useState(ARTWORK_ROLES[0].id);+ const [artworkLabel, setArtworkLabel] = useState(ARTWORK_ROLES[0].label);+ const [artworkDestination, setArtworkDestination] = useState(ARTWORK_ROLES[0].destinationPath);const spriteMap = useMemo(() => new Map(sprites.map((sprite) => [sprite.id, sprite])), [sprites]);const trackMap = useMemo(() => new Map(tracks.map((track) => [track.id, track])), [tracks]);const spriteIntegrity = useMemo(() => new Map(@@ -153,6 +330,9 @@ export default function GameBindings({const musicIntegrity = useMemo(() => new Map((integrity?.assets?.music || []).map((asset) => [asset.bindingId, asset]),), [integrity]);+ const artworkIntegrity = useMemo(() => new Map(+ (integrity?.assets?.artwork || []).map((asset) => [asset.bindingId, asset]),+ ), [integrity]);const spriteIssues = useMemo(() => new Map((integrity?.issues || []).filter((issue) => issue.assetType === 'sprite')@@ -171,6 +351,8 @@ export default function GameBindings({const availableTracks = tracks.filter((track) => !boundTrackIds.has(track.id)).map((track) => ({ id: track.id, label: `${track.title}${track.audioFilename ? '' : ' · no audio yet'}` }));+ const galleryMap = useMemo(() => new Map(gallery.map((image) => [image.filename, image])), [gallery]);+ const selectedArtwork = galleryMap.get(artworkFilename);const addSprite = async () => {if (!spriteId) return;@@ -180,6 +362,21 @@ export default function GameBindings({if (!trackId) return;if (await onBindMusic(trackId)) setTrackId('');};+ const chooseArtworkRole = (nextRole) => {+ const next = roleFor(nextRole);+ setArtworkRole(nextRole);+ setArtworkLabel(next.label);+ setArtworkDestination(next.destinationPath);+ };+ const addArtwork = async () => {+ if (!artworkFilename || !artworkLabel.trim() || !artworkDestination.trim()) return;+ if (await onBindArtwork({+ imageFilename: artworkFilename,+ label: artworkLabel.trim(),+ role: artworkRole,+ destinationPath: artworkDestination.trim(),+ })) setArtworkFilename('');+ };return (<div className="grid gap-4 lg:grid-cols-2">@@ -262,6 +459,121 @@ export default function GameBindings({</ul>) : null}</BindingSection>++ <section className="rounded-xl border border-port-border bg-port-card p-4 lg:col-span-2">+ <div className="flex flex-col justify-between gap-3 sm:flex-row sm:items-start">+ <div>+ <div className="flex items-center gap-2">+ <ImageIcon className="h-5 w-5 text-port-accent" aria-hidden="true" />+ <h2 className="font-semibold text-white">World & interface artwork</h2>+ <Pill tone="muted" bordered={false}>{game.artworkBindings?.length || 0}</Pill>+ </div>+ <p className="mt-1 max-w-2xl text-sm text-gray-400">+ Assign gallery images to a design role, preview them here, and publish verified bytes into the managed game.+ </p>+ </div>+ <Link+ to={`/media/image?prompt=${encodeURIComponent(roleFor(artworkRole).prompt)}`}+ className="inline-flex min-h-[44px] shrink-0 items-center justify-center gap-2 rounded-lg border border-port-accent/50 bg-port-accent/10 px-3 py-2 text-sm font-medium text-port-accent hover:bg-port-accent/20"+ >+ <Sparkles className="h-4 w-4" aria-hidden="true" />+ Generate for this role+ </Link>+ </div>++ <div className="mt-4 grid gap-3 rounded-xl border border-port-border bg-port-bg/35 p-3 lg:grid-cols-[minmax(0,1.3fr)_minmax(180px,.7fr)]">+ <div className="grid gap-3 sm:grid-cols-2">+ <div>+ <label htmlFor="game-artwork-picker" className="mb-1 block text-xs text-gray-400">Gallery image</label>+ <select+ id="game-artwork-picker"+ value={artworkFilename}+ onChange={(event) => setArtworkFilename(event.target.value)}+ className={selectClass}+ disabled={busy || gallery.length === 0}+ >+ <option value="">{gallery.length ? 'Select artwork…' : 'No gallery images available'}</option>+ {gallery.map((image) => (+ <option key={image.filename} value={image.filename}>+ {image.prompt?.slice(0, 70) || image.filename}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="game-artwork-role" className="mb-1 block text-xs text-gray-400">Design role</label>+ <select+ id="game-artwork-role"+ value={artworkRole}+ onChange={(event) => chooseArtworkRole(event.target.value)}+ className={selectClass}+ disabled={busy}+ >+ {ARTWORK_ROLES.map((entry) => <option key={entry.id} value={entry.id}>{entry.label}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor="game-artwork-label" className="mb-1 block text-xs text-gray-400">Display name</label>+ <input+ id="game-artwork-label"+ value={artworkLabel}+ maxLength={120}+ onChange={(event) => setArtworkLabel(event.target.value)}+ className={inputClass}+ />+ </div>+ <div>+ <label htmlFor="game-artwork-destination" className="mb-1 block text-xs text-gray-400">Game destination</label>+ <input+ id="game-artwork-destination"+ value={artworkDestination}+ maxLength={500}+ onChange={(event) => setArtworkDestination(event.target.value)}+ className={`${inputClass} font-mono text-xs`}+ />+ </div>+ <button+ type="button"+ disabled={busy || !artworkFilename || !artworkLabel.trim() || !artworkDestination.trim()}+ onClick={addArtwork}+ className={`${actionClass} sm:col-span-2 sm:justify-self-start`}+ >+ <Plus className="h-4 w-4" aria-hidden="true" />+ Bind artwork+ </button>+ </div>+ <div className="overflow-hidden rounded-lg border border-port-border bg-black/25">+ {selectedArtwork?.path ? (+ <img src={selectedArtwork.path} alt="Selected gallery preview" className="h-full min-h-40 w-full object-cover" />+ ) : (+ <div className="flex h-full min-h-40 items-center justify-center px-6 text-center text-sm text-gray-500">+ Select a gallery image to preview the game-facing composition.+ </div>+ )}+ </div>+ </div>++ {(game.artworkBindings?.length || 0) > 0 ? (+ <div className="mt-4 grid gap-4 xl:grid-cols-2">+ {game.artworkBindings.map((binding) => (+ <ArtworkCard+ key={binding.id}+ binding={binding}+ image={galleryMap.get(binding.imageFilename)}+ health={artworkIntegrity.get(binding.id)}+ busy={busy}+ onUpdate={onUpdateArtwork}+ onPublish={onPublishArtwork}+ onUnbind={onUnbindArtwork}+ />+ ))}+ </div>+ ) : (+ <p className="mt-4 text-sm text-gray-500">+ No world or interface artwork is bound yet. Start with title key art to give the launch experience a strong visual identity.+ </p>+ )}+ </section></div>);}diff --git a/client/src/components/games/GameBindings.test.jsx b/client/src/components/games/GameBindings.test.jsxindex dcb923f91e..5f96f4cdb5 100644--- a/client/src/components/games/GameBindings.test.jsx+++ b/client/src/components/games/GameBindings.test.jsx@@ -11,6 +11,14 @@ const renderBindings = () => render(game={{spriteBindings: [{ spriteId: 'deleted-sprite' }],musicBindings: [{ id: 'binding-1', trackId: 'theme/one' }],+ artworkBindings: [{+ id: 'artwork-1',+ imageFilename: 'title.png',+ label: 'Title Key Art',+ role: 'title-key-art',+ destinationPath: 'game/assets/art/title.png',+ publication: null,+ }],}}sprites={[{id: 'deleted-sprite',@@ -23,6 +31,11 @@ const renderBindings = () => render(title: 'Example Theme',audioFilename: 'example-theme.ogg',}]}+ gallery={[{+ filename: 'title.png',+ path: '/data/images/title.png',+ prompt: 'Cinematic alien valley',+ }]}integrity={{issues: [{@@ -49,6 +62,12 @@ const renderBindings = () => render(status: 'blocked',message: 'Audio path invalid',}],+ artwork: [{+ bindingId: 'artwork-1',+ status: 'ready',+ publicationStatus: 'pending',+ message: 'Gallery source verified · publish pending',+ }],},}}busy={false}@@ -56,6 +75,10 @@ const renderBindings = () => render(onUnbindSprite={noop}onBindMusic={noop}onUnbindMusic={noop}+ onBindArtwork={noop}+ onUpdateArtwork={noop}+ onPublishArtwork={noop}+ onUnbindArtwork={noop}/></MemoryRouter>,);@@ -80,4 +103,14 @@ describe('GameBindings', () => {expect(screen.getByRole('link', { name: 'Open in Music' })).toHaveAttribute('href', '/music/tracks/theme%2Fone');});++ it('previews role-specific artwork and keeps publishing behind saved details', () => {+ renderBindings();+ expect(screen.getByRole('heading', { name: 'World & interface artwork' })).toBeInTheDocument();+ expect(screen.getByRole('img', { name: 'Title Key Art preview' })).toHaveAttribute('src', '/data/images/title.png');+ expect(screen.getByText('Publish pending')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Publish to game' })).toBeEnabled();+ expect(screen.getByRole('link', { name: 'Generate for this role' }))+ .toHaveAttribute('href', expect.stringContaining('/media/image?prompt='));+ });});diff --git a/client/src/components/games/GameCompilePanel.jsx b/client/src/components/games/GameCompilePanel.jsxindex 1cf9af78cf..b9b27bedba 100644--- a/client/src/components/games/GameCompilePanel.jsx+++ b/client/src/components/games/GameCompilePanel.jsx@@ -58,6 +58,9 @@ const manageSource = (issue, spriteIds, trackIds) => {to: `/music/tracks/${encodeURIComponent(issue.assetId)}`,};}+ if (issue.assetType === 'artwork') {+ return { label: 'Open image gallery', to: '/media/image' };+ }return null;};@@ -124,7 +127,7 @@ export default function GameCompilePanel({</div></div>- <div className="mt-4 grid gap-3 sm:grid-cols-3">+ <div className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-5"><div className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-sm ${bundleStatus.className}`}><StatusIcon className={`h-4 w-4 shrink-0 ${loadingIntegrity ? 'animate-spin' : ''}`} aria-hidden="true" /><div>@@ -138,6 +141,18 @@ export default function GameCompilePanel({{integrity ? `${integrity.counts.spriteReady} / ${integrity.counts.spriteTotal}` : '—'}</div></div>+ <div className="rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-sm">+ <div className="text-xs text-gray-500">Music readiness</div>+ <div className="font-medium text-white">+ {integrity ? `${integrity.counts.musicReady ?? 0} / ${integrity.counts.musicTotal ?? 0}` : '—'}+ </div>+ </div>+ <div className="rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-sm">+ <div className="text-xs text-gray-500">Artwork readiness</div>+ <div className="font-medium text-white">+ {integrity ? `${integrity.counts.artworkReady ?? 0} / ${integrity.counts.artworkTotal ?? 0}` : '—'}+ </div>+ </div><div className="rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-sm"><div className="text-xs text-gray-500">Verified files</div><div className="font-medium text-white">{integrity?.counts?.verifiedFiles ?? '—'}</div>@@ -204,10 +219,11 @@ export default function GameCompilePanel({)}{current ? (- <dl className="mt-4 grid gap-3 rounded-lg border border-port-border bg-port-bg/50 p-3 text-sm sm:grid-cols-2 lg:grid-cols-4">+ <dl className="mt-4 grid gap-3 rounded-lg border border-port-border bg-port-bg/50 p-3 text-sm sm:grid-cols-2 lg:grid-cols-5"><div><dt className="text-xs text-gray-500">Version</dt><dd className="text-white">v{current.version}</dd></div><div><dt className="text-xs text-gray-500">Sprites</dt><dd className="text-white">{current.spriteCount}</dd></div><div><dt className="text-xs text-gray-500">Music</dt><dd className="text-white">{current.musicCount}</dd></div>+ <div><dt className="text-xs text-gray-500">Artwork</dt><dd className="text-white">{current.artworkCount ?? 0}</dd></div><div><dt className="text-xs text-gray-500">Built</dt><dd className="text-white">{formatDateShort(current.builtAt)}</dd></div><div><dt className="text-xs text-gray-500">Verified files</dt><dd className="text-white">{current.verifiedFileCount ?? '—'}</dd></div><div className="min-w-0 sm:col-span-2 lg:col-span-4">diff --git a/client/src/pages/Game.jsx b/client/src/pages/Game.jsxindex 6c00c959cd..aa99df28ce 100644--- a/client/src/pages/Game.jsx+++ b/client/src/pages/Game.jsx@@ -9,6 +9,7 @@ import GameFeedback from '../components/games/GameFeedback.jsx';import TabPills from '../components/ui/TabPills.jsx';import useDrawerTab from '../hooks/useDrawerTab.js';import {+ bindGameArtwork,bindGameMusic,bindGameSprite,compileGameAssets,@@ -17,13 +18,17 @@ import {getGame,getGameIntegrity,listGames,+ listImageGallery,listSpriteRecords,listTracks,launchNativeApp,+ publishGameArtwork,requestGameFeedback,startApp,+ unbindGameArtwork,unbindGameMusic,unbindGameSprite,+ updateGameArtwork,} from '../services/api.js';import { timeAgo } from '../utils/formatters.js';@@ -34,7 +39,9 @@ const DETAIL_TABS = [id: 'assets',label: 'Assets',icon: Images,- count: (game) => game.spriteBindings.length + game.musicBindings.length,+ count: (game) => game.spriteBindings.length+ + game.musicBindings.length+ + (game.artworkBindings?.length || 0),},{ id: 'feedback', label: 'Feedback', icon: MessageSquare, count: (game) => game.feedbackHistory.length },];@@ -48,6 +55,7 @@ export default function Game() {const [apps, setApps] = useState([]);const [sprites, setSprites] = useState([]);const [tracks, setTracks] = useState([]);+ const [gallery, setGallery] = useState([]);// Integrity is keyed by the game it describes, never stored bare. `/game/A` →// `/game/B` reuses the same route, so the component does NOT remount: unkeyed// state would render B's panel with A's verdict — enabling "Start game" for a@@ -68,15 +76,17 @@ export default function Game() {getApps(silent),listSpriteRecords(silent),listTracks(silent),+ listImageGallery(silent),]).catch(() => null);if (!result) {toast.error('Failed to load the Game studio');} else {- const [gameRows, appRows, spriteRows, trackRows] = result;+ const [gameRows, appRows, spriteRows, trackRows, galleryRows] = result;setGames(Array.isArray(gameRows) ? gameRows : []);setApps((Array.isArray(appRows) ? appRows : []).filter((app) => !app.archived));setSprites(Array.isArray(spriteRows) ? spriteRows : []);setTracks(Array.isArray(trackRows) ? trackRows : []);+ setGallery((Array.isArray(galleryRows) ? galleryRows : []).filter((image) => !image.hidden));}setLoading(false);}, []);@@ -192,6 +202,21 @@ export default function Game() {return true;};+ const publishArtwork = async (bindingId) => {+ setBusy(`artwork-publish-${bindingId}`);+ const result = await publishGameArtwork(game.id, bindingId, {}, silent).catch(() => null);+ setBusy('');+ if (!result?.game) {+ toast.error('Artwork publish was refused; the destination may contain unmanaged changes');+ return false;+ }+ replaceGame(result.game);+ setCompileError('');+ await refreshIntegrity();+ toast.success(result.publication?.wrote ? 'Artwork published to the game' : 'Artwork is already current');+ return true;+ };+if (loading) {return <div className="py-12 text-center text-sm text-gray-400">Loading Game studio…</div>;}@@ -266,7 +291,7 @@ export default function Game() {<div className="font-semibold text-white">{entry.name}</div><div className="mt-1 text-sm text-gray-400">{linkedApp?.name || 'Managed app unavailable'}</div><div className="mt-3 text-xs text-gray-500">- {entry.spriteBindings.length} sprites · {entry.musicBindings.length} tracks · updated {timeAgo(entry.updatedAt)}+ {entry.spriteBindings.length} sprites · {entry.musicBindings.length} tracks · {entry.artworkBindings?.length || 0} artwork · updated {timeAgo(entry.updatedAt)}</div></Link></li>@@ -284,7 +309,7 @@ export default function Game() {// Binding actions are namespaced so a new non-binding action (compile,// feedback, launch, …) doesn't have to be remembered in an exclusion list.- const bindingBusy = /^(un)?bind-/.test(busy);+ const bindingBusy = /^(un)?bind-|^artwork-/.test(busy);return (<div className="flex h-full min-h-0 flex-col"><header className="flex shrink-0 flex-col justify-between gap-2 border-b border-port-border px-4 py-3 sm:flex-row sm:items-center">@@ -307,6 +332,8 @@ export default function Game() {<span>{game.spriteBindings.length} sprites</span><span aria-hidden="true">·</span><span>{game.musicBindings.length} {game.musicBindings.length === 1 ? 'music track' : 'music tracks'}</span>+ <span aria-hidden="true">·</span>+ <span>{game.artworkBindings?.length || 0} artwork</span></div></header>@@ -346,12 +373,29 @@ export default function Game() {game={game}sprites={sprites}tracks={tracks}+ gallery={gallery}integrity={integrity}busy={bindingBusy}onBindSprite={(spriteId) => mutate('bind-sprite', () => bindGameSprite(game.id, spriteId, silent), 'Sprite bound')}onUnbindSprite={(spriteId) => mutate('unbind-sprite', () => unbindGameSprite(game.id, spriteId, silent), 'Sprite unbound')}onBindMusic={(trackId) => mutate('bind-music', () => bindGameMusic(game.id, trackId, silent), 'Music bound')}onUnbindMusic={(bindingId) => mutate('unbind-music', () => unbindGameMusic(game.id, bindingId, silent), 'Music unbound')}+ onBindArtwork={(binding) => mutate(+ 'bind-artwork',+ () => bindGameArtwork(game.id, binding, silent),+ 'Artwork bound',+ )}+ onUpdateArtwork={(bindingId, patch) => mutate(+ `artwork-update-${bindingId}`,+ () => updateGameArtwork(game.id, bindingId, patch, silent),+ 'Artwork details saved',+ )}+ onPublishArtwork={publishArtwork}+ onUnbindArtwork={(bindingId) => mutate(+ 'unbind-artwork',+ () => unbindGameArtwork(game.id, bindingId, silent),+ 'Artwork unbound',+ )}/></div>)}diff --git a/client/src/pages/Game.test.jsx b/client/src/pages/Game.test.jsxindex a8813ff9e8..66fb2eb1d9 100644--- a/client/src/pages/Game.test.jsx+++ b/client/src/pages/Game.test.jsx@@ -26,6 +26,7 @@ vi.mock('../services/api.js', () => ({name: 'Verified Game',spriteBindings: [{ spriteId: 'hero' }],musicBindings: [],+ artworkBindings: [],feedbackHistory: [],compiledManifest: {version: 2,@@ -43,6 +44,7 @@ vi.mock('../services/api.js', () => ({name: 'Unbuilt Game',spriteBindings: [],musicBindings: [],+ artworkBindings: [],feedbackHistory: [],compiledManifest: null,updatedAt: '2026-07-28T12:00:00.000Z',@@ -51,6 +53,7 @@ vi.mock('../services/api.js', () => ({getApps: vi.fn(async () => [{ id: 'app-1', name: 'Example App' }]),listSpriteRecords: vi.fn(async () => [{ id: 'hero', name: 'Hero', kind: 'character', status: 'ready' }]),listTracks: vi.fn(async () => []),+ listImageGallery: vi.fn(async () => []),getGameIntegrity: vi.fn(async (id) => {api.integrityCalls.push(id);return api.integrityByGame[id] ?? null;@@ -61,8 +64,12 @@ vi.mock('../services/api.js', () => ({requestGameFeedback: vi.fn(),bindGameSprite: vi.fn(),bindGameMusic: vi.fn(),+ bindGameArtwork: vi.fn(),+ updateGameArtwork: vi.fn(),+ publishGameArtwork: vi.fn(),unbindGameSprite: vi.fn(),unbindGameMusic: vi.fn(),+ unbindGameArtwork: vi.fn(),startApp: vi.fn(),launchNativeApp: vi.fn(),}));@@ -87,16 +94,32 @@ describe('Game page', () => {canLaunch: true,bundle: { status: 'current' },issues: [],- counts: { spriteReady: 1, spriteTotal: 1, musicReady: 0, musicTotal: 0, verifiedFiles: 2 },- assets: { sprites: [], music: [] },+ counts: {+ spriteReady: 1,+ spriteTotal: 1,+ musicReady: 0,+ musicTotal: 0,+ artworkReady: 0,+ artworkTotal: 0,+ verifiedFiles: 2,+ },+ assets: { sprites: [], music: [], artwork: [] },},'unbuilt-game': {readyToCompile: true,canLaunch: false,bundle: { status: 'missing' },issues: [],- counts: { spriteReady: 0, spriteTotal: 0, musicReady: 0, musicTotal: 0, verifiedFiles: 0 },- assets: { sprites: [], music: [] },+ counts: {+ spriteReady: 0,+ spriteTotal: 0,+ musicReady: 0,+ musicTotal: 0,+ artworkReady: 0,+ artworkTotal: 0,+ verifiedFiles: 0,+ },+ assets: { sprites: [], music: [], artwork: [] },},};});diff --git a/client/src/services/apiGames.js b/client/src/services/apiGames.jsindex bc0f441760..146ada19c7 100644--- a/client/src/services/apiGames.js+++ b/client/src/services/apiGames.js@@ -42,6 +42,26 @@ export const unbindGameMusic = (id, bindingId, options = {}) => request({ method: 'DELETE', ...options },);+export const bindGameArtwork = (id, binding, options = {}) => request(+ `/games/${encodeURIComponent(id)}/artwork`,+ { method: 'POST', body: JSON.stringify(binding), ...options },+);++export const updateGameArtwork = (id, bindingId, patch, options = {}) => request(+ `/games/${encodeURIComponent(id)}/artwork/${encodeURIComponent(bindingId)}`,+ { method: 'PATCH', body: JSON.stringify(patch), ...options },+);++export const unbindGameArtwork = (id, bindingId, options = {}) => request(+ `/games/${encodeURIComponent(id)}/artwork/${encodeURIComponent(bindingId)}`,+ { method: 'DELETE', ...options },+);++export const publishGameArtwork = (id, bindingId, body = {}, options = {}) => request(+ `/games/${encodeURIComponent(id)}/artwork/${encodeURIComponent(bindingId)}/publish`,+ { method: 'POST', body: JSON.stringify(body), ...options },+);+export const compileGameAssets = (id, options = {}) => request(`/games/${encodeURIComponent(id)}/compile`,{ method: 'POST', ...options },diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.jsindex 875da236d6..9c5f0ff59e 100644--- a/client/src/services/apiImageVideo.js+++ b/client/src/services/apiImageVideo.js@@ -24,7 +24,7 @@ export const repairImageModel = (modelId, { deep = false } = {}) => request(`/imsilent: true,});export const listLoras = () => request('/image-gen/loras');-export const listImageGallery = () => request('/image-gen/gallery');+export const listImageGallery = (options = {}) => request('/image-gen/gallery', options);export const getActiveImageJob = () => request('/image-gen/active');// cancelImageGen({ all: true }) cancels every queued/running image job.// cancelImageGen({ jobId }) cancels a specific job. Plain cancelImageGen()diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 059a9c283b..acf2012ab8 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -343,6 +343,46 @@ export const gameMusicBindingSchema = z.object({trackId: gameAssetIdSchema,}).strict();+export const GAME_ARTWORK_ROLES = [+ 'title-key-art',+ 'biome-luminous-wilds',+ 'biome-mineral-steppe',+ 'biome-tide-meadow',+ 'loading-screen',+ 'other',+];++const gameArtworkFilenameSchema = z.string()+ .trim()+ .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/i, 'must be a gallery PNG filename')+ .max(255);+const gameArtworkDestinationSchema = z.string()+ .trim()+ .min(1)+ .max(500)+ .regex(/\.png$/i, 'must end in .png')+ .refine((value) => !value.startsWith('/') && !value.includes('\\'), 'must be a repo-relative path')+ .refine((value) => !value.split('/').includes('..'), 'must not traverse outside the app repository');++export const gameArtworkBindingSchema = z.object({+ imageFilename: gameArtworkFilenameSchema,+ label: z.string().trim().min(1).max(120),+ role: z.enum(GAME_ARTWORK_ROLES),+ destinationPath: gameArtworkDestinationSchema,+}).strict();++export const gameArtworkBindingUpdateSchema = z.object({+ label: z.string().trim().min(1).max(120).optional(),+ role: z.enum(GAME_ARTWORK_ROLES).optional(),+ destinationPath: gameArtworkDestinationSchema.optional(),+}).strict().refine((patch) => Object.keys(patch).length > 0, {+ message: 'at least one field is required',+});++export const gameArtworkPublishSchema = z.object({+ acknowledgeOverwrite: z.boolean().optional(),+}).strict();+export const gameFeedbackSchema = z.object({providerId: z.string().trim().min(1).max(128),model: z.string().trim().min(1).max(256).optional(),diff --git a/server/routes/games.js b/server/routes/games.jsindex 7e54cda349..d50c6aafb4 100644--- a/server/routes/games.js+++ b/server/routes/games.js@@ -6,6 +6,9 @@ import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import {gameCreateSchema,+ gameArtworkBindingSchema,+ gameArtworkBindingUpdateSchema,+ gameArtworkPublishSchema,gameFeedbackSchema,gameMusicBindingSchema,gameSpriteBindingSchema,@@ -14,6 +17,7 @@ import {} from '../lib/validation.js';import {bindMusic,+ bindArtwork,bindSprite,compileGameAssets,createGame,@@ -21,9 +25,12 @@ import {getGame,getGameIntegrity,listGames,+ publishGameArtwork,requestGameFeedback,unbindMusic,+ unbindArtwork,unbindSprite,+ updateArtwork,updateGame,} from '../services/games/index.js';@@ -77,6 +84,25 @@ router.delete('/:id/music/:bindingId', asyncHandler(async (req, res) => {res.json(await unbindMusic(req.params.id, req.params.bindingId));}));+router.post('/:id/artwork', asyncHandler(async (req, res) => {+ const binding = validateRequest(gameArtworkBindingSchema, req.body);+ res.status(201).json(await bindArtwork(req.params.id, binding));+}));++router.patch('/:id/artwork/:bindingId', asyncHandler(async (req, res) => {+ const patch = validateRequest(gameArtworkBindingUpdateSchema, req.body);+ res.json(await updateArtwork(req.params.id, req.params.bindingId, patch));+}));++router.delete('/:id/artwork/:bindingId', asyncHandler(async (req, res) => {+ res.json(await unbindArtwork(req.params.id, req.params.bindingId));+}));++router.post('/:id/artwork/:bindingId/publish', asyncHandler(async (req, res) => {+ const options = validateRequest(gameArtworkPublishSchema, req.body || {});+ res.json(await publishGameArtwork(req.params.id, req.params.bindingId, options));+}));+router.post('/:id/compile', asyncHandler(async (req, res) => {res.json(await compileGameAssets(req.params.id));}));diff --git a/server/routes/games.test.js b/server/routes/games.test.jsindex bc3d74d2b2..57b8bb01bf 100644--- a/server/routes/games.test.js+++ b/server/routes/games.test.js@@ -4,6 +4,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';import { request } from '../lib/testHelper.js';vi.mock('../services/games/index.js', () => ({+ bindArtwork: vi.fn(),bindMusic: vi.fn(),bindSprite: vi.fn(),compileGameAssets: vi.fn(),@@ -12,9 +13,12 @@ vi.mock('../services/games/index.js', () => ({getGame: vi.fn(),getGameIntegrity: vi.fn(),listGames: vi.fn(async () => []),+ publishGameArtwork: vi.fn(),requestGameFeedback: vi.fn(),unbindMusic: vi.fn(),+ unbindArtwork: vi.fn(),unbindSprite: vi.fn(),+ updateArtwork: vi.fn(),updateGame: vi.fn(),}));@@ -49,6 +53,45 @@ describe('Game routes', () => {expect(games.bindSprite).not.toHaveBeenCalled();});+ it('binds and publishes role-specific gallery artwork', async () => {+ const updated = { id: 'game-1', artworkBindings: [{ id: 'artwork-1' }] };+ games.bindArtwork.mockResolvedValueOnce(updated);+ const binding = {+ imageFilename: 'title-key-art.png',+ label: 'Title Key Art',+ role: 'title-key-art',+ destinationPath: 'game/assets/art/title/title-key-art.png',+ };+ const bindResponse = await request(makeApp())+ .post('/api/games/game-1/artwork')+ .send(binding);+ expect(bindResponse.status).toBe(201);+ expect(games.bindArtwork).toHaveBeenCalledWith('game-1', binding);++ games.publishGameArtwork.mockResolvedValueOnce({+ game: updated,+ publication: { bindingId: 'artwork-1', wrote: true },+ });+ const publishResponse = await request(makeApp())+ .post('/api/games/game-1/artwork/artwork-1/publish')+ .send({});+ expect(publishResponse.status).toBe(200);+ expect(games.publishGameArtwork).toHaveBeenCalledWith('game-1', 'artwork-1', {});+ });++ it('rejects artwork destinations that escape the managed repository', async () => {+ const response = await request(makeApp())+ .post('/api/games/game-1/artwork')+ .send({+ imageFilename: 'title.png',+ label: 'Title',+ role: 'title-key-art',+ destinationPath: '../outside.png',+ });+ expect(response.status).toBe(400);+ expect(games.bindArtwork).not.toHaveBeenCalled();+ });+it('compiles a Game bundle', async () => {games.compileGameAssets.mockResolvedValueOnce({ version: 2, created: true });const response = await request(makeApp()).post('/api/games/game-1/compile');diff --git a/server/services/games/README.md b/server/services/games/README.mdindex cf8558f2b5..e3df6bd2fc 100644--- a/server/services/games/README.md+++ b/server/services/games/README.md@@ -1,12 +1,13 @@# Games-The Game studio binds a managed app to reusable Sprite and Music records, compiles immutable versioned asset manifests, and stores user-triggered AI review history.+The Game studio binds a managed app to reusable Sprite, Music, and gallery Artwork records, publishes artwork into the app repository, compiles immutable versioned asset manifests, and stores user-triggered AI review history.| File | Purpose ||---|---|| `store.js` | PostgreSQL/collectionStore dispatcher plus per-Game write serialization and manifest directory paths. || `db.js` | PostgreSQL leaf I/O for `games` JSONB records. |-| `records.js` | Game CRUD, managed-app validation, and sprite/music bind/unbind operations. |+| `records.js` | Game CRUD, managed-app validation, and sprite/music/artwork bind operations. |+| `artwork.js` | Provenance-tracked, drift-guarded gallery-artwork publishing into managed app repositories. || `compile.js` | Deterministic, idempotent asset-manifest compiler with SHA-256 references. || `integrity.js` | Bundle preflight, imported-runtime resolution, and current manifest/source hash verification. || `feedback.js` | Explicitly user-triggered provider/model/effort feedback and history persistence. |diff --git a/server/services/games/artwork.js b/server/services/games/artwork.jsnew file mode 100644index 0000000000..f533816bbf--- /dev/null+++ b/server/services/games/artwork.js@@ -0,0 +1,136 @@+/**+ * Publish gallery artwork into a managed game's repository with provenance and+ * occupied/diverged-destination guards.+ */++import { createHash } from 'crypto';+import { readFile, stat } from 'fs/promises';+import { join, resolve } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';+import { atomicWrite, isPathInsideDir, PATHS } from '../../lib/fileUtils.js';+import { getAppById } from '../apps.js';+import { isDeploying } from '../appDeployer.js';+import { getGame, mutateGame } from './records.js';++const repoPublishTail = createKeyCachedQueue();+const sha256Buffer = (buffer) => createHash('sha256').update(buffer).digest('hex');++const anchorRepoPath = (repoRoot, relPath) => {+ const abs = resolve(repoRoot, relPath);+ if (abs === resolve(repoRoot)+ || relPath.startsWith('/')+ || relPath.includes('\\')+ || !isPathInsideDir(repoRoot, abs)) {+ throw new ServerError('Artwork destination must stay inside the managed app repository', {+ status: 400,+ code: 'INVALID_PUBLISH_PATH',+ });+ }+ return abs;+};++const readIfPresent = (path) => readFile(path).then(+ (buffer) => buffer,+ (error) => {+ if (error?.code === 'ENOENT') return null;+ throw error;+ },+);++export async function publishGameArtwork(+ gameId,+ bindingId,+ { acknowledgeOverwrite = false } = {},+) {+ const game = await getGame(gameId);+ if (!game) throw new ServerError('Game not found', { status: 404, code: 'NOT_FOUND' });+ const binding = game.artworkBindings.find((entry) => entry.id === bindingId);+ if (!binding) throw new ServerError('Artwork binding not found', { status: 404, code: 'NOT_FOUND' });+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/i.test(binding.imageFilename)) {+ throw new ServerError('The bound gallery artwork path is invalid', {+ status: 409,+ code: 'ARTWORK_PATH_INVALID',+ });+ }++ const app = await getAppById(game.appId);+ const repoStat = app?.repoPath ? await stat(app.repoPath).catch(() => null) : null;+ if (!app || !repoStat?.isDirectory()) {+ throw new ServerError('The bound managed app has no accessible repository', {+ status: 409,+ code: 'APP_REPO_MISSING',+ });+ }++ const sourcePath = join(PATHS.images, binding.imageFilename);+ const source = await readIfPresent(sourcePath);+ if (!source) {+ throw new ServerError('The bound gallery artwork is missing', {+ status: 409,+ code: 'ARTWORK_MISSING',+ });+ }+ const sourceSha256 = sha256Buffer(source);+ const repoRoot = resolve(app.repoPath);++ return repoPublishTail(repoRoot, async () => {+ if (isDeploying(app.repoPath)) {+ throw new ServerError(`App ${app.name || app.id} is deploying — retry when it finishes`, {+ status: 409,+ code: 'APP_DEPLOY_IN_PROGRESS',+ });+ }+ const destination = anchorRepoPath(repoRoot, binding.destinationPath);+ const existing = await readIfPresent(destination);+ const existingSha256 = existing ? sha256Buffer(existing) : null;+ const previous = binding.publication?.destinationPath === binding.destinationPath+ ? binding.publication+ : null;+ const occupiedByOtherBytes = existingSha256+ && existingSha256 !== sourceSha256+ && existingSha256 !== previous?.destinationSha256;+ if (occupiedByOtherBytes && !acknowledgeOverwrite) {+ throw new ServerError(+ `${binding.destinationPath} contains bytes PortOS did not publish — confirm the overwrite to replace it.`,+ { status: 409, code: 'PUBLISH_DEST_OCCUPIED' },+ );+ }++ const wrote = existingSha256 !== sourceSha256;+ if (wrote) await atomicWrite(destination, source);+ const publishedAt = new Date().toISOString();+ const updated = await mutateGame(gameId, (current) => {+ if (!current.artworkBindings.some((entry) => entry.id === bindingId)) {+ throw new ServerError('Artwork binding not found', { status: 404, code: 'NOT_FOUND' });+ }+ return {+ ...current,+ artworkBindings: current.artworkBindings.map((entry) => (+ entry.id === bindingId+ ? {+ ...entry,+ publication: {+ sourceSha256,+ destinationSha256: sourceSha256,+ destinationPath: entry.destinationPath,+ publishedAt,+ },+ }+ : entry+ )),+ };+ });+ return {+ game: updated,+ publication: {+ bindingId,+ sourceSha256,+ destinationSha256: sourceSha256,+ destinationPath: binding.destinationPath,+ publishedAt,+ wrote,+ },+ };+ });+}diff --git a/server/services/games/artwork.test.js b/server/services/games/artwork.test.jsnew file mode 100644index 0000000000..62afa29cb0--- /dev/null+++ b/server/services/games/artwork.test.js@@ -0,0 +1,89 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({+ game: null,+ source: Buffer.from('title-art-v1'),+ destination: null,+}));++vi.mock('fs/promises', () => ({+ readFile: vi.fn(async (path) => {+ if (path === '/gallery/title.png') return state.source;+ if (path === '/app/game/assets/art/title.png' && state.destination) return state.destination;+ throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' });+ }),+ stat: vi.fn(async () => ({ isDirectory: () => true })),+}));++vi.mock('../../lib/fileUtils.js', () => ({+ PATHS: { images: '/gallery' },+ atomicWrite: vi.fn(async (path, bytes) => {+ if (path === '/app/game/assets/art/title.png') state.destination = Buffer.from(bytes);+ }),+ isPathInsideDir: vi.fn((dir, candidate) => candidate.startsWith(`${dir}/`)),+}));++vi.mock('../apps.js', () => ({+ getAppById: vi.fn(async () => ({ id: 'app-1', name: 'Example App', repoPath: '/app' })),+}));++vi.mock('../appDeployer.js', () => ({ isDeploying: vi.fn(() => false) }));++vi.mock('./records.js', () => ({+ getGame: vi.fn(async () => state.game),+ mutateGame: vi.fn(async (_id, mutator) => {+ state.game = await mutator(state.game);+ return state.game;+ }),+}));++import { atomicWrite } from '../../lib/fileUtils.js';+import { publishGameArtwork } from './artwork.js';++const gameFixture = () => ({+ id: 'game-1',+ appId: 'app-1',+ artworkBindings: [{+ id: 'artwork-1',+ imageFilename: 'title.png',+ label: 'Title Key Art',+ role: 'title-key-art',+ destinationPath: 'game/assets/art/title.png',+ publication: null,+ }],+});++describe('publishGameArtwork', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ state.game = gameFixture();+ state.source = Buffer.from('title-art-v1');+ state.destination = null;+ });++ it('publishes gallery bytes and records provenance', async () => {+ const result = await publishGameArtwork('game-1', 'artwork-1');+ expect(result.publication.wrote).toBe(true);+ expect(state.destination).toEqual(state.source);+ expect(state.game.artworkBindings[0].publication).toMatchObject({+ destinationPath: 'game/assets/art/title.png',+ sourceSha256: expect.stringMatching(/^[a-f0-9]{64}$/),+ });+ });++ it('is a byte-preserving no-op when the destination is current', async () => {+ state.destination = Buffer.from(state.source);+ const result = await publishGameArtwork('game-1', 'artwork-1');+ expect(result.publication.wrote).toBe(false);+ expect(atomicWrite).not.toHaveBeenCalled();+ });++ it('refuses to replace unmanaged destination bytes without acknowledgement', async () => {+ state.destination = Buffer.from('hand-authored-game-art');+ await expect(publishGameArtwork('game-1', 'artwork-1')).rejects.toMatchObject({+ code: 'PUBLISH_DEST_OCCUPIED',+ status: 409,+ });+ expect(atomicWrite).not.toHaveBeenCalled();+ });+});diff --git a/server/services/games/compile.js b/server/services/games/compile.jsindex 8eb768c7ba..754d7c59ee 100644--- a/server/services/games/compile.js+++ b/server/services/games/compile.js@@ -37,7 +37,9 @@ export async function compileGameAssets(id) {context: { issues: resolved.issues },});}- const { sprites, music, inputSha256, schemaVersion, verifiedFileCount } = resolved;+ const {+ sprites, music, artwork, inputSha256, schemaVersion, verifiedFileCount,+ } = resolved;const current = game.compiledManifest;const currentPath = current?.manifestPath? join(gameRecordDir(id), current.manifestPath)@@ -62,6 +64,7 @@ export async function compileGameAssets(id) {builtAt,sprites,music,+ artwork,};const serialized = `${canonicalStringify(manifest)}\n`;const manifestPath = manifestPathFor(version);@@ -75,6 +78,7 @@ export async function compileGameAssets(id) {inputSha256,spriteCount: sprites.length,musicCount: music.length,+ artworkCount: artwork.length,verifiedFileCount,};const next = sanitizeGame({diff --git a/server/services/games/compile.test.js b/server/services/games/compile.test.jsindex d5bc8a1163..d2a280c394 100644--- a/server/services/games/compile.test.js+++ b/server/services/games/compile.test.js@@ -18,7 +18,7 @@ vi.mock('./store.js', () => ({}));vi.mock('../../lib/fileUtils.js', () => ({- PATHS: { music: '/tmp/music' },+ PATHS: { images: '/tmp/images', music: '/tmp/music' },atomicWrite: vi.fn(async () => { state.manifestExists = true; }),pathExists: vi.fn(async (path) =>path.includes('/manifests/') ? state.manifestExists : true),@@ -27,6 +27,7 @@ vi.mock('../../lib/fileUtils.js', () => ({sha256File: vi.fn(async (path) => {if (path.includes('/manifests/')) return state.manifestSha256;const spriteId = path.match(/\/sprites\/([^/]+)\//)?.[1];+ if (path.endsWith('title.png')) return 'title-art-sha';if (path.endsWith('.png')) return `atlas-${spriteId}`;if (path.endsWith('.json')) return `manifest-${spriteId}`;return 'audio-sha';@@ -91,6 +92,14 @@ describe('compileGameAssets', () => {{ id: 'music-2', trackId: 'track-z' },{ id: 'music-1', trackId: 'track-a' },],+ artworkBindings: [{+ id: 'artwork-1',+ imageFilename: 'title.png',+ label: 'Title Key Art',+ role: 'title-key-art',+ destinationPath: 'game/assets/art/title.png',+ publication: null,+ }],compiledManifest: null,compileHistory: [],feedbackHistory: [],@@ -109,6 +118,10 @@ describe('compileGameAssets', () => {state.manifestSha256 = first.manifestSha256;expect(manifest.sprites.map((sprite) => sprite.spriteId)).toEqual(['alpha', 'zeta']);expect(manifest.music.map((track) => track.trackId)).toEqual(['track-a', 'track-z']);+ expect(manifest.artwork).toEqual([+ expect.objectContaining({ bindingId: 'artwork-1', role: 'title-key-art' }),+ ]);+ expect(first.artworkCount).toBe(1);const second = await compileGameAssets('game-1');expect(second).toEqual({ ...state.game.compiledManifest, created: false });diff --git a/server/services/games/feedback.js b/server/services/games/feedback.jsindex d91ce04de6..7f4812ccf5 100644--- a/server/services/games/feedback.js+++ b/server/services/games/feedback.js@@ -41,6 +41,13 @@ async function buildGameFeedbackPrompt(game, request) {title: track.title,hasAudio: Boolean(track.audioFilename),})),+ artwork: (game.artworkBindings || []).map((binding) => ({+ id: binding.id,+ label: binding.label,+ role: binding.role,+ destinationPath: binding.destinationPath,+ published: binding.publication?.destinationPath === binding.destinationPath,+ })),compiledManifest: game.compiledManifest,};return `You are reviewing an asset bundle plan for a game project.diff --git a/server/services/games/index.js b/server/services/games/index.jsindex 17cc5c5b66..160b2bcf28 100644--- a/server/services/games/index.js+++ b/server/services/games/index.js@@ -1,5 +1,6 @@export {GAME_HISTORY_LIMIT,+ bindArtwork,bindMusic,bindSprite,createGame,@@ -8,10 +9,13 @@ export {listGames,mutateGame,sanitizeGame,+ unbindArtwork,unbindMusic,unbindSprite,+ updateArtwork,updateGame,} from './records.js';+export { publishGameArtwork } from './artwork.js';export { compileGameAssets } from './compile.js';export {BUNDLE_SCHEMA_VERSION,diff --git a/server/services/games/integrity.js b/server/services/games/integrity.jsindex e40f3b94fe..f62db59acd 100644--- a/server/services/games/integrity.js+++ b/server/services/games/integrity.js@@ -29,7 +29,7 @@ import { getTrack } from '../tracks/index.js';import { getGame } from './records.js';import { gameRecordDir } from './store.js';-export const BUNDLE_SCHEMA_VERSION = 2;+export const BUNDLE_SCHEMA_VERSION = 3;const issue = (assetType, assetId, name, code, message) => ({assetType,@@ -270,23 +270,81 @@ async function resolveMusic(binding) {};}+const safeArtworkFilename = (filename) =>+ typeof filename === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/i.test(filename);++async function resolveArtwork(binding) {+ const identity = {+ assetId: binding.id,+ bindingId: binding.id,+ name: binding.label,+ role: binding.role,+ };+ if (!safeArtworkFilename(binding.imageFilename)) {+ return blocked(+ 'artwork',+ identity,+ 'ARTWORK_PATH_INVALID',+ `The gallery path for "${binding.label}" is invalid`,+ 'Gallery path invalid',+ );+ }+ const sourceSha256 = await hashIfPresent(join(PATHS.images, binding.imageFilename));+ if (!sourceSha256) {+ return blocked(+ 'artwork',+ identity,+ 'ARTWORK_MISSING',+ `The gallery artwork for "${binding.label}" is missing or unreadable`,+ 'Gallery artwork missing',+ );+ }+ const publicationCurrent = binding.publication?.sourceSha256 === sourceSha256+ && binding.publication?.destinationPath === binding.destinationPath;+ return {+ item: {+ bindingId: binding.id,+ label: binding.label,+ role: binding.role,+ imagePath: `images/${binding.imageFilename}`,+ sourceSha256,+ destinationPath: binding.destinationPath,+ publishedSha256: publicationCurrent ? sourceSha256 : null,+ },+ summary: {+ ...identity,+ imageFilename: binding.imageFilename,+ destinationPath: binding.destinationPath,+ status: 'ready',+ fileCount: 1,+ publicationStatus: publicationCurrent ? 'current' : 'pending',+ message: publicationCurrent ? 'Gallery source verified · published' : 'Gallery source verified · publish pending',+ },+ };+}+export async function resolveGameAssets(game) {- const [spriteResults, musicResults] = await Promise.all([+ const [spriteResults, musicResults, artworkResults] = await Promise.all([Promise.all([...game.spriteBindings].sort((a, b) => a.spriteId.localeCompare(b.spriteId)).map(resolveSprite)),Promise.all([...game.musicBindings].sort((a, b) => a.trackId.localeCompare(b.trackId) || a.id.localeCompare(b.id)).map(resolveMusic)),+ Promise.all([...(game.artworkBindings || [])]+ .sort((a, b) => a.role.localeCompare(b.role) || a.id.localeCompare(b.id))+ .map(resolveArtwork)),]);- const issues = [...spriteResults, ...musicResults]+ const issues = [...spriteResults, ...musicResults, ...artworkResults].map((result) => result.problem).filter(Boolean);const sprites = spriteResults.map((result) => result.item).filter(Boolean);const music = musicResults.map((result) => result.item).filter(Boolean);+ const artwork = artworkResults.map((result) => result.item).filter(Boolean);const summaries = {sprites: spriteResults.map((result) => result.summary),music: musicResults.map((result) => result.summary),+ artwork: artworkResults.map((result) => result.summary),};const inputs = {schemaVersion: BUNDLE_SCHEMA_VERSION,@@ -294,11 +352,13 @@ export async function resolveGameAssets(game) {appId: game.appId,sprites,music,+ artwork,};return {schemaVersion: BUNDLE_SCHEMA_VERSION,sprites,music,+ artwork,issues,inputSha256: sha256Text(canonicalStringify(inputs)),summaries,@@ -306,7 +366,7 @@ export async function resolveGameAssets(game) {// resolver that hashed them. The compiled manifest pointer and the// preflight both read this, so a new source type can't make the two// numbers disagree on screen.- verifiedFileCount: [...summaries.sprites, ...summaries.music]+ verifiedFileCount: [...summaries.sprites, ...summaries.music, ...summaries.artwork].reduce((sum, asset) => sum + (asset.fileCount || 0), 0),};}@@ -380,6 +440,8 @@ export async function getGameIntegrity(id) {spriteTotal: game.spriteBindings.length,musicReady: resolved.music.length,musicTotal: game.musicBindings.length,+ artworkReady: resolved.artwork.length,+ artworkTotal: (game.artworkBindings || []).length,verifiedFiles: resolved.verifiedFileCount,},};diff --git a/server/services/games/integrity.test.js b/server/services/games/integrity.test.jsindex 1d8865e780..56a1d6f1bd 100644--- a/server/services/games/integrity.test.js+++ b/server/services/games/integrity.test.js@@ -63,7 +63,7 @@ vi.mock('../pipeline/musicLibrary.js', () => ({}));vi.mock('../../lib/fileUtils.js', () => ({- PATHS: { music: '/tmp/music' },+ PATHS: { images: '/tmp/images', music: '/tmp/music' },readJSONFile: vi.fn(async () => state.manifest),// Content-exact, not length-based — a canonical-stringify change that happened// to preserve length must still register as a changed input.@@ -95,6 +95,7 @@ const baseGame = () => ({{ spriteId: 'draft-character' },],musicBindings: [{ id: 'music-1', trackId: 'theme' }],+ artworkBindings: [],compiledManifest: null,});@@ -150,6 +151,63 @@ describe('Game bundle integrity', () => {]));});+ it('hashes gallery artwork and reports whether publishing is current', async () => {+ state.game.spriteBindings = [];+ state.game.musicBindings = [];+ state.game.artworkBindings = [{+ id: 'artwork-1',+ imageFilename: 'title.png',+ label: 'Title Key Art',+ role: 'title-key-art',+ destinationPath: 'game/assets/art/title.png',+ publication: null,+ }];+ state.hashes['title.png'] = 'title-sha';++ const pending = await resolveGameAssets(state.game);+ expect(pending.artwork).toEqual([+ expect.objectContaining({+ bindingId: 'artwork-1',+ sourceSha256: 'title-sha',+ destinationPath: 'game/assets/art/title.png',+ }),+ ]);+ expect(pending.summaries.artwork[0]).toMatchObject({+ status: 'ready',+ publicationStatus: 'pending',+ fileCount: 1,+ });++ state.game.artworkBindings[0].publication = {+ sourceSha256: 'title-sha',+ destinationSha256: 'title-sha',+ destinationPath: 'game/assets/art/title.png',+ publishedAt: '2026-01-01T00:00:00.000Z',+ };+ const current = await resolveGameAssets(state.game);+ expect(current.summaries.artwork[0].publicationStatus).toBe('current');+ expect(current.verifiedFileCount).toBe(1);+ });++ it('blocks missing gallery artwork without failing the whole preflight', async () => {+ state.game.spriteBindings = [];+ state.game.musicBindings = [];+ state.game.artworkBindings = [{+ id: 'artwork-missing',+ imageFilename: 'missing.png',+ label: 'Missing Art',+ role: 'loading-screen',+ destinationPath: 'game/assets/art/loading.png',+ publication: null,+ }];+ const resolved = await resolveGameAssets(state.game);+ expect(resolved.artwork).toEqual([]);+ expect(resolved.issues[0]).toMatchObject({+ assetType: 'artwork',+ code: 'ARTWORK_MISSING',+ });+ });+it('reports a corrupt binding id as a blocked asset instead of throwing', async () => {// The atlas pointer read is issued in parallel with the record read, so a// binding whose id is not a valid slug must be gated — `spriteDir` throws adiff --git a/server/services/games/records.js b/server/services/games/records.jsindex 0f8148b0c0..35d4a86282 100644--- a/server/services/games/records.js+++ b/server/services/games/records.js@@ -3,7 +3,9 @@*/import { randomUUID } from 'crypto';+import { join } from 'path';import { ServerError } from '../../lib/errorHandler.js';+import { PATHS, pathExists } from '../../lib/fileUtils.js';import { getAppById } from '../apps.js';import { getRecord as getSpriteRecord } from '../sprites/records.js';import { getTrack } from '../tracks/index.js';@@ -21,6 +23,38 @@ const HISTORY_LIMIT = 50;const objectArray = (value) =>(Array.isArray(value) ? value.filter((entry) => entry && typeof entry === 'object') : []);const boundedHistory = (value) => objectArray(value).slice(-HISTORY_LIMIT);+const isSafeArtworkFilename = (value) =>+ typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]*\.png$/i.test(value);+const sanitizeArtworkPublication = (value) => {+ if (!value || typeof value !== 'object') return null;+ if (typeof value.sourceSha256 !== 'string'+ || typeof value.destinationSha256 !== 'string'+ || typeof value.destinationPath !== 'string'+ || typeof value.publishedAt !== 'string') return null;+ return {+ sourceSha256: value.sourceSha256,+ destinationSha256: value.destinationSha256,+ destinationPath: value.destinationPath,+ publishedAt: value.publishedAt,+ };+};+const sanitizeArtworkBinding = (binding) => {+ if (!binding || typeof binding !== 'object') return null;+ if (typeof binding.id !== 'string'+ || !isSafeArtworkFilename(binding.imageFilename)+ || typeof binding.label !== 'string'+ || typeof binding.role !== 'string'+ || typeof binding.destinationPath !== 'string') return null;+ return {+ id: binding.id,+ imageFilename: binding.imageFilename,+ label: binding.label,+ role: binding.role,+ destinationPath: binding.destinationPath,+ boundAt: typeof binding.boundAt === 'string' ? binding.boundAt : new Date().toISOString(),+ publication: sanitizeArtworkPublication(binding.publication),+ };+};export function sanitizeGame(raw) {if (!raw || typeof raw !== 'object') return null;@@ -29,12 +63,13 @@ export function sanitizeGame(raw) {if (!name) return null;return {id: raw.id,- schemaVersion: 1,+ schemaVersion: 2,appId: raw.appId,name,spriteBindings: objectArray(raw.spriteBindings).filter((binding) => typeof binding.spriteId === 'string'),musicBindings: objectArray(raw.musicBindings).filter((binding) =>typeof binding.id === 'string' && typeof binding.trackId === 'string'),+ artworkBindings: objectArray(raw.artworkBindings).map(sanitizeArtworkBinding).filter(Boolean),compiledManifest: raw.compiledManifest && typeof raw.compiledManifest === 'object'? raw.compiledManifest: null,@@ -76,11 +111,12 @@ export async function createGame({ appId, name }) {const now = new Date().toISOString();const game = sanitizeGame({id: `game-${randomUUID()}`,- schemaVersion: 1,+ schemaVersion: 2,appId,name,spriteBindings: [],musicBindings: [],+ artworkBindings: [],compiledManifest: null,compileHistory: [],feedbackHistory: [],@@ -185,4 +221,64 @@ export async function unbindMusic(id, bindingId) {});}+export async function bindArtwork(id, binding) {+ if (!isSafeArtworkFilename(binding.imageFilename)) {+ throw new ServerError('Gallery artwork filename is invalid', {+ status: 400,+ code: 'INVALID_ARTWORK',+ });+ }+ if (!await pathExists(join(PATHS.images, binding.imageFilename))) {+ throw new ServerError('Gallery artwork not found', { status: 400, code: 'INVALID_ARTWORK' });+ }+ return mutateGame(id, (current) => {+ if (current.artworkBindings.some((entry) => entry.imageFilename === binding.imageFilename+ && entry.role === binding.role)) {+ throw new ServerError('This artwork is already bound for that role', {+ status: 409,+ code: 'ALREADY_BOUND',+ });+ }+ return {+ ...current,+ artworkBindings: [...current.artworkBindings, {+ id: `artwork-${randomUUID()}`,+ ...binding,+ boundAt: new Date().toISOString(),+ publication: null,+ }],+ };+ });+}++export async function updateArtwork(id, bindingId, patch) {+ return mutateGame(id, (current) => {+ if (!current.artworkBindings.some((binding) => binding.id === bindingId)) {+ throw new ServerError('Artwork binding not found', { status: 404, code: 'NOT_FOUND' });+ }+ return {+ ...current,+ artworkBindings: current.artworkBindings.map((binding) => {+ if (binding.id !== bindingId) return binding;+ const next = { ...binding, ...patch };+ return patch.destinationPath && patch.destinationPath !== binding.destinationPath+ ? { ...next, publication: binding.publication }+ : next;+ }),+ };+ });+}++export async function unbindArtwork(id, bindingId) {+ return mutateGame(id, (current) => {+ if (!current.artworkBindings.some((binding) => binding.id === bindingId)) {+ throw new ServerError('Artwork binding not found', { status: 404, code: 'NOT_FOUND' });+ }+ return {+ ...current,+ artworkBindings: current.artworkBindings.filter((binding) => binding.id !== bindingId),+ };+ });+}+export const GAME_HISTORY_LIMIT = HISTORY_LIMIT;