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([issue-3020]): version sprite asset URLs so a reprocess repaints without a reload
[._.]/ Adam Eivydc4661eeb281
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex aaca67e8a7..da0dbc218b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -35,6 +35,7 @@## Sprite Manager+- **[issue-3020] Reprocessing a walk at a new frame count now updates every preview immediately, instead of showing the old art** — re-deriving a direction from 8 frames to 12 left the loop preview playing a violently jumpy, mis-centered animation: it had already picked up the new 12-frame timing, but your browser was still painting the *previous* 8-frame image, so it stepped 12 times across a picture that only had 8 poses in it. It looked like the sprite had been packed off-center — the packed art was fine all along, and reloading the page fixed it. Every sprite asset's address now carries a fingerprint of its contents, so the moment a reprocess changes the art the loop preview, the Loop Trimmer, and the asset browser and inspector all repaint on their own. That last part matters because the same reprocess also rewrites the individual pose frames and the contrast review sheet — the very things you'd open to check whether the strip really was repacked, which until now kept showing you the pre-reprocess art. This also covers a reprocess that changes the art *without* changing the frame count (a different cycle window, different background-removal settings), which previously went unnoticed entirely — and because the fingerprint only changes when the art does, unchanged assets are still served from cache rather than re-downloaded over Tailscale.- **[issue-3022] Walk cards now show the clip length grok actually delivered** — the Clip picker offers 6s and 10s, and it turns out those really are the only two lengths available: asking for a shorter clip to save render time doesn't work, because grok renders 6 seconds regardless and charges the same for it. Rather than leave that buried in a code comment (where it had already drifted into two comments claiming opposite things), each walk direction now reports the length of the clip it actually got, measured from the file — and says so in amber if that differs from what was requested. So if grok's options ever change, you'll see it on the card instead of having to guess.- **[issue-2980] See every frame a walk's video produced — and rebuild the loop at a new frame count without re-rendering** — the Loop Trimmer could only *drop* columns from a strip that was already packed, so an 8-frame walk could never become a 12-frame one there: the extra source frames were thrown away at pack time and nothing in the workspace showed they had ever existed. The trimmer now has a **Source frames** section listing every frame extracted from that run's clip (typically ~70 at 12fps), with the gait cycle the packer picked marked in amber and the frames that became the strip's columns highlighted — so the headroom above the current count is visible at a glance. A **Re-derive from clip** control beside it repacks the loop from that same on-disk video at a new frame count / speed, with no AI call and no new render; the frame count and speed are the walk set's shared cycle target rather than a free per-run range, since every direction of one walk has to agree for the atlas to compile, and changing them says so before it retargets the set. A run whose extracted frames were cleaned up (which is every imported run — the importer doesn't copy them) says so and offers a one-click "Extract frames from clip" rather than quietly running ffmpeg for every direction you happen to click through; an approved direction or a frozen set offers the matching inline Reopen / Unlock instead of failing on click; a run with no clip at all explains that in one line rather than showing an empty grid, and names the right remedy for how it got there; and if the frames on disk turn out not to be the ones the strip was packed from, the cycle markers are withheld rather than pointing at the wrong frames. Re-deriving an *imported* run also works now — its run id was rejected by the reprocess endpoint before it ever reached the service that #2993 taught to handle it.- **[issue-3004] Turnaround sheets stop mirroring the front view, so a front-worn bag no longer ends up on the character's back** — the back panel of a generated turnaround sheet was often just the front figure flipped left-to-right, which meant anything mounted on the *front* of the body (a hip bag worn at the front, a chest pack, a belt buckle) reappeared on the character's back in the rear view, and the same mistake carried into any single rotated view derived from the sheet. The old instruction only pinned accessories to the same anatomical *side* — a rule a mirrored figure satisfies perfectly, because the bug is on the front/back axis, not left/right. The sheet prompt now states that the panels are one character physically *rotated* about a vertical axis and that no panel may be a flip or copy of another, each derived view is told it is a rotation rather than a mirrored copy, and every facing carries its own rule for what that angle hides: a rear view hides front-mounted gear (keeping only what genuinely wraps around, like a strap crossing the back) and shows no face or front closures; a front view hides backpacks and back-slung weapons; each profile hides whatever sits on the far side of the torso — hedged for the diagonal views, where a 45-degree turn only partly hides things, so gear doesn't pop in and out as the sprite rotates. The diagonal views are also now told to interpolate between the two sheet panels they sit between, instead of being pointed at a panel the four-panel sheet doesn't have. The front/back panels also now say where a right-hip item lands on screen once the character turns, so "same side" can't be satisfied by leaving it in the same pixels. The walk-video step is told not to invent gear the anchor hides mid-loop.diff --git a/client/src/components/sprites/AssetCollection.jsx b/client/src/components/sprites/AssetCollection.jsxindex 24b508921d..8a179f5a81 100644--- a/client/src/components/sprites/AssetCollection.jsx+++ b/client/src/components/sprites/AssetCollection.jsx@@ -20,7 +20,7 @@ import { FolderOpen, RefreshCw, Scissors, Sparkles, Film, FileJson, NotebookPenimport AssetInspector from './AssetInspector.jsx';import CorrectionNote from './CorrectionNote.jsx';import SpritePreview from './SpritePreview.jsx';-import { hasSpritePreview } from './spriteAssets.js';+import { hasSpritePreview, assetVersionToken } from './spriteAssets.js';import { groupSpriteAssetsByRole } from '../../lib/spriteFacets.js';import { formatBytes } from '../../utils/formatters.js';@@ -72,7 +72,7 @@ function AssetCard({ recordId, asset, actions, corrections, onCorrectionChange,title={asset.path}>{hasSpritePreview(asset) && (- <SpritePreview recordId={recordId} path={asset.path} className="h-20 rounded" />+ <SpritePreview recordId={recordId} path={asset.path} version={assetVersionToken(asset)} className="h-20 rounded" />)}<span className="block text-[10px] text-gray-500 truncate">{name}</span><span className="flex items-center gap-1 text-[10px] text-gray-600">diff --git a/client/src/components/sprites/AssetInspector.jsx b/client/src/components/sprites/AssetInspector.jsxindex 9df9d8b65d..9c2dffff3b 100644--- a/client/src/components/sprites/AssetInspector.jsx+++ b/client/src/components/sprites/AssetInspector.jsx@@ -14,7 +14,7 @@ import { Download, ClipboardCopy, ExternalLink, Trash2, X } from 'lucide-react';import Modal from '../ui/Modal.jsx';import SpritePreview from './SpritePreview.jsx';import AssetPromptSection from './AssetPromptSection.jsx';-import { spriteAssetUrl, hasSpritePreview, isVideoAsset } from './spriteAssets.js';+import { spriteAssetUrl, hasSpritePreview, isVideoAsset, assetVersionToken } from './spriteAssets.js';import { isRuntimeVersionPath, isRuntimeSidecarManifest } from '../../lib/spriteFacets.js';import { formatBytes, timeAgo } from '../../utils/formatters.js';import { copyToClipboard } from '../../lib/clipboard.js';@@ -46,7 +46,7 @@ export default function AssetInspector({ recordId, asset, onClose, onDeleted = nif (!asset) return null;- const url = spriteAssetUrl(recordId, asset.path);+ const url = spriteAssetUrl(recordId, asset.path, assetVersionToken(asset));const fileName = asset.path.split('/').pop();const previewable = hasSpritePreview(asset);// A runtime version lives in `runtime/vN/` as an atlas PNG + its sidecar@@ -96,6 +96,7 @@ export default function AssetInspector({ recordId, asset, onClose, onDeleted = n<SpritePreviewrecordId={recordId}path={asset.path}+ version={assetVersionToken(asset)}className="rounded border border-port-border p-2"imgClassName="mx-auto max-w-full max-h-[55vh] object-contain"cell={10}diff --git a/client/src/components/sprites/AssetInspector.test.jsx b/client/src/components/sprites/AssetInspector.test.jsxindex 8178881452..64d3f4b72b 100644--- a/client/src/components/sprites/AssetInspector.test.jsx+++ b/client/src/components/sprites/AssetInspector.test.jsx@@ -66,8 +66,10 @@ describe('AssetInspector', () => {expect(screen.getByText('png')).toBeInTheDocument();expect(screen.getByText('2 KB')).toBeInTheDocument();+ // The href carries the asset's content token (#3020) so a re-download after+ // an in-place rewrite fetches the current bytes rather than a cached copy.const download = screen.getByRole('link', { name: /download/i });- expect(download).toHaveAttribute('href', '/data/sprites/trail-hand/reference/main.png');+ expect(download).toHaveAttribute('href', `/data/sprites/trail-hand/reference/main.png?v=${IMAGE.mtime}-${IMAGE.size}`);expect(download).toHaveAttribute('download', 'main.png');await userEvent.click(screen.getByRole('button', { name: /copy path/i }));@@ -109,15 +111,16 @@ describe('AssetInspector', () => {});it('plays a walk run source clip inline instead of forcing a download', () => {+ const clip = { path: 'grok/walk-east-abc/generated/source-video.mp4', size: 900, mtime: Date.now() };const { container } = render(- <AssetInspector- recordId="trail-hand"- asset={{ path: 'grok/walk-east-abc/generated/source-video.mp4', size: 900, mtime: Date.now() }}- onClose={() => {}}- />,+ <AssetInspector recordId="trail-hand" asset={clip} onClose={() => {}} />,);const video = container.querySelector('video');- expect(video).toHaveAttribute('src', '/data/sprites/trail-hand/grok/walk-east-abc/generated/source-video.mp4');+ // Same content token as every other asset URL (#3020). A run's clip is+ // write-once per run directory so it can't actually go stale, but the+ // inspector builds one URL for the download link and the inline player —+ // keeping that single rather than special-casing by asset kind.+ expect(video).toHaveAttribute('src', `/data/sprites/trail-hand/grok/walk-east-abc/generated/source-video.mp4?v=${clip.mtime}-${clip.size}`);expect(video).toHaveAttribute('controls');});diff --git a/client/src/components/sprites/LoopTrimmer.jsx b/client/src/components/sprites/LoopTrimmer.jsxindex 384baaeded..ae864b22a5 100644--- a/client/src/components/sprites/LoopTrimmer.jsx+++ b/client/src/components/sprites/LoopTrimmer.jsx@@ -139,18 +139,17 @@ export default function LoopTrimmer({if (!source) return undefined;const image = new Image();image.onload = () => setImg(image);- image.src = spriteAssetUrl(recordId, source.stripPath);+ image.src = spriteAssetUrl(recordId, source.stripPath, source.stripVersion);return () => { image.onload = null; };- // Geometry is in the deps, not just the path: a re-derive (#2980) repacks the- // strip at the SAME path, so nothing else here changes and the <img> would- // never be re-requested — it would keep painting the old column count. Keying- // on the refreshed frameCount/fps also sequences the reload correctly: it- // fires when the parent's new walk state lands, so `cellW` can never slice a- // freshly-loaded 12-column strip by the stale count of 8. (The asset mount- // serves max-age=0 with an ETag, so the re-request revalidates for free; a- // re-derive at unchanged geometry is deterministic and byte-identical, so- // skipping the reload there is correct rather than a missed refresh.)- }, [source?.id, source?.stripPath, recordId, frameCount, source?.fps]);+ // Keyed on the strip's content token, not just its path: a re-derive (#2980)+ // repacks at the SAME path, so without it nothing here changes and the image+ // keeps painting the old column count. The token also covers a repack at+ // unchanged geometry but different pixels (a new cycle window, different+ // chroma settings), which the frameCount keying alone could not see.+ // `frameCount` stays as the fallback for a run packed before the token+ // existed; it also sequences the reload correctly, so `cellW` can never+ // slice a freshly-loaded 12-column strip by the stale count of 8.+ }, [source?.id, source?.stripPath, recordId, frameCount, source?.stripVersion]);const cellW = img && frameCount > 0 ? img.naturalWidth / frameCount : 0;const cellH = img ? img.naturalHeight : 0;diff --git a/client/src/components/sprites/SpriteLightbox.jsx b/client/src/components/sprites/SpriteLightbox.jsxindex 3d4ef5842b..43691ce366 100644--- a/client/src/components/sprites/SpriteLightbox.jsx+++ b/client/src/components/sprites/SpriteLightbox.jsx@@ -15,7 +15,7 @@ import Modal from '../ui/Modal.jsx';import AssetPromptSection from './AssetPromptSection.jsx';import { checkerboardStyle, spriteAssetUrl, PIXELATED } from './spriteAssets.js';-export default function SpriteLightbox({ recordId, path, alt, onClose }) {+export default function SpriteLightbox({ recordId, path, version, alt, onClose }) {const fileName = path.split('/').pop();return (<Modal@@ -43,7 +43,7 @@ export default function SpriteLightbox({ recordId, path, alt, onClose }) {style={checkerboardStyle(12)}><img- src={spriteAssetUrl(recordId, path)}+ src={spriteAssetUrl(recordId, path, version)}alt={alt ?? path}className="mx-auto max-w-full max-h-[75vh] object-contain"style={PIXELATED}diff --git a/client/src/components/sprites/SpritePreview.jsx b/client/src/components/sprites/SpritePreview.jsxindex 4943cbbca7..f5f2a6c99e 100644--- a/client/src/components/sprites/SpritePreview.jsx+++ b/client/src/components/sprites/SpritePreview.jsx@@ -18,6 +18,10 @@ import SpriteLightbox from './SpriteLightbox.jsx';export default function SpritePreview({recordId,path,+ // Cache-busting token (#3020) for an asset that can be rewritten in place —+ // pass `assetVersionToken(asset)` when rendering a row from listSpriteAssets.+ // Omitted for a write-once/versioned path, which renders the bare URL.+ version,alt,className = '',imgClassName = 'w-full h-full object-contain',@@ -32,7 +36,7 @@ export default function SpritePreview({const [zoomed, setZoomed] = useState(false);const img = (<img- src={spriteAssetUrl(recordId, path)}+ src={spriteAssetUrl(recordId, path, version)}alt={alt ?? path}loading={loading}className={imgClassName}@@ -60,7 +64,7 @@ export default function SpritePreview({{img}</button>{zoomed && (- <SpriteLightbox recordId={recordId} path={path} alt={alt} onClose={() => setZoomed(false)} />+ <SpriteLightbox recordId={recordId} path={path} version={version} alt={alt} onClose={() => setZoomed(false)} />)}</>);diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex dd587c1133..930704382a 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -79,7 +79,11 @@ function stripGeometry(stripPreview) {function StripLoop({ recordId, stripPreview }) {const { frameCount, fps, height } = stripGeometry(stripPreview);const scrub = CELL_PX * frameCount;- const url = spriteAssetUrl(recordId, stripPreview.stripPath);+ // Content-token the URL (#3020) — a CSS background-image at an unchanged URL+ // is reused from the already-decoded image without issuing a request, so a+ // reprocessed strip would keep painting stale until a manual reload. See+ // spriteAssets.js for the full why.+ const url = spriteAssetUrl(recordId, stripPreview.stripPath, stripPreview.stripVersion);// The strip paints as a CSS background-image, which fires no onError — a// missing/404 file just renders blank. The server now surfaces a missing// strip as an error run (dropping stripPath so we never get here), but keep adiff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxindex 5db4a615cc..b40e5421de 100644--- a/client/src/components/sprites/WalkWorkflow.test.jsx+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -1,6 +1,6 @@import { describe, it, expect, vi } from 'vitest';import {- render, screen, act, fireEvent,+ render, screen, act, fireEvent, cleanup,} from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';@@ -93,6 +93,33 @@ describe('WalkWorkflow loop preview', () => {expect(loop.style.backgroundSize).toBe(`${CELL_PX * 8}px ${CELL_PX}px`);});+ // #3020: the packer rewrites the strip IN PLACE, and a CSS background-image at+ // an unchanged URL is reused from the already-decoded image with no request —+ // so the mount's ETag never revalidates. Reprocessing 8f → 12f then stepped the+ // NEW geometry over the OLD 8-cell strip: a jumpy, mis-centered toggle until a+ // manual reload. The content token in the URL is what forces the repaint.+ describe('strip cache-busting', () => {+ it('versions the strip URL with the token the server normalized onto it', () => {+ const loop = renderWalk({ ...APPROVED_STRIP, stripVersion: 'c432029004b5' });+ expect(loop.style.backgroundImage).toContain('?v=c432029004b5');+ });++ it('paints a different URL after a reprocess changes the strip bytes', () => {+ // Unmount between renders — two mounted loops would both match the role+ // query. This is the exact 8f → 12f reprocess the issue reported.+ const before = renderWalk({ ...APPROVED_STRIP, frameCount: 8, stripVersion: 'aaaaaaaaaaaa' }).style.backgroundImage;+ cleanup();+ const after = renderWalk({ ...APPROVED_STRIP, frameCount: 12, stripVersion: 'bbbbbbbbbbbb' }).style.backgroundImage;+ expect(before).not.toBe(after);+ });++ it('leaves a pre-token run on the un-versioned URL rather than ?v=undefined', () => {+ const loop = renderWalk({ ...APPROVED_STRIP });+ expect(loop.style.backgroundImage).toContain(APPROVED_STRIP.stripPath);+ expect(loop.style.backgroundImage).not.toContain('?v=');+ });+ });+// A strip painted as a CSS background-image fires no onError, so a missing/404// file would otherwise render a silent blank box. The server drops the path// for a known-missing strip, but a preload probe is the client-side backstop:diff --git a/client/src/components/sprites/spriteAssets.js b/client/src/components/sprites/spriteAssets.jsindex 5fe4985d03..2461787538 100644--- a/client/src/components/sprites/spriteAssets.js+++ b/client/src/components/sprites/spriteAssets.js@@ -1,6 +1,57 @@// Shared URL builder for sprite record assets served by the /data/sprites// static mount — one place for the per-segment encoding rules.-export const spriteAssetUrl = (recordId, relPath) => `/data/sprites/${encodeURIComponent(recordId)}/${relPath.split('/').map(encodeURIComponent).join('/')}`;+//+// `version` is an optional content token (a sha256 from the run manifest) that+// makes the URL change whenever the bytes behind it change (#3020). The packer+// rewrites a strip IN PLACE at a stable path, so without a token the browser+// keeps painting the image it already decoded — no request is issued, so no+// ETag revalidation happens either. Reprocessing 8f → 12f then applies the new+// stepped geometry to the OLD strip and the sprite reads as a jumpy, mis-+// centered toggle until a manual reload. A CONTENT hash (not `Date.now()`)+// is what's wanted: it changes if and only if the pixels did, so caching still+// works for the unchanged case — important over Tailscale, where these are+// multi-MB PNGs.+//+// The token is used VERBATIM — this builder deliberately does not shorten it.+// Truncating here silently corrupted a composite token: an `mtimeMs-size`+// stamp is 22 chars, so a 12-char clamp cut mid-mtime and dropped the size+// component entirely, which is the half that catches a rewrite too fast for+// mtime resolution. Shortening is the caller's call, because only the caller+// knows whether the token is a hash (safe to truncate) or a composite (not) —+// see `stripVersionToken`.+export const spriteAssetUrl = (recordId, relPath, version) => {+ const path = `/data/sprites/${encodeURIComponent(recordId)}/${relPath.split('/').map(encodeURIComponent).join('/')}`;+ // Only a non-empty STRING versions the URL — a stray number/object would+ // stringify into nonsense, and `?v=undefined` on a record that predates the+ // field would be a cache-buster that never changes (worse than no token).+ return typeof version === 'string' && version ? `${path}?v=${encodeURIComponent(version)}` : path;+};++// There is deliberately no client-side "which token field wins" resolver. The+// server normalizes every run's strip token into a single `stripPreview+// .stripVersion` (see normalizeStripPreview in services/sprites/walk.js), so a+// strip consumer just passes that field through and cannot paint a stale image+// by forgetting a precedence rule.++/**+ * Cache-busting token for an asset row from `listSpriteAssets` (#3020).+ *+ * The packed strip is not the only thing a reprocess rewrites in place: the+ * same run also rewrites its packaged phase frames+ * (`runs/<id>/generated/frames/NN-<phase>.png`) and its contrast review sheet,+ * both of which `listSpriteAssets` deliberately keeps in the asset browser+ * because they exist FOR human review (see paths.js). Those are exactly the+ * surfaces a user opens to confirm the strip really was repacked — so without a+ * token they show the pre-reprocess art, which is worse than the strip bug it+ * would be "confirming."+ *+ * No new server work is needed: every asset row already carries `mtime` and+ * `size`. Same composite shape as the redraw strip token, and likewise never+ * truncated — size is what catches a rewrite too fast for mtime resolution.+ */+export const assetVersionToken = (asset) => (+ asset?.mtime > 0 && asset?.size >= 0 ? `${Math.round(asset.mtime)}-${asset.size}` : undefined+);// Every sprite asset is a transparent-capable PNG/GIF, and PortOS's dark// surfaces are near-black — so alpha regions are indistinguishable from blackdiff --git a/client/src/components/sprites/spriteAssets.test.js b/client/src/components/sprites/spriteAssets.test.jsnew file mode 100644index 0000000000..09901c9214--- /dev/null+++ b/client/src/components/sprites/spriteAssets.test.js@@ -0,0 +1,84 @@+// The URL builder is the single place that decides whether a sprite asset's+// URL carries a content token (#3020). Every strip surface depends on it, so+// its no-token fallback has to stay byte-identical to the pre-token URL — a+// drift there would silently version (or fail to version) every asset at once.+import { describe, it, expect } from 'vitest';+import { spriteAssetUrl, assetVersionToken } from './spriteAssets.js';++const REC = 'example-walker';+const STRIP = 'runs/walk-east-abc/generated/example-walk-east-strip.png';+const BARE = `/data/sprites/${REC}/${STRIP}`;++describe('spriteAssetUrl', () => {+ it('builds the un-versioned URL when no version is passed', () => {+ expect(spriteAssetUrl(REC, STRIP)).toBe(BARE);+ });++ it('encodes each path segment separately, leaving the separators intact', () => {+ // A record id or filename with a space/# must encode, but the `/` between+ // segments must NOT — encoding the whole path would 404 the static mount.+ expect(spriteAssetUrl('my walker', 'runs/a b/strip #1.png'))+ .toBe('/data/sprites/my%20walker/runs/a%20b/strip%20%231.png');+ });++ it('appends the ?v= token when a version string is passed', () => {+ expect(spriteAssetUrl(REC, STRIP, 'c432029004b5')).toBe(`${BARE}?v=c432029004b5`);+ });++ // Regression: this builder used to clamp the token to 12 chars. An+ // `mtimeMs-size` stamp is 22 chars, so the clamp cut mid-mtime and dropped the+ // size component entirely — the half that catches a rewrite too fast for mtime+ // resolution. The token is now used verbatim; shortening is the caller's job,+ // because only the caller knows a hash from a composite.+ it('uses a composite mtime-size token verbatim rather than truncating it', () => {+ const composite = `${Date.now()}-10485760`;+ expect(composite.length).toBeGreaterThan(12); // the case the old clamp broke+ expect(spriteAssetUrl(REC, STRIP, composite)).toBe(`${BARE}?v=${composite}`);+ });++ it('keeps two composite tokens distinct when they differ only past char 12', () => {+ const mtime = Date.now();+ const a = spriteAssetUrl(REC, STRIP, `${mtime}-100`);+ const b = spriteAssetUrl(REC, STRIP, `${mtime}-200`);+ expect(a).not.toBe(b);+ });++ it('encodes a token that would otherwise break the query string', () => {+ expect(spriteAssetUrl(REC, STRIP, 'a&b=c')).toBe(`${BARE}?v=a%26b%3Dc`);+ });++ // A run that predates the version fields must render exactly as it does today+ // — never `?v=undefined`, which would be a cache-buster that never changes.+ it.each([+ ['undefined', undefined],+ ['null', null],+ ['an empty string', ''],+ ['a non-string', 12345],+ ])('falls back to the un-versioned URL for %s', (_label, version) => {+ expect(spriteAssetUrl(REC, STRIP, version)).toBe(BARE);+ });+});++describe('assetVersionToken', () => {+ it('builds an mtime-size token from an asset row', () => {+ expect(assetVersionToken({ path: 'a.png', mtime: 1784945418439.7, size: 4096 })).toBe('1784945418440-4096');+ });++ it('changes when only the size changes — a rewrite too fast for mtime resolution', () => {+ const mtime = 1784945418439;+ expect(assetVersionToken({ mtime, size: 100 })).not.toBe(assetVersionToken({ mtime, size: 200 }));+ });++ it('tokenizes a legitimately zero-byte asset rather than treating it as missing', () => {+ expect(assetVersionToken({ mtime: 1784945418439, size: 0 })).toBe('1784945418439-0');+ });++ it.each([+ ['an asset with no stat fields', { path: 'x.png' }],+ ['a zero mtime', { mtime: 0, size: 10 }],+ ['undefined', undefined],+ ['null', null],+ ])('returns undefined for %s so the URL stays un-versioned', (_label, asset) => {+ expect(assetVersionToken(asset)).toBeUndefined();+ });+});diff --git a/client/src/lib/spriteTrimmer.js b/client/src/lib/spriteTrimmer.jsindex eb32d3a9a2..c1af1f8465 100644--- a/client/src/lib/spriteTrimmer.js+++ b/client/src/lib/spriteTrimmer.js@@ -140,6 +140,12 @@ export function buildTrimmerSources(walk, assets = []) {direction: run.direction || null,label: `${run.direction || run.id} · ${run.status || 'run'}`,stripPath,+ // The strip's cache-busting token (#3020) has to be carried through this+ // flattener, not read off the run downstream: the trimmer only ever sees+ // this object, so a token left behind here silently leaves it slicing a+ // stale strip. Absent on a run packed before the token existed, which+ // renders as the un-versioned URL it used to get.+ stripVersion: run.stripPreview.stripVersion,frameCount,fps,// Any run with a packed strip can be re-trimmed — the service resolves itdiff --git a/client/src/lib/spriteTrimmer.test.js b/client/src/lib/spriteTrimmer.test.jsindex fbe488a8b5..1a2875551b 100644--- a/client/src/lib/spriteTrimmer.test.js+++ b/client/src/lib/spriteTrimmer.test.js@@ -96,6 +96,28 @@ describe('buildTrimmerSources', () => {expect(out.find((s) => s.kind === 'trim').trimmable).toBe(false);});+ // Regression (#3020): this flattener is the ONLY thing the Loop Trimmer sees,+ // so a strip token left behind here leaves the trimmer slicing a stale strip+ // with no other symptom — the first cut of that fix read the token off this+ // object, which never carried it, and was silently inert.+ it('carries the strip cache-busting token through to the trimmer source', () => {+ const withToken = {+ runs: [{+ id: 'walk-east-1',+ direction: 'east',+ status: 'candidate',+ stripPreview: {+ stripPath: 'grok/walk-east-1/generated/strip.png', frameCount: 8, fps: 12, stripVersion: 'c432029004b5',+ },+ }],+ };+ expect(buildTrimmerSources(withToken, [])[0].stripVersion).toBe('c432029004b5');+ });++ it('leaves the token undefined for a run packed before it existed', () => {+ expect(buildTrimmerSources(walk, assets)[0].stripVersion).toBeUndefined();+ });+it('derives a saved trim frame count from strip width / height', () => {const trim = buildTrimmerSources(walk, assets).find((s) => s.kind === 'trim');expect(trim.frameCount).toBe(4); // 1536 / 384diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.jsindex 2eb953a4f1..7c9b002c27 100644--- a/server/services/sprites/walk.js+++ b/server/services/sprites/walk.js@@ -19,7 +19,7 @@*/import { join } from 'path';-import { readdir, rm } from 'fs/promises';+import { readdir, rm, stat } from 'fs/promises';import { randomUUID } from 'crypto';import {ensureDir, atomicWrite, readJSONFile, pathExists, sha256File,@@ -272,10 +272,33 @@ function normalizeStaleRendering(run) {// here, in memory, at read time instead. Never written back to disk.function normalizeStripPreview(recordId, run) {if (!run?.stripPreview) return run;+ const patch = {};+const raw = run.stripPreview.stripPath ?? run.stripPreview.path;const stripPath = toRecordRelativeAssetPath(recordId, raw);- if (!stripPath) return run;- return { ...run, stripPreview: { ...run.stripPreview, stripPath } };+ if (stripPath) patch.stripPath = stripPath;++ // Collapse the strip's cache-busting token to ONE field the client reads+ // (#3020). The packer rewrites a strip in place at a stable path, so the URL+ // needs a token that changes with the bytes — but the two run flavors can+ // afford different tokens: a native run persists the real content hash, while+ // a synthesized redraw run has no hash in its manifest and sets `stripVersion`+ // itself from an mtime-size stat. Deriving the native case HERE — the one+ // choke point every run reader passes through — means the client never learns+ // that difference, and a strip consumer cannot silently paint a stale image by+ // forgetting to apply the precedence rule by hand. (That is not hypothetical:+ // the first cut of this fix resolved it client-side and the Loop Trimmer read+ // a flattened object that never carried either field, so its half was inert.)+ //+ // Truncated to 12 chars because a sha256 is 64 and only needs to be unique+ // across one file's own history; `stripVersion` is set verbatim by its+ // producer, since a composite token can't be cut without losing a component.+ if (!run.stripPreview.stripVersion && typeof run.stripPreview.stripSha256 === 'string' && run.stripPreview.stripSha256) {+ patch.stripVersion = run.stripPreview.stripSha256.slice(0, 12);+ }++ if (!Object.keys(patch).length) return run;+ return { ...run, stripPreview: { ...run.stripPreview, ...patch } };}// Same fixup as normalizeStripPreview, for the OTHER repo-anchored path fields@@ -416,16 +439,29 @@ async function loadRedrawRun(recordId, direction, entry) {const frameCount = Number(cycle?.frameCount);if (!Number.isInteger(frameCount) || frameCount < 2) return null;+ // `stat` answers BOTH questions in one syscall — does the strip exist, and+ // what is its cache-busting token (#3020) — so this deliberately stats rather+ // than calling pathExists and then stat-ing the winner again. A redraw+ // manifest carries no strip hash, and this is a READ path (it runs on every+ // walk-state load, per direction), so hashing a multi-MB PNG here would be a+ // real per-request cost; mtime+size is the cheap stand-in that still changes+ // whenever a re-import rewrites the strip at its stable path. Size matters+ // alongside mtime because mtime resolution can be too coarse to catch a fast+ // rewrite — which is also why this token must never be truncated.let stripPath = null;+ let stripStat = null;for (const field of REDRAW_STRIP_FIELDS) {const rel = toRecordRelativeAssetPath(recordId, cycle[field]);// eslint-disable-next-line no-await-in-loop -- ordered preference: stop at the first strip that exists- if (rel && await pathExists(join(spriteDir(recordId), rel))) {+ const found = rel && await stat(join(spriteDir(recordId), rel)).catch(() => null);+ if (found) {stripPath = rel;+ stripStat = found;break;}}if (!stripPath) return null;+ const stripVersion = `${Math.round(stripStat.mtimeMs)}-${stripStat.size}`;const cellSize = Number(manifest.cellSize) > 0 ? Number(manifest.cellSize) : WALK_CELL_SIZE;const fps = Number(cycle.referenceFps) > 0 ? Number(cycle.referenceFps) : WALK_FPS;@@ -454,6 +490,7 @@ async function loadRedrawRun(recordId, direction, entry) {? { importedPackaging: true } : {}),stripPreview: {stripPath,+ stripVersion,frameCount,fps,cellWidth: cellSize,diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.jsindex 0c2189f4da..55e80e9f2b 100644--- a/server/services/sprites/walk.test.js+++ b/server/services/sprites/walk.test.js@@ -1872,6 +1872,33 @@ describe('getWalkState', () => {// manifest does NOT land on postprocessManifest, which approve/trim// resolve as a packaged grok manifest (frames[] + alignment).expect(runs[0].postprocessManifest).toBeUndefined();++ // A redraw manifest carries no strip hash, and this is a read path — so+ // the strip's cache-busting token (#3020) is an mtime-size stand-in. It+ // still has to be PRESENT and well-formed, or the client falls back to an+ // un-versioned URL and an imported strip goes stale after a re-import.+ // The client reads ONE field regardless of which server path produced it.+ expect(runs[0].stripPreview.stripVersion).toMatch(/^\d+-\d+$/);+ });++ // The token must track the bytes: rewriting the strip at its stable path+ // (what a re-import does) has to produce a different token, or the client+ // keeps painting the strip it already decoded. Size is part of the token+ // precisely because mtime resolution can be too coarse to catch a fast+ // rewrite. (The absent-token fallback — a run predating the field — is+ // covered client-side in spriteAssets.test.js, which is where the+ // degradation to an un-versioned URL actually happens.)+ it('changes the strip version when the strip is rewritten in place', async () => {+ const id = newId();+ await characterWithRedrawEast(id);+ const before = (await getWalkState(id)).runs[0].stripPreview.stripVersion;++ const stripAbs = join(TEST_ROOT, 'sprites', id, 'imagegen', 'v19', 'clean-alpha.png');+ await writeFile(stripAbs, Buffer.alloc(4096, 7)); // same path, different bytes+ const after = (await getWalkState(id)).runs[0].stripPreview.stripVersion;++ expect(after).toMatch(/^\d+-\d+$/);+ expect(after).not.toBe(before);});// Same importer-shape guard as the runs/ layout above: a copied redrawdiff --git a/server/services/sprites/walkPostprocess.e2e.test.js b/server/services/sprites/walkPostprocess.e2e.test.jsindex fbf0f16962..7ec9916e68 100644--- a/server/services/sprites/walkPostprocess.e2e.test.js+++ b/server/services/sprites/walkPostprocess.e2e.test.js@@ -132,8 +132,16 @@ describe.skipIf(!ffmpegBin)('runWalkPostprocess e2e (synthetic keyed walk video)const preview = JSON.parse(await readFile(join(runAbs, 'generated', 'review-preview.json'), 'utf8'));expect(preview).toEqual({stripPath: 'grok/walk-east-fixture0/generated/fixture-hero-walk-east-strip.png',+ // The client versions the strip's URL with this hash (#3020) — the packer+ // rewrites the strip in place, so without it the browser keeps painting+ // the previously-decoded image after a reprocess.+ stripSha256: manifest.stripSha256,frameCount: n, fps: WALK_DEFAULT_FPS, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,});+ // Guard against the hash being echoed from a stale/empty source rather than+ // the strip actually written — it must be a real sha256 of real content.+ expect(preview.stripSha256).toMatch(/^[0-9a-f]{64}$/);+ expect(result.stripPreview.stripSha256).toBe(manifest.stripSha256);// Determinism: same video, second run → byte-identical manifest & strip.const second = await runOnce('run-b', videoAbs, anchorAbs);diff --git a/server/services/sprites/walkPostprocess.js b/server/services/sprites/walkPostprocess.jsindex 5d1979f5a5..b3109816cd 100644--- a/server/services/sprites/walkPostprocess.js+++ b/server/services/sprites/walkPostprocess.js@@ -758,8 +758,15 @@ export async function runWalkPostprocess({};await atomicWrite(join(generatedAbs, manifestName), manifest);+ // `stripSha256` mirrors the manifest's hash so the client can version the+ // strip's URL (#3020). The packer rewrites this path IN PLACE, so without a+ // content token in the URL the browser keeps painting the strip it already+ // decoded — reprocessing 8f → 12f applies the new stepped geometry to the old+ // 8-cell image and the sprite reads as a jumpy, mis-centered toggle until a+ // manual reload.const stripPreview = {stripPath: `${generatedRel}/${stripName}`,+ stripSha256,frameCount: targetFrames,fps: playbackFps,cellWidth: WALK_CELL_SIZE,