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([issue-2933]): Loop Trimmer as a deep-linkable Sprites workspace
[._.]/ Adam Eivyf717f06be2fa
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex feea069e77..0e47f4a795 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,7 @@## Sprite Manager+- **[issue-2933] Trim walk loops in a real editor, not a buried 8-checkbox strip** — loop trimming used to be a tiny row of checkboxes tucked inside a walk candidate card, with no way to see what you were doing: no playback, no scrubbing, no frame rate control, no per-frame preview. It's now its own **Loop Trimmer** workspace on the Sprites page, switchable from a tab beside the asset **Library** and deep-linkable (`?spriteTab=trimmer&run=<id>`) so a specific run is shareable and bookmarkable — and "Edit in Loop Trimmer", from either a walk card or an asset tile, jumps straight to it. Pick an animation source (any packaged walk run, plus your previously saved trims for review), play the loop on a checkerboarded canvas or scrub it frame by frame with prev/next and a frame label, tune the frame rate with a live slider, and toggle individual frames on and off from a grid of per-frame thumbnails (disabled frames dim and desaturate, the current frame is outlined) with a live enabled-count and Enable-all / Invert shortcuts. Name the output (it's normalized to a safe `a-z0-9-` slug) and save — the trimmed strip, preview GIF, and manifest paths are surfaced right there, and the source artwork is never touched. The old inline trim panel is gone, so there's exactly one place to trim.- **[issue-2932] Search the sprite library, and organize it by character / place / object** — the Sprites sidebar used to dump every record as a flat wall of names under just two buckets ("Characters" and "Props"), so a standalone place or object had nowhere to live and a big library was hard to scan. It now leads with a labelled autocomplete search box: type any part of a name, id, or kind and it narrows to a bounded, keyboard-navigable suggestion list (↑/↓ to move, Enter to open, Esc to clear); the full list is one click away behind a **Browse all** disclosure. Records group under **Characters**, **Places**, and **Objects**, and the New button (now **New Sprite**) lets you pick which of those three you're creating. Existing imported prop-atlas families keep working unchanged — they simply show under Objects alongside standalone objects. The reference / walk / publish workflows remain character-only.- **[issue-2938] Asset badges and Regenerate now reflect approval and backend state, not just the file path** — a walk direction you've already approved now shows its strip, frames, and animation with an **approved** badge instead of "candidate": approval is tracked in the walk selection, and the artwork never moves on disk, so the browser now reads that selection to badge the assets correctly. And a reference candidate's **Regenerate** button is greyed out with the same "No image backend configured" guidance the reference workflow shows when no image backend is set up — so it no longer queues a render that just fails with a toast — and when you do re-roll a candidate, it uses the same backend you picked in the reference workflow above instead of falling back to the install default.- **[issue-2931] A character's assets now group by what they are, and you can act on them in place** — the asset browser used to be a flat dump grouped by folder name (`reference`, `grok`, `runtime`), with every tile inert. Assets are now grouped by their actual role — reference set, strips, animations, frames, atlases, review evidence, manifests — and each one carries a status badge (runtime · approved · candidate · superseded · rejected · source), so you can see at a glance which reference version is current and which have been replaced. Walk strips, frames and animations gain two buttons: **Regenerate**, which re-runs that direction's render, and **Edit in Loop Trimmer**, which jumps straight to the trimmer for that run — including for a direction you've already approved, since trims are saved separately and never overwrite the approved artwork. Regenerate is correctly greyed out when the walk set is finalized, when the direction is already approved, when its reference anchor isn't locked yet, or while a render for it is already running — and it now shares one in-flight view with the workflow panels above, so starting a render in one place immediately disables it in the other instead of letting you pay for the same render twice. An unlocked reference candidate can be re-rolled the same way. Switching between characters no longer carries a stale "Rendering…" state across from the previous one.diff --git a/client/src/components/sprites/LoopTrimmer.jsx b/client/src/components/sprites/LoopTrimmer.jsxnew file mode 100644index 0000000000..98604efde8--- /dev/null+++ b/client/src/components/sprites/LoopTrimmer.jsx@@ -0,0 +1,367 @@+import {+ useCallback, useEffect, useMemo, useRef, useState,+} from 'react';+import {+ Scissors, Play, Pause, ChevronLeft, ChevronRight, Save, CheckCheck, FlipHorizontal2,+} from 'lucide-react';+import toast from '../ui/Toast';+import { trimSpriteWalk } from '../../services/apiSprites.js';+import { useAsyncAction } from '../../hooks/useAsyncAction.js';+import { spriteAssetUrl, paintCheckerboard } from './spriteAssets.js';+import SpritePreview from './SpritePreview.jsx';+import {+ buildTrimmerSources, allColumns, invertColumns, phaseLabelFor, sanitizeTrimSlug,+} from '../../lib/spriteTrimmer.js';++// Loop Trimmer workspace (#2933): the deep-linkable (`?spriteTab=trimmer&run=…`)+// replacement for WalkWorkflow's old inline 8-checkbox TrimPanel. It brings the+// source Sprite Manager's feature set to the browser — pick an animation source,+// scrub/play the loop on a checkerboarded canvas, toggle individual frames, tune+// fps, name the output, and save through the existing+// `POST /api/sprites/:id/walk/trim`. Only a packaged `grok/` run is trimmable;+// imported runs and previously saved trims load read-only for review.++const MAIN_PX = 192;+const THUMB_PX = 64;++// One frame of a packed strip on a checkerboarded canvas. Its own ref+effect so+// each thumbnail repaints independently when the image loads or geometry shifts.+function FrameCanvas({ img, col, cellW, cellH, size }) {+ const ref = useRef(null);+ useEffect(() => {+ const canvas = ref.current;+ if (!canvas) return;+ const ctx = canvas.getContext('2d');+ if (!ctx) return; // jsdom / context-less canvas+ paintCheckerboard(ctx, canvas.width, canvas.height, size >= MAIN_PX ? 8 : 5);+ if (img && cellW > 0 && cellH > 0) {+ ctx.imageSmoothingEnabled = false;+ ctx.drawImage(img, col * cellW, 0, cellW, cellH, 0, 0, canvas.width, canvas.height);+ }+ }, [img, col, cellW, cellH, size]);+ const aspect = cellW > 0 && cellH > 0 ? cellH / cellW : 1;+ return (+ <canvas+ ref={ref}+ width={size}+ height={Math.round(size * aspect)}+ className="w-full h-auto block"+ />+ );+}++export default function LoopTrimmer({+ record, walk, assets, runId = null, onSelectRun = () => {}, onSaved = () => {},+}) {+ const recordId = record.id;+ const sources = useMemo(() => buildTrimmerSources(walk, assets), [walk, assets]);++ const [selectedId, setSelectedId] = useState(null);+ const source = sources.find((s) => s.id === selectedId) || null;++ // Sync the selection from the `?run=` deep link, and keep it valid as the+ // source list (re)loads: a deep-linked run wins, otherwise keep the current+ // pick if it still exists, else fall back to the first source.+ useEffect(() => {+ const fromRun = runId ? sources.find((s) => s.kind === 'run' && s.runId === runId) : null;+ if (fromRun) { setSelectedId(fromRun.id); return; }+ setSelectedId((prev) => (sources.some((s) => s.id === prev) ? prev : (sources[0]?.id ?? null)));+ }, [runId, sources]);++ const frameCount = source?.frameCount || 0;++ const [enabled, setEnabled] = useState(() => new Set());+ const [frameIndex, setFrameIndex] = useState(0);+ const [playing, setPlaying] = useState(false);+ const [fps, setFps] = useState(12);+ const [outputName, setOutputName] = useState('');+ const [result, setResult] = useState(null);+ const [img, setImg] = useState(null);++ // Re-seed everything the moment the source changes — a stale enabled set from+ // a previous strip could hold out-of-range indices and 400 the endpoint.+ useEffect(() => {+ setEnabled(new Set(allColumns(frameCount)));+ setFrameIndex(0);+ setPlaying(false);+ setResult(null);+ setOutputName('');+ setFps(source?.fps || 12);+ }, [source?.id, frameCount, source?.fps]);++ // Load the strip PNG; cell geometry is derived from its natural size so a run+ // without cellWidth in its preview — and every saved-trim strip — still slices.+ useEffect(() => {+ setImg(null);+ if (!source) return undefined;+ const image = new Image();+ image.onload = () => setImg(image);+ image.src = spriteAssetUrl(recordId, source.stripPath);+ return () => { image.onload = null; };+ }, [source?.id, source?.stripPath, recordId]);++ const cellW = img && frameCount > 0 ? img.naturalWidth / frameCount : 0;+ const cellH = img ? img.naturalHeight : 0;++ // Main preview canvas — repaints on frame/geometry change.+ const mainRef = useRef(null);+ const aspect = cellW > 0 && cellH > 0 ? cellH / cellW : 1;+ const mainH = Math.round(MAIN_PX * aspect);+ useEffect(() => {+ const canvas = mainRef.current;+ if (!canvas) return;+ const ctx = canvas.getContext('2d');+ if (!ctx) return;+ paintCheckerboard(ctx, canvas.width, canvas.height, 8);+ if (img && cellW > 0 && cellH > 0) {+ ctx.imageSmoothingEnabled = false;+ ctx.drawImage(img, frameIndex * cellW, 0, cellW, cellH, 0, 0, canvas.width, canvas.height);+ }+ }, [img, frameIndex, cellW, cellH, mainH]);++ // Playback cycles the ENABLED frames in order (that IS the trimmed loop).+ useEffect(() => {+ if (!playing) return undefined;+ const cols = [...enabled].sort((a, b) => a - b);+ if (cols.length < 1) return undefined;+ const timer = setInterval(() => {+ setFrameIndex((prev) => {+ const at = cols.indexOf(prev);+ return at === -1 ? cols[0] : cols[(at + 1) % cols.length];+ });+ }, Math.max(1000 / (fps || 12), 40));+ return () => clearInterval(timer);+ }, [playing, enabled, fps]);++ const toggle = useCallback((i) => setEnabled((prev) => {+ const next = new Set(prev);+ if (next.has(i)) next.delete(i); else next.add(i);+ return next;+ }), []);+ const enableAll = () => setEnabled(new Set(allColumns(frameCount)));+ const invert = () => setEnabled(new Set(invertColumns(frameCount, [...enabled])));+ const step = (delta) => {+ if (frameCount < 1) return;+ setPlaying(false);+ setFrameIndex((prev) => (prev + delta + frameCount) % frameCount);+ };++ const slug = sanitizeTrimSlug(outputName);+ const [save, saving] = useAsyncAction(async () => {+ const trim = await trimSpriteWalk(recordId, {+ runId: source.runId,+ enabledColumns: [...enabled].sort((a, b) => a - b),+ fps,+ ...(slug ? { slug } : {}),+ }, { silent: true });+ setResult(trim);+ toast.success(`Trim saved (${trim.frameCount} frames)`);+ onSaved();+ }, { errorMessage: 'Trim failed' });++ const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white';++ if (sources.length === 0) {+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-semibold text-white flex items-center gap-1.5 mb-2">+ <Scissors className="w-4 h-4" /> Loop Trimmer+ </h3>+ <p className="text-sm text-gray-500">+ No animation strips to trim yet. Generate a walk cycle first, then return here to trim its loop.+ </p>+ </div>+ );+ }++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">+ <h3 className="text-sm font-semibold text-white flex items-center gap-1.5">+ <Scissors className="w-4 h-4" /> Loop Trimmer+ </h3>++ {/* Source + fps + output name */}+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div>+ <label htmlFor="trimmer-source" className="block text-xs text-gray-400 mb-1">Animation source</label>+ <select+ id="trimmer-source"+ value={selectedId || ''}+ onChange={(e) => {+ const next = sources.find((s) => s.id === e.target.value) || null;+ setSelectedId(e.target.value);+ onSelectRun(next?.kind === 'run' ? next.runId : null);+ }}+ className={inputCls}+ >+ {sources.map((s) => (+ <option key={s.id} value={s.id}>+ {s.label}{s.trimmable ? '' : ' (read-only)'}+ </option>+ ))}+ </select>+ </div>+ <div>+ <label htmlFor="trimmer-output" className="block text-xs text-gray-400 mb-1">+ Output name <span className="text-gray-600">([a-z0-9-])</span>+ </label>+ <input+ id="trimmer-output"+ type="text"+ value={outputName}+ onChange={(e) => setOutputName(e.target.value)}+ pattern="[a-z0-9-]+"+ placeholder={source?.direction ? `${source.direction}-loop` : 'east-loop'}+ className={inputCls}+ />+ <p className="mt-1 text-[11px] text-gray-500">+ saves as <code className="text-gray-400">{slug || `${source?.direction || 'east'}-loop`}</code>+ <span className="text-gray-600">-vNNN</span>+ </p>+ </div>+ </div>++ <div>+ <label htmlFor="trimmer-fps" className="flex items-center justify-between text-xs text-gray-400 mb-1">+ <span>Playback / output fps</span>+ <span className="text-gray-300 tabular-nums">{fps} fps</span>+ </label>+ <input+ id="trimmer-fps"+ type="range"+ min="1"+ max="24"+ value={fps}+ onChange={(e) => setFps(Number(e.target.value))}+ className="w-full accent-port-accent"+ />+ </div>++ {/* Canvas playback */}+ <div className="flex flex-col sm:flex-row gap-4">+ <div className="shrink-0">+ <div+ className="border border-port-border rounded overflow-hidden mx-auto"+ style={{ width: MAIN_PX, maxWidth: '100%' }}+ >+ <canvas ref={mainRef} width={MAIN_PX} height={mainH} className="w-full h-auto block" />+ </div>+ <div className="flex items-center justify-center gap-2 mt-2">+ <button+ onClick={() => step(-1)}+ aria-label="Previous frame"+ className="p-1.5 bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <ChevronLeft className="w-4 h-4" />+ </button>+ <button+ onClick={() => setPlaying((p) => !p)}+ aria-label={playing ? 'Pause' : 'Play'}+ className="p-1.5 bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ {playing ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}+ </button>+ <button+ onClick={() => step(1)}+ aria-label="Next frame"+ className="p-1.5 bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <ChevronRight className="w-4 h-4" />+ </button>+ </div>+ <p className="text-center text-[11px] text-gray-500 mt-1">+ frame {frameIndex} · {phaseLabelFor(frameIndex, frameCount)}+ {!enabled.has(frameIndex) && <span className="text-port-warning"> · disabled</span>}+ </p>+ </div>++ <div className="flex-1 min-w-0 space-y-3">+ <div>+ <label htmlFor="trimmer-scrub" className="block text-xs text-gray-400 mb-1">Scrub</label>+ <input+ id="trimmer-scrub"+ type="range"+ min="0"+ max={Math.max(0, frameCount - 1)}+ value={frameIndex}+ onChange={(e) => { setPlaying(false); setFrameIndex(Number(e.target.value)); }}+ className="w-full accent-port-accent"+ />+ </div>++ <div className="flex flex-wrap items-center gap-2">+ <button+ onClick={enableAll}+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <CheckCheck className="w-3.5 h-3.5" /> Enable all+ </button>+ <button+ onClick={invert}+ className="flex items-center gap-1 px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <FlipHorizontal2 className="w-3.5 h-3.5" /> Invert+ </button>+ <span className="text-xs text-gray-500">{enabled.size}/{frameCount} frames enabled</span>+ </div>++ {/* Per-frame toggles */}+ <div className="grid grid-cols-4 sm:grid-cols-6 gap-2">+ {allColumns(frameCount).map((i) => {+ const on = enabled.has(i);+ const active = i === frameIndex;+ return (+ <button+ key={i}+ onClick={() => toggle(i)}+ aria-pressed={on}+ title={`${phaseLabelFor(i, frameCount)} — ${on ? 'enabled' : 'disabled'}`}+ className={`rounded overflow-hidden border transition-colors ${+ active ? 'border-port-accent ring-1 ring-port-accent' : 'border-port-border hover:border-gray-500'+ } ${on ? '' : 'opacity-40 grayscale'}`}+ >+ <FrameCanvas img={img} col={i} cellW={cellW} cellH={cellH} size={THUMB_PX} />+ <span className="block text-center text-[10px] text-gray-500 py-0.5">{i}</span>+ </button>+ );+ })}+ </div>+ </div>+ </div>++ {/* Save + result */}+ <div className="flex flex-wrap items-center gap-3 border-t border-port-border pt-3">+ <button+ onClick={save}+ disabled={saving || !source?.trimmable || enabled.size < 2}+ title={!source?.trimmable+ ? 'This source is read-only — pick a packaged walk run to save a new trim'+ : enabled.size < 2 ? 'Keep at least 2 frames' : undefined}+ className="flex items-center gap-1.5 px-3 py-1.5 bg-port-accent hover:bg-blue-600 disabled:opacity-50 text-white rounded text-sm"+ >+ <Save className="w-4 h-4" /> {saving ? 'Saving…' : `Save trim (${enabled.size}/${frameCount})`}+ </button>+ {!source?.trimmable && (+ <p className="text-xs text-gray-500">Read-only source — loaded for review; pick a packaged run to trim.</p>+ )}+ </div>++ {result && (+ <div className="flex items-start gap-3 bg-port-bg border border-port-border rounded p-3">+ <SpritePreview+ recordId={recordId}+ path={result.loop}+ alt="trimmed loop"+ className="w-24 h-24 shrink-0 border border-port-border rounded"+ />+ <div className="min-w-0 text-[11px] text-gray-400 space-y-1">+ <p className="text-port-success">Saved {result.frameCount} frames ({result.disabledFrameCount} dropped).</p>+ <p className="break-all"><span className="text-gray-600">strip </span>{result.strip}</p>+ <p className="break-all"><span className="text-gray-600">gif </span>{result.loop}</p>+ <p className="break-all"><span className="text-gray-600">manifest </span>{result.manifest}</p>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/sprites/LoopTrimmer.test.jsx b/client/src/components/sprites/LoopTrimmer.test.jsxnew file mode 100644index 0000000000..f027b736c3--- /dev/null+++ b/client/src/components/sprites/LoopTrimmer.test.jsx@@ -0,0 +1,103 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';++// The trim endpoint is the whole point of Save — mock it so the test asserts+// the exact payload the UI sends without hitting the network. Canvas painting+// is a no-op in jsdom (getContext returns null) and the component guards it, so+// the frame math (toggle / enable-all / invert / save gating) is what's covered.+vi.mock('../../services/apiSprites.js', () => ({+ trimSpriteWalk: vi.fn(() => Promise.resolve({+ strip: 'walk/trims/east-loop-v001-strip.png',+ loop: 'walk/trims/east-loop-v001.gif',+ manifest: 'walk/trims/east-loop-v001.json',+ frameCount: 7,+ disabledFrameCount: 1,+ })),+}));++import LoopTrimmer from './LoopTrimmer';+import { trimSpriteWalk } from '../../services/apiSprites.js';++// jsdom has no 2D canvas; the component already guards a null context. Stub+// getContext to return null explicitly so the suite doesn't spam jsdom's+// "Not implemented: getContext" warning for every frame canvas it renders.+HTMLCanvasElement.prototype.getContext = () => null;++const grokRun = {+ id: 'walk-east-1', direction: 'east', status: 'candidate',+ stripPreview: { stripPath: 'grok/walk-east-1/generated/strip.png', frameCount: 8, fps: 12 },+};++const renderTrimmer = (props = {}) => render(+ <LoopTrimmer+ record={{ id: 'example-walker' }}+ walk={{ runs: [grokRun] }}+ assets={[]}+ onSelectRun={vi.fn()}+ onSaved={vi.fn()}+ {...props}+ />,+);++const enabledToggles = () => screen.queryAllByRole('button', { pressed: true });++describe('LoopTrimmer', () => {+ beforeEach(() => vi.clearAllMocks());++ it('seeds every frame enabled and gates Save at ≥2 frames', () => {+ renderTrimmer();+ expect(enabledToggles()).toHaveLength(8);+ expect(screen.getByRole('button', { name: /Save trim \(8\/8\)/ })).not.toBeDisabled();+ });++ it('toggles a frame off and reflects the count in Save', () => {+ renderTrimmer();+ fireEvent.click(enabledToggles()[0]);+ expect(enabledToggles()).toHaveLength(7);+ expect(screen.getByRole('button', { name: /Save trim \(7\/8\)/ })).toBeTruthy();+ });++ it('Enable all and Invert rewrite the whole selection', () => {+ renderTrimmer();+ fireEvent.click(screen.getByRole('button', { name: /Invert/ }));+ expect(enabledToggles()).toHaveLength(0); // all-on inverted → all-off+ expect(screen.getByRole('button', { name: /Save trim \(0\/8\)/ })).toBeDisabled();+ fireEvent.click(screen.getByRole('button', { name: /Enable all/ }));+ expect(enabledToggles()).toHaveLength(8);+ });++ it('saves the enabled columns + fps through the trim endpoint', async () => {+ renderTrimmer();+ fireEvent.click(enabledToggles()[7]); // drop the last frame+ fireEvent.click(screen.getByRole('button', { name: /Save trim/ }));+ await waitFor(() => expect(trimSpriteWalk).toHaveBeenCalled());+ expect(trimSpriteWalk).toHaveBeenCalledWith(+ 'example-walker',+ { runId: 'walk-east-1', enabledColumns: [0, 1, 2, 3, 4, 5, 6], fps: 12 },+ { silent: true },+ );+ // Result area surfaces the returned strip / GIF / manifest paths.+ await screen.findByText(/walk\/trims\/east-loop-v001\.json/);+ });++ it('sends a sanitized slug when the user names the output', async () => {+ renderTrimmer();+ fireEvent.change(screen.getByLabelText(/Output name/), { target: { value: 'East Loop V2!' } });+ expect(screen.getByText('east-loop-v2')).toBeTruthy(); // live slug preview+ fireEvent.click(screen.getByRole('button', { name: /Save trim/ }));+ await waitFor(() => expect(trimSpriteWalk).toHaveBeenCalled());+ expect(trimSpriteWalk.mock.calls[0][1]).toMatchObject({ slug: 'east-loop-v2' });+ });++ it('disables Save for a read-only (imported) source', () => {+ renderTrimmer({+ walk: { runs: [{ ...grokRun, stripPreview: { ...grokRun.stripPreview, stripPath: 'runs/import-east/generated/strip.png' } }] },+ });+ expect(screen.getByRole('button', { name: /Save trim/ })).toBeDisabled();+ });++ it('shows an empty state when there is nothing to trim', () => {+ renderTrimmer({ walk: { runs: [] } });+ expect(screen.getByText(/No animation strips to trim/)).toBeTruthy();+ });+});diff --git a/client/src/components/sprites/WalkWorkflow.jsx b/client/src/components/sprites/WalkWorkflow.jsxindex 36afaaf875..319a9f6f4f 100644--- a/client/src/components/sprites/WalkWorkflow.jsx+++ b/client/src/components/sprites/WalkWorkflow.jsx@@ -1,27 +1,18 @@import { useEffect, useMemo, useState } from 'react';import { Check, Film, RefreshCw, Scissors, Lock } from 'lucide-react';import toast from '../ui/Toast';-import { approveSpriteWalk, postprocessSpriteWalk, trimSpriteWalk } from '../../services/apiSprites.js';+import { approveSpriteWalk, postprocessSpriteWalk } from '../../services/apiSprites.js';import { useAsyncAction } from '../../hooks/useAsyncAction.js';import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.js';-import SpritePreview from './SpritePreview.jsx';--// Scroll anchor for the asset collection's "Edit in Loop Trimmer" action-// (#2931) — the trimmer lives in this card, potentially far above the asset-// grid that requested it.-export const WALK_WORKFLOW_DOM_ID = 'sprite-walk-workflow';+import { WALK_PHASES } from '../../lib/spriteTrimmer.js';// Walk workflow (issue #2897): one grok image_to_video clip per locked// directional anchor, deterministic server-side packaging into the 8-phase-// strip, per-direction review (loop preview + optional trim) and approval.-// The server's run records / selection / walk-set are the source of truth;-// this component renders them and fires generate/approve/trim.+// strip, per-direction review (loop preview) and approval. Loop trimming moved+// to its own deep-linkable workspace (#2933) — each card links into it. The+// server's run records / selection / walk-set are the source of truth; this+// component renders them and fires generate/approve.-// Mirrors server/services/sprites/walkPostprocess.js WALK_PHASES.-const WALK_PHASES = [- 'left-contact', 'left-down', 'left-passing', 'left-up',- 'right-contact', 'right-down', 'right-passing', 'right-up',-];const CELL_PX = 96; // preview cell size — the strip animates at 96px/frame// The scrub distance varies with the strip's frame count (a native run packs// 8, an imported redraw cycle can pack 12 — #2924), so the single keyframe@@ -82,88 +73,17 @@ function StripLoop({ recordId, stripPreview }) {);}-// Frame enable/disable trimmer for one packaged run — non-destructive: the-// server derives the strip geometry from the run manifest and re-packs the-// enabled frames into a versioned strip + GIF.-function TrimPanel({ recordId, run, onClose }) {- // Column count follows the packaged strip rather than the 8-phase constant,- // so a longer imported cycle trims every frame it actually contains (#2924).- const columns = useMemo(() => {- const { frameCount } = stripGeometry(run?.stripPreview);- return Array.from({ length: frameCount }, (_, i) => i);- }, [run?.stripPreview]);- const [enabled, setEnabled] = useState(() => new Set(columns));- // Re-seed when the strip changes under a mounted panel — a stale `enabled`- // holding out-of-range indices 400s the trim endpoint.- useEffect(() => setEnabled(new Set(columns)), [columns]);- const [result, setResult] = useState(null);- const toggle = (i) => setEnabled((prev) => {- const next = new Set(prev);- if (next.has(i)) next.delete(i); else next.add(i);- return next;- });- const [save, saving] = useAsyncAction(async () => {- const trim = await trimSpriteWalk(recordId, {- runId: run.id,- enabledColumns: [...enabled].sort((a, b) => a - b),- }, { silent: true });- setResult(trim);- toast.success(`Trim saved (${trim.frameCount} frames)`);- }, { errorMessage: 'Trim failed' });-- return (- <div className="bg-port-bg border border-port-border rounded p-2 space-y-2">- <div className="grid grid-cols-4 gap-1">- {columns.map((i) => {- const phase = WALK_PHASES[i] || `frame ${i}`;- return (- <label key={i} className="flex items-center gap-1 text-[10px] text-gray-400 cursor-pointer">- <input type="checkbox" checked={enabled.has(i)} onChange={() => toggle(i)} />- <span className="truncate" title={phase}>{i}·{phase}</span>- </label>- );- })}- </div>- <div className="flex items-center gap-2">- <button- onClick={save}- disabled={saving || enabled.size < 2}- className="px-2 py-0.5 text-xs bg-port-accent text-white rounded disabled:opacity-50"- >- {saving ? 'Saving…' : `Save trim (${enabled.size}/${columns.length})`}- </button>- <button onClick={onClose} className="px-2 py-0.5 text-xs text-gray-400 hover:text-white">Close</button>- </div>- {result && (- <div className="flex items-center gap-2">- <SpritePreview- recordId={recordId}- path={result.loop}- alt="trimmed loop"- className="w-24 h-24 shrink-0 border border-port-border rounded"- />- <p className="text-[10px] text-gray-500 break-all">{result.loop}</p>- </div>- )}- </div>- );-}-function DirectionCard({recordId, direction, anchorLocked, run, approved, finalized, pending,- trimRequestRun = null, onTrimClose, onGenerate, onApprove, onRetry,+ onOpenTrimmer, onGenerate, onApprove, onRetry,}) {const [confirming, setConfirming] = useState(false);- const [trimming, setTrimming] = useState(false);const candidate = run?.status === 'candidate' ? run : null;- // Two ways in: this card's own Scissors toggle (the direction's current- // candidate, as before) and an explicit request routed from an asset card- // (#2931), which names the exact run — possibly an older or APPROVED one,- // and possibly under a finalized walk set. That's sound: trims are- // non-destructive derived artifacts under `walk/trims/` and the server only- // requires a packaged manifest. It stays request-driven rather than becoming- // a new always-on affordance on approved directions.- const trimRun = trimRequestRun || (trimming ? candidate : null);+ // Only a run whose strip was packaged under `grok/` can be trimmed — the trim+ // endpoint reads `grok/<runId>/animation-run.json` hard-coded (an imported+ // `runs/<id>/` strip 404s). The link stands for approved and finalized runs+ // too, since a trim is a non-destructive derived artifact under `walk/trims/`.+ const trimmable = Boolean(run?.stripPreview?.stripPath?.startsWith('grok/'));const statusLabel = approved ? 'approved': pending ? 'rendering…': run?.status === 'postprocessing' ? 'packaging…'@@ -216,37 +136,26 @@ function DirectionCard({<button onClick={() => setConfirming(false)} className="px-1.5 py-0.5 text-gray-400 hover:text-white">No</button></div>) : (- <div className="flex gap-1">- <button onClick={() => setConfirming(true)} className="flex-1 px-2 py-0.5 text-xs bg-port-success/20 border border-port-success rounded text-port-success">- Approve- </button>- <button- onClick={() => setTrimming((t) => !t)}- title="Trim loop frames"- className="px-2 py-0.5 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"- >- <Scissors className="w-3 h-3" />- </button>- </div>+ <button onClick={() => setConfirming(true)} className="w-full px-2 py-0.5 text-xs bg-port-success/20 border border-port-success rounded text-port-success">+ Approve+ </button>))}</div>)}- {/* Outside the !finalized && !approved block on purpose: an explicit- trim request from the asset collection must open even for an- approved direction or a finalized walk set. */}- {trimRun && (- // Keyed by run id: a new trim request (from an asset card) can target a- // DIFFERENT run than the one currently open — remount so the panel's- // enabled-frame selection and last saved result don't leak from the- // previous run into the new one.- <TrimPanel- key={trimRun.id}- recordId={recordId}- run={trimRun}- onClose={() => { setTrimming(false); onTrimClose(); }}- />+ {/* The single trim UI now lives in the Loop Trimmer workspace (#2933);+ each card just links into it, deep-linked to this run. Shown for+ approved and finalized directions too — the trim is a non-destructive+ derived artifact, so trimming an approved loop is always allowed. */}+ {trimmable && (+ <button+ onClick={() => onOpenTrimmer(run.id)}+ title="Open this run in the Loop Trimmer"+ className="flex items-center gap-1 w-full justify-center px-2 py-0.5 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent"+ >+ <Scissors className="w-3 h-3" /> Edit in Loop Trimmer+ </button>)}</div>);@@ -254,7 +163,7 @@ function DirectionCard({export default function WalkWorkflow({record, reference, walk, renders, duration, onDurationChange, onGenerate,- trimRunId = null, onTrimClose = () => {}, onChanged,+ onOpenTrimmer = () => {}, onChanged,}) {const recordId = record.id;const manifest = reference?.manifest || null;@@ -296,13 +205,6 @@ export default function WalkWorkflow({return () => clearInterval(timer);}, [packaging, awaitingAttach, onChanged]);- // Resolved by id, not by direction: the asset collection can name any run- // that packed a strip, including one older than the direction's latest.- const requestedTrimRun = useMemo(- () => (trimRunId ? runs.find((r) => r.id === trimRunId) || null : null),- [runs, trimRunId],- );-const latestRunByDirection = useMemo(() => {const byDir = {};for (const run of runs) {@@ -336,7 +238,7 @@ export default function WalkWorkflow({.filter((d) => d?.status === 'approved').length;return (- <div id={WALK_WORKFLOW_DOM_ID} className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3"><style>{LOOP_KEYFRAMES}</style><div className="flex flex-wrap items-center justify-between gap-2"><h3 className="text-sm font-semibold text-white flex items-center gap-1.5">@@ -373,8 +275,7 @@ export default function WalkWorkflow({approved={selection?.directions?.[anchor.direction]?.status === 'approved'}finalized={finalized}pending={Boolean(pendingJobs[anchor.direction])}- trimRequestRun={requestedTrimRun?.direction === anchor.direction ? requestedTrimRun : null}- onTrimClose={onTrimClose}+ onOpenTrimmer={onOpenTrimmer}onGenerate={onGenerate}onApprove={approve}onRetry={retryPostprocess}diff --git a/client/src/components/sprites/WalkWorkflow.test.jsx b/client/src/components/sprites/WalkWorkflow.test.jsxindex a5f84d03b8..cb16a59a8a 100644--- a/client/src/components/sprites/WalkWorkflow.test.jsx+++ b/client/src/components/sprites/WalkWorkflow.test.jsx@@ -10,7 +10,6 @@ vi.mock('../../services/apiSprites.js', () => ({generateSpriteWalk: vi.fn(),approveSpriteWalk: vi.fn(),postprocessSpriteWalk: vi.fn(),- trimSpriteWalk: vi.fn(),}));import WalkWorkflow from './WalkWorkflow';@@ -99,24 +98,29 @@ describe('WalkWorkflow loop preview', () => {});});-// The asset collection's "Edit in Loop Trimmer" (#2931) routes back into this-// component's one TrimPanel. The run in this fixture is APPROVED, which the-// pre-existing Scissors toggle never reaches — so the panel has to render-// outside the `!finalized && !approved` action block or the action silently-// does nothing on exactly the assets most worth trimming.-describe('WalkWorkflow trim requests', () => {- it('shows no trim panel until a run is requested', () => {- renderWalk(APPROVED_STRIP);- expect(screen.queryByRole('button', { name: /Save trim/ })).toBeNull();+// Loop trimming moved to its own deep-linkable workspace (#2933): the inline+// TrimPanel is gone and each card just links into the trimmer. The link stands+// for approved/finalized directions too (a trim is a non-destructive artifact),+// and only for a run whose strip was packaged under `grok/` (the endpoint reads+// `grok/<runId>/…` hard-coded — an imported strip would 404).+describe('WalkWorkflow loop trimmer link', () => {+ it('offers "Edit in Loop Trimmer" for an approved grok run and fires with its id', () => {+ const onOpenTrimmer = vi.fn();+ renderWalk(APPROVED_STRIP, { onOpenTrimmer });+ const link = screen.getByRole('button', { name: /Edit in Loop Trimmer/ });+ link.click();+ expect(onOpenTrimmer).toHaveBeenCalledWith('run-east');});- it('opens the trim panel for an approved run named by id', () => {- renderWalk(APPROVED_STRIP, { trimRunId: 'run-east' });- expect(screen.getByRole('button', { name: /Save trim \(8\/8\)/ })).toBeTruthy();+ it('renders no inline trim panel', () => {+ renderWalk(APPROVED_STRIP, { onOpenTrimmer: vi.fn() });+ expect(screen.queryByRole('button', { name: /Save trim/ })).toBeNull();});- it('ignores a run id that is not in this record listing', () => {- renderWalk(APPROVED_STRIP, { trimRunId: 'run-that-does-not-exist' });- expect(screen.queryByRole('button', { name: /Save trim/ })).toBeNull();+ it('hides the link for a run whose strip is not under grok/ (not trimmable)', () => {+ renderWalk({+ stripPath: 'runs/import-east/generated/strip.png', frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384,+ }, { onOpenTrimmer: vi.fn() });+ expect(screen.queryByRole('button', { name: /Edit in Loop Trimmer/ })).toBeNull();});});diff --git a/client/src/components/sprites/spriteAssets.js b/client/src/components/sprites/spriteAssets.jsindex fbcae2ac66..bd4ccf15ff 100644--- a/client/src/components/sprites/spriteAssets.js+++ b/client/src/components/sprites/spriteAssets.js@@ -38,6 +38,29 @@ export function checkerboardStyle(cell = 6) {// constant, and every consumer treats React style props as read-only.export const PIXELATED = Object.freeze({ imageRendering: 'pixelated' });+// Canvas equivalent of the CSS checkerboard above (#2933). A `<canvas>` can't+// read `var(--sprite-checker-*)` or paint a CSS gradient, so the Loop Trimmer's+// canvases resolve the same custom properties off the document root (falling+// back to the dark literals when a theme sets neither) and fill the squares by+// hand. Kept next to `checkerboardStyle` so the two stay the same pattern.+function checkerColor(name, fallback) {+ if (typeof window === 'undefined' || typeof getComputedStyle !== 'function') return fallback;+ const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();+ return value || fallback;+}++export function paintCheckerboard(ctx, width, height, cell = 6) {+ if (!ctx) return; // jsdom / a context-less canvas — nothing to paint+ ctx.fillStyle = checkerColor('--sprite-checker-dark', '#191919');+ ctx.fillRect(0, 0, width, height);+ ctx.fillStyle = checkerColor('--sprite-checker-light', '#2e2e2e');+ for (let y = 0; y < height; y += cell) {+ for (let x = 0; x < width; x += cell) {+ if ((Math.floor(x / cell) + Math.floor(y / cell)) % 2 === 0) ctx.fillRect(x, y, cell, cell);+ }+ }+}+// sharp can probe more formats than a browser can paint — a TIFF yields clean// metadata but renders as a broken-image icon in Chrome/Firefox. So the server// probe list (for metadata) and this list (for "can I put it in an <img>") arediff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex ab3eaf6259..c54b27238a 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -139,6 +139,7 @@ grep -i "what you want to do" client/src/lib/README.md| `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js`. || `spriteFacets.js` | Client-side facet classifier for the Sprite Manager's asset collection (#2931), mirroring the source pipeline's `classify_asset()`. `classifySpriteAsset(path)` decodes a record-relative asset path into `{ family, status, role, direction, runId }` — `status ∈ runtime/approved/candidate/superseded/rejected/source`, `role ∈ reference/strip/animation/frame/atlas/evidence/sprite/manifest` — and is total (an unknown path degrades to `sprite`/`source` rather than throwing). `classifySpriteAssets(assets)` adds the one facet only knowable across a listing: an approved asset below the highest `-vN` of its stem becomes `superseded`. `groupSpriteAssetsByRole(assets)` returns render-ready `{ role, label, assets }` sections in `SPRITE_ASSET_ROLES` order. Also exports `SPRITE_DIRECTIONS` (mirror of `server/services/sprites/prompts.js`) — the `direction`/`runId` facets are what drive the collection's Regenerate and Edit-in-Loop-Trimmer actions. Pure — no React, no I/O. || `spriteRecordGroups.js` | Grouping + search for the Sprite Manager sidebar's record picker (#2932). `groupSpriteRecords(records)` → ordered `[{ key, label, records }]` under **Characters / Places / Objects** (`props` folded into Objects alongside `object`, no migration). `filterSpriteRecords(records, query, limit=8)` is the autocomplete filter — multi-term (AND) substring over `name`/`id`/`kind`, capped at `limit`. `groupKeyForKind(kind)` maps a kind to its group key (unknown → `objects`). `SPRITE_RECORD_GROUPS` / `NEW_SPRITE_KINDS` back the browse disclosure and the create-panel kind selector. Pure — no React, no I/O; the page owns the per-group icons. |+| `spriteTrimmer.js` | Pure geometry + source-list math behind the Sprite Manager's Loop Trimmer workspace (#2933). `buildTrimmerSources(walk, assets)` → the ordered animation sources the trimmer can load (every preview-strip run first, then saved trims read from the asset listing), each `{ id, kind: 'run'\|'trim', runId, direction, label, stripPath, frameCount, fps, trimmable }` — only a `grok/` run is `trimmable`, mirroring `spriteCollectionActions`' gate. `stripFrameGeometry(stripPreview)` → `{ frameCount, fps, cellWidth, cellHeight }` with the native 8-phase / 12fps fallback; `phaseLabelFor(index, frameCount)` names the 8 walk phases (bare `frame N` for any other length); `sanitizeTrimSlug(name)` → the server's `[a-z0-9-]+` output slug; `allColumns(n)` / `invertColumns(n, enabled)` for the frame-toggle set. `WALK_PHASES` is the shared phase-label constant (WalkWorkflow imports it here). Pure — no React, no canvas, no I/O. || `tribe.js` | Pure Tribe domain helpers shared by the Tribe page and its `TribeCircleMap` visualization: `RINGS` (support→core→tribe→village Dunbar rings + the uncapped `external` "outside the tribe" classification — caps, cadence defaults, Tailwind tones + `hex`), `TRIBE_RINGS` (the four inner rings the care queue/capacity/overdue counts operate over, excluding `external`), `ENERGY` (energy tiers + `hex`), `STATUS_HEX` (cadence-status → SVG stroke color), `contactStatus(contact)` (presentation wrapper over the shared `cadenceStatus` — attaches label/tone to the missing/overdue/soon/steady/`external` state) / `daysBetween(date)` (alias of the shared `daysSinceDate`), `ringFor` / `energyFor` lookups, `tagsToArray` / `tagsToInput`, and `initialsFor(name)` (node glyph). Ring `cadenceDays` mirror `DEFAULT_RING_CADENCE` in `server/services/tribe.js`; the cadence STATE MACHINE lives in `tribeCadence.js`. || `tribeCadence.js` | Mirror of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the proactive alert: `cadenceStatus(entity)` → `{ state, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS`, `SOON_WINDOW_DAYS`. A cross-boundary contract test asserts it never drifts from the server copy. || `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex c7dda05f3c..0983077323 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -107,6 +107,7 @@ export * from './songProgress.js';export * from './spriteCollectionActions.js';export * from './spriteFacets.js';export * from './spriteRecordGroups.js';+export * from './spriteTrimmer.js';export * from './streakGlyph.js';export * from './syncCounts.js';export * from './tabNotation.js';diff --git a/client/src/lib/spriteTrimmer.js b/client/src/lib/spriteTrimmer.jsnew file mode 100644index 0000000000..251d3b5fc0--- /dev/null+++ b/client/src/lib/spriteTrimmer.js@@ -0,0 +1,132 @@+/**+ * Loop Trimmer helpers for the Sprite Manager (#2933).+ *+ * Pure geometry + source-list math behind the deep-linkable Loop Trimmer+ * workspace: turn a record's walk state (+ its on-disk asset listing) into the+ * ordered set of animation sources the trimmer can load, derive a strip's frame+ * geometry, label each phase, and sanitize the user's output slug to the+ * `[a-z0-9-]+` shape the server accepts.+ *+ * No React, no I/O, no canvas — the component owns painting; this module owns+ * the arithmetic so the correctness surface is unit-testable without mounting.+ */++// Mirrors server/services/sprites/walkPostprocess.js WALK_PHASES (and the copy+// WalkWorkflow.jsx imports from here) — the phase label for each of the 8 cells+// a native grok walk run packs.+export const WALK_PHASES = [+ 'left-contact', 'left-down', 'left-passing', 'left-up',+ 'right-contact', 'right-down', 'right-passing', 'right-up',+];++const DEFAULT_FPS = 12;++/**+ * Frame geometry for a packed strip, defaulting to the native 8-phase packaging+ * when a run predates (or omits) the richer stripPreview fields. `cellWidth` /+ * `cellHeight` are 0 when the preview carries no cell size — callers derive the+ * true cell size from the loaded image's natural dimensions instead, which also+ * covers saved-trim strips that never carry a stripPreview.+ */+export function stripFrameGeometry(stripPreview) {+ const rawCount = Math.round(Number(stripPreview?.frameCount));+ const frameCount = rawCount > 1 ? rawCount : WALK_PHASES.length; // NaN > 1 is false+ const fps = Number(stripPreview?.fps) > 0 ? Number(stripPreview.fps) : DEFAULT_FPS;+ const cw = Number(stripPreview?.cellWidth);+ const ch = Number(stripPreview?.cellHeight);+ return {+ frameCount,+ fps,+ cellWidth: cw > 0 ? cw : 0,+ cellHeight: ch > 0 ? ch : 0,+ };+}++/**+ * Human label for one frame index. Named walk phases only apply to the native+ * 8-cell packing; a longer imported redraw cycle (or an arbitrary saved trim)+ * gets a plain `frame N` so the labels never mix a real phase with a bare index.+ */+export function phaseLabelFor(index, frameCount) {+ if (frameCount === WALK_PHASES.length && WALK_PHASES[index]) return WALK_PHASES[index];+ return `frame ${index}`;+}++/** `[0, 1, …, frameCount-1]`. */+export function allColumns(frameCount) {+ const n = Math.max(0, Math.round(Number(frameCount)) || 0);+ return Array.from({ length: n }, (_, i) => i);+}++/** The complement of `enabled` within `[0, frameCount)`, ascending. */+export function invertColumns(frameCount, enabled) {+ const set = new Set(enabled);+ return allColumns(frameCount).filter((i) => !set.has(i));+}++/**+ * Normalize a user-typed output name to the server's `[a-z0-9-]+` slug shape:+ * lowercase, non-alphanumerics collapse to a single `-`, and leading/trailing+ * dashes are trimmed. Returns '' for input with no usable characters so callers+ * can fall back to the server's default (`<direction>-loop`) rather than send a+ * slug the route would reject.+ */+export function sanitizeTrimSlug(name) {+ if (typeof name !== 'string') return '';+ return name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+}++/**+ * Ordered animation sources for the trimmer's source select: every packaged+ * walk run that carries a preview strip, followed by the record's saved trims+ * (read from the asset listing). Only a run whose strip lives under `grok/` is+ * `trimmable` — the trim endpoint reads `grok/<runId>/animation-run.json`+ * hard-coded, so an imported `runs/<id>/` strip or a saved trim is preview-only+ * (playback + scrubbing, no re-save). This mirrors `spriteCollectionActions`'+ * `trimmableRunIds` gate so the two surfaces agree on what can be trimmed.+ *+ * Each source: `{ id, kind: 'run'|'trim', runId, direction, label, stripPath,+ * frameCount, fps, trimmable }`. `runId` is null for a saved-trim source.+ */+export function buildTrimmerSources(walk, assets = []) {+ const sources = [];+ for (const run of walk?.runs || []) {+ const stripPath = run?.stripPreview?.stripPath;+ if (!stripPath) continue;+ const { frameCount, fps } = stripFrameGeometry(run.stripPreview);+ sources.push({+ id: `run:${run.id}`,+ kind: 'run',+ runId: run.id,+ direction: run.direction || null,+ label: `${run.direction || run.id} · ${run.status || 'run'}`,+ stripPath,+ frameCount,+ fps,+ trimmable: stripPath.startsWith('grok/'),+ });+ }++ for (const asset of assets || []) {+ if (!/^walk\/trims\/[^/]+-strip\.png$/.test(asset?.path || '')) continue;+ if (!(asset.width > 0) || !(asset.height > 0)) continue;+ const frameCount = Math.max(1, Math.round(asset.width / asset.height));+ const name = asset.path.slice('walk/trims/'.length).replace(/-strip\.png$/, '');+ sources.push({+ id: `trim:${asset.path}`,+ kind: 'trim',+ runId: null,+ direction: null,+ label: `saved trim · ${name}`,+ stripPath: asset.path,+ frameCount,+ fps: DEFAULT_FPS,+ trimmable: false,+ });+ }++ return sources;+}diff --git a/client/src/lib/spriteTrimmer.test.js b/client/src/lib/spriteTrimmer.test.jsnew file mode 100644index 0000000000..52ec01213b--- /dev/null+++ b/client/src/lib/spriteTrimmer.test.js@@ -0,0 +1,107 @@+import { describe, it, expect } from 'vitest';+import {+ WALK_PHASES, stripFrameGeometry, phaseLabelFor, allColumns, invertColumns,+ sanitizeTrimSlug, buildTrimmerSources,+} from './spriteTrimmer.js';++describe('stripFrameGeometry', () => {+ it('reads frame count / fps / cell size from a rich preview', () => {+ expect(stripFrameGeometry({ frameCount: 12, fps: 24, cellWidth: 384, cellHeight: 320 }))+ .toEqual({ frameCount: 12, fps: 24, cellWidth: 384, cellHeight: 320 });+ });++ it('falls back to the native 8-phase packing and 12fps when fields are absent', () => {+ expect(stripFrameGeometry({})).toEqual({ frameCount: 8, fps: 12, cellWidth: 0, cellHeight: 0 });+ expect(stripFrameGeometry(null)).toEqual({ frameCount: 8, fps: 12, cellWidth: 0, cellHeight: 0 });+ });++ it('treats a non-numeric or <2 frame count as the native default (NaN > 1 is false)', () => {+ expect(stripFrameGeometry({ frameCount: 'x' }).frameCount).toBe(8);+ expect(stripFrameGeometry({ frameCount: 1 }).frameCount).toBe(8);+ });+});++describe('phaseLabelFor', () => {+ it('names walk phases for the native 8-cell packing', () => {+ expect(phaseLabelFor(0, 8)).toBe('left-contact');+ expect(phaseLabelFor(7, 8)).toBe(WALK_PHASES[7]);+ });++ it('uses a bare frame index for a non-8 strip so labels never mix', () => {+ expect(phaseLabelFor(0, 12)).toBe('frame 0');+ expect(phaseLabelFor(11, 12)).toBe('frame 11');+ });+});++describe('allColumns / invertColumns', () => {+ it('lists every column', () => {+ expect(allColumns(4)).toEqual([0, 1, 2, 3]);+ expect(allColumns(0)).toEqual([]);+ });++ it('inverts an enabled selection', () => {+ expect(invertColumns(6, [0, 2, 4])).toEqual([1, 3, 5]);+ expect(invertColumns(3, [])).toEqual([0, 1, 2]);+ expect(invertColumns(3, [0, 1, 2])).toEqual([]);+ });+});++describe('sanitizeTrimSlug', () => {+ it('lowercases and collapses non-alphanumerics to single dashes', () => {+ expect(sanitizeTrimSlug('East Loop v2')).toBe('east-loop-v2');+ expect(sanitizeTrimSlug(' --Hero__Walk!! ')).toBe('hero-walk');+ });++ it('returns empty for input with no usable characters', () => {+ expect(sanitizeTrimSlug('!!!')).toBe('');+ expect(sanitizeTrimSlug('')).toBe('');+ expect(sanitizeTrimSlug(null)).toBe('');+ });+});++describe('buildTrimmerSources', () => {+ const walk = {+ runs: [+ {+ id: 'walk-east-1', direction: 'east', status: 'candidate',+ stripPreview: { stripPath: 'grok/walk-east-1/generated/strip.png', frameCount: 8, fps: 12 },+ },+ {+ id: 'import-north', direction: 'north', status: 'approved',+ stripPreview: { stripPath: 'runs/import-north/generated/strip.png', frameCount: 12, fps: 10 },+ },+ { id: 'no-strip', direction: 'west', status: 'queued', stripPreview: null },+ ],+ };+ const assets = [+ { path: 'walk/trims/east-loop-v001-strip.png', width: 1536, height: 384 },+ { path: 'walk/trims/east-loop-v001.gif', width: 0, height: 0 },+ { path: 'grok/walk-east-1/generated/strip.png', width: 3072, height: 384 },+ ];++ it('lists packaged runs first, saved trims after, and skips stripless runs', () => {+ const out = buildTrimmerSources(walk, assets);+ expect(out.map((s) => s.id)).toEqual([+ 'run:walk-east-1', 'run:import-north', 'trim:walk/trims/east-loop-v001-strip.png',+ ]);+ });++ it('marks only grok/ runs trimmable; imported runs and saved trims are preview-only', () => {+ const out = buildTrimmerSources(walk, assets);+ expect(out.find((s) => s.id === 'run:walk-east-1').trimmable).toBe(true);+ expect(out.find((s) => s.id === 'run:import-north').trimmable).toBe(false);+ expect(out.find((s) => s.kind === 'trim').trimmable).toBe(false);+ });++ 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 / 384+ expect(trim.runId).toBeNull();+ expect(trim.label).toBe('saved trim · east-loop-v001');+ });++ it('tolerates missing walk / assets', () => {+ expect(buildTrimmerSources(null)).toEqual([]);+ expect(buildTrimmerSources({ runs: [] }, null)).toEqual([]);+ });+});diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex 62392cb33e..b5a073e849 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -1,6 +1,6 @@import { useEffect, useState, useCallback, useMemo, useRef } from 'react';-import { useParams, useNavigate } from 'react-router-dom';-import { PersonStanding, MapPin, Package, Download, X, RefreshCw, Plus, ChevronRight, ChevronDown } from 'lucide-react';+import { useParams, useNavigate, useSearchParams } from 'react-router-dom';+import { PersonStanding, MapPin, Package, Download, X, RefreshCw, Plus, ChevronRight, ChevronDown, Images, Scissors } from 'lucide-react';import toast from '../components/ui/Toast';import {listSpriteRecords, getSpriteRecord, importSprites, createSpriteRecord,@@ -11,9 +11,12 @@ import { getSettings } from '../services/apiSystem.js';import { deriveAvailableBackends } from '../lib/imageGenBackends.js';import AppContextPicker from '../components/AppContextPicker.jsx';import ReferenceWorkflow from '../components/sprites/ReferenceWorkflow.jsx';-import WalkWorkflow, { WALK_WORKFLOW_DOM_ID, WALK_DURATIONS } from '../components/sprites/WalkWorkflow.jsx';+import WalkWorkflow, { WALK_DURATIONS } from '../components/sprites/WalkWorkflow.jsx';+import LoopTrimmer from '../components/sprites/LoopTrimmer.jsx';import PublishWorkflow from '../components/sprites/PublishWorkflow.jsx';import AssetCollection from '../components/sprites/AssetCollection.jsx';+import TabPills from '../components/ui/TabPills.jsx';+import useDrawerTab from '../hooks/useDrawerTab.js';import { useAsyncAction } from '../hooks/useAsyncAction.js';import { useSpritePendingRenders } from '../hooks/useSpritePendingRenders.js';import { buildCollectionActions } from '../lib/spriteCollectionActions.js';@@ -441,12 +444,24 @@ export default function Sprites() {onChanged: onWorkflowChanged,});- // Which run the Loop Trimmer panel is open for. Phase 5 (#2933) turns this- // into a `?spriteTab=trimmer&run=<id>` deep link; until then it routes the- // collection's request into WalkWorkflow's existing inline TrimPanel so- // there is still exactly one trim UI.- const [trimRunId, setTrimRunId] = useState(null);- useEffect(() => setTrimRunId(null), [id]);+ // Workspace tab (Library / Loop Trimmer) and the run the trimmer is open for+ // live in the URL (#2933) so the active workspace is deep-linkable+ // (`?spriteTab=trimmer&run=<runId>`) — the same "URL is the source of truth+ // for what's open" rule the rest of the app follows. Switching records via+ // navigate() drops the search entirely, resetting the tab to Library.+ const [searchParams, setSearchParams] = useSearchParams();+ const [spriteTab, setSpriteTab] = useDrawerTab('spriteTab', 'library', ['library', 'trimmer']);+ const trimRunParam = searchParams.get('run');+ // Open the trimmer deep-linked to a run. `replace` keeps an in-trimmer source+ // switch out of history; the default push lets Back return to the Library.+ const openTrimmer = useCallback((runId, { replace = false } = {}) => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ next.set('spriteTab', 'trimmer');+ if (runId) next.set('run', runId); else next.delete('run');+ return next;+ }, replace ? { replace: true } : undefined);+ }, [setSearchParams]);// Clip length lives here rather than inside WalkWorkflow so a Regenerate// fired from an asset card honors the length the user picked in the walk@@ -545,15 +560,11 @@ export default function Sprites() {generateAnchor,hasBackend: hasImageBackend,mode: imageMode,- onRequestTrim: (runId) => {- setTrimRunId(runId);- // The trimmer lives inside WalkWorkflow further up the page; a request- // from an asset card near the bottom must bring it into view or the- // click looks like it did nothing.- document.getElementById(WALK_WORKFLOW_DOM_ID)?.scrollIntoView({ behavior: 'smooth', block: 'start' });- },+ // "Edit in Loop Trimmer" from an asset card now switches to the trimmer+ // workspace deep-linked to the run, instead of scrolling to an inline panel.+ onRequestTrim: (runId) => openTrimmer(runId),});- }, [detail, walkRenders.pendingJobs, referenceRenders.pendingJobs, generateWalk, generateAnchor, hasImageBackend, imageMode]);+ }, [detail, walkRenders.pendingJobs, referenceRenders.pendingJobs, generateWalk, generateAnchor, hasImageBackend, imageMode, openTrimmer]);return (<div className="space-y-4">@@ -617,49 +628,79 @@ export default function Sprites() {<p className="text-xs text-gray-500">archetype: {detail.record.spec.archetype}</p>)}</div>+ {/* Library / Loop Trimmer workspaces (#2933). The trimmer is+ character-only (it trims packaged walk runs), so non-character+ records skip the tab bar and always show their asset library. */}{detail.record.kind === 'character' && (- <>- <ReferenceWorkflow- record={detail.record}- reference={detail.reference}- renders={referenceRenders}- backends={imageBackends}- mode={imageMode}- onModeChange={setImageMode}- onChanged={onWorkflowChanged}- />- <WalkWorkflow- record={detail.record}- reference={detail.reference}- walk={detail.walk}- renders={walkRenders}- duration={duration}- onDurationChange={setDuration}- onGenerate={generateWalk}- trimRunId={trimRunId}- onTrimClose={() => setTrimRunId(null)}- onChanged={onWorkflowChanged}- />- {/* Keyed by record so form state and an armed publish/overwrite- confirmation never survive switching characters. */}- <PublishWorkflow- key={detail.record.id}- record={detail.record}- walk={detail.walk}- atlas={detail.atlas}- onChanged={onWorkflowChanged}- />- </>+ <TabPills+ variant="pills"+ size="sm"+ mobileDropdown+ mobileSelectId="sprite-workspace-tab"+ ariaLabel="Sprite workspace"+ tabs={[+ { id: 'library', label: 'Library', icon: Images },+ { id: 'trimmer', label: 'Loop Trimmer', icon: Scissors },+ ]}+ activeTab={spriteTab}+ onChange={setSpriteTab}+ />)}- {detail.assets.length === 0 ? (- <p className="text-sm text-gray-500">No assets on disk for this record.</p>- ) : (- <AssetCollection- recordId={detail.record.id}+ {detail.record.kind === 'character' && spriteTab === 'trimmer' ? (+ <LoopTrimmer+ record={detail.record}+ walk={detail.walk}assets={detail.assets}- actions={collectionActions}- approvedRunIds={approvedRunIds}+ runId={trimRunParam}+ onSelectRun={(runId) => openTrimmer(runId, { replace: true })}+ onSaved={onWorkflowChanged}/>+ ) : (+ <>+ {detail.record.kind === 'character' && (+ <>+ <ReferenceWorkflow+ record={detail.record}+ reference={detail.reference}+ renders={referenceRenders}+ backends={imageBackends}+ mode={imageMode}+ onModeChange={setImageMode}+ onChanged={onWorkflowChanged}+ />+ <WalkWorkflow+ record={detail.record}+ reference={detail.reference}+ walk={detail.walk}+ renders={walkRenders}+ duration={duration}+ onDurationChange={setDuration}+ onGenerate={generateWalk}+ onOpenTrimmer={openTrimmer}+ onChanged={onWorkflowChanged}+ />+ {/* Keyed by record so form state and an armed publish/overwrite+ confirmation never survive switching characters. */}+ <PublishWorkflow+ key={detail.record.id}+ record={detail.record}+ walk={detail.walk}+ atlas={detail.atlas}+ onChanged={onWorkflowChanged}+ />+ </>+ )}+ {detail.assets.length === 0 ? (+ <p className="text-sm text-gray-500">No assets on disk for this record.</p>+ ) : (+ <AssetCollection+ recordId={detail.record.id}+ assets={detail.assets}+ actions={collectionActions}+ approvedRunIds={approvedRunIds}+ />+ )}+ </>)}</div>)}