Skip to content

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

41.2 KB
Raw Blame
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router';
import {
  Check, Film, RefreshCw, Scissors, Lock, Unlock, Terminal, Gauge, RotateCcw, Cpu,
} from 'lucide-react';
import toast from '../ui/Toast';
import {
  approveSpriteWalk, postprocessSpriteWalk, unlockSpriteWalk, reopenSpriteWalk,
} from '../../services/apiSprites.js';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
import Banner from '../ui/Banner.jsx';
import CycleTarget from './CycleTarget.jsx';
import AnimationProviderPicker from './AnimationProviderPicker.jsx';
import { CorrectionNoteToggle, walkCorrectionKey } from './CorrectionNote.jsx';
import SpritePreview from './SpritePreview.jsx';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
import { spriteAssetUrl, checkerboardStyle, PIXELATED } from './spriteAssets.js';
import { GROK_VIDEO_DURATIONS } from '../../lib/grokVideoClip.js';
import {
  WALK_PHASES, WALK_DEFAULT_FRAME_COUNT, WALK_DEFAULT_FPS,
} from '../../lib/spriteTrimmer.js';
import { walkUnlockCopy, WALK_UNLOCK_TOAST } from '../../lib/spriteWalkUnlock.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) 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.

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
// rule reads it from a per-preview custom property instead of hardcoding 8.
const LOOP_KEYFRAMES = '@keyframes sprite-walk-loop { to { background-position-x: var(--sprite-walk-loop-end) } }';
// Clip length only decides how much source footage the packer can choose from;
// the CYCLE'S look (walk vs run) comes from the frame-count + speed controls.
// The offered lengths live in lib/grokVideoClip.js — see there for why 6/10/15 s
// are the only ones (#3022).

// Delivered clip length for a run, when the server managed to probe it
// (`sourceVideoSeconds` is absent on older runs and when ffprobe is missing —
// absent means UNKNOWN, so render nothing rather than implying a 0s clip).
// A mismatch against the requested `duration` is worth surfacing: it is the
// visible evidence that grok rendered something other than what was asked for.
function clipLengthLabel(run) {
  const delivered = Number(run?.sourceVideoSeconds);
  if (!(delivered > 0)) return null;
  const requested = Number(run?.duration);
  const mismatch = requested > 0 && Math.abs(requested - delivered) >= 0.5;
  // A truncated clip (a real but near-zero-length file) must not round to the
  // "0.0s" that would read as the absent case handled above — give sub-0.05s
  // lengths the extra digit so a broken clip looks broken, not unknown.
  const shown = delivered.toFixed(delivered < 0.05 ? 2 : 1);
  return {
    text: `${shown}s clip${mismatch ? ` (asked ${requested}s)` : ''}`,
    mismatch,
  };
}

// The deterministic-postprocess authoring knobs (frame count + preview fps) and
// their option lists moved to lib/spriteTrimmer.js (#2980) — the Loop Trimmer's
// re-derive control offers the same set-level target, and two copies of the
// bounds would be exactly the drift #2985 exists to prevent.

/**
 * Strip geometry for a preview/trim UI, defaulting to the native 8-phase
 * packaging when a run predates (or omits) the richer stripPreview fields.
 */
function stripGeometry(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) : 12;
  const cellWidth = Number(stripPreview?.cellWidth);
  const cellHeight = Number(stripPreview?.cellHeight);
  const aspect = cellWidth > 0 && cellHeight > 0 ? cellHeight / cellWidth : 1;
  return { frameCount, fps, height: Math.round(CELL_PX * aspect) };
}

// Animated preview of a packed strip: the strip PNG as a stepped background
// animation (8 frames at 12fps ≈ 0.67s per loop for a native run; an imported
// 12-frame redraw cycle steps 12 times over 1s).
function StripLoop({ recordId, stripPreview }) {
  const { frameCount, fps, height } = stripGeometry(stripPreview);
  const scrub = CELL_PX * frameCount;
  // 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 a
  // client-side preload probe as defense-in-depth: a strip that fails to load
  // for any other reason shows an explicit placeholder instead of a silent gap.
  const [failed, setFailed] = useState(false);
  useEffect(() => {
    setFailed(false);
    const img = new Image();
    img.onerror = () => setFailed(true);
    img.src = url;
    return () => { img.onerror = null; };
  }, [url]);
  if (failed) {
    return (
      <div
        className="border border-port-error/60 rounded flex items-center justify-center text-[9px] leading-tight text-port-error text-center px-1"
        style={{ width: CELL_PX, height }}
      >
        strip missing
      </div>
    );
  }
  return (
    // The loop paints the strip as its OWN background-image, so it can't also
    // carry the checkerboard — that goes on a wrapper sized to match, and shows
    // through the frame's alpha (#2930). SpritePreview doesn't fit here: there
    // is no <img>, the animation is a stepped background scrub.
    // `overflow-hidden` matters: the strip is painted by the INNER div, whose
    // corners are square, so without clipping it covers the rounded corners.
    <div
      className="border border-port-border rounded overflow-hidden"
      style={{ width: CELL_PX, height, ...checkerboardStyle(6) }}
    >
      <div
        role="img"
        aria-label="walk loop preview"
        className="w-full h-full"
        style={{
          // Quoted: encodeURIComponent leaves `(`/`)` intact, and an externally
          // authored redraw filename containing one would end the url() token early.
          backgroundImage: `url("${url}")`,
          backgroundSize: `${scrub}px ${height}px`,
          ...PIXELATED,
          '--sprite-walk-loop-end': `-${scrub}px`,
          animation: `sprite-walk-loop ${(frameCount / fps).toFixed(3)}s steps(${frameCount}) infinite`,
        }}
      />
    </div>
  );
}

// How a drifted direction gets back onto the target, given what it still has
// behind it. Named rather than inlined as a nested ternary so the three cases
// read as the decision they are.
// Whether a run can be re-derived without a new render. The server resolves
// `sourceVideoPath` against disk and flags `sourceClipMissing` when the clip the
// record names isn't there, so "declares a clip" and "has one" never read the
// same. Named once because every affordance below gates on it — and the header's
// Unlock and a card's Reopen disagreeing about the same run would be a bug.
const hasClip = (run) => Boolean(run?.sourceVideoPath) && !run?.sourceClipMissing;

/**
 * The set-level Unlock, as a trigger that swaps to an inline confirm.
 *
 * Both frozen-set entry points render this: the header's plain Unlock and the
 * blocked panel's "Unlock anyway". They differ only in copy and tone, and they
 * are mutually exclusive on `unlockBlocked` — sharing the shape keeps a change to
 * the confirm UX (busy text, tone, aria convention) from having to be made twice
 * and landing in only one of the two frozen-set paths.
 */
function UnlockAffordance({
  armed, onArm, onCancel, onConfirm, busy, label, prompt, ariaLabel, title, className,
}) {
  if (armed) {
    return (
      <ConfirmButtonPair
        prompt={prompt}
        confirmText={label}
        confirmIcon={Unlock}
        busy={busy}
        busyText="Unlocking…"
        tone="warning"
        ariaLabel={ariaLabel}
        onConfirm={onConfirm}
        onCancel={onCancel}
      />
    );
  }
  return (
    <button
      onClick={onArm}
      title={title}
      className={`flex items-center gap-1 px-1.5 py-0.5 text-xs border rounded ${className}`}
    >
      <Unlock className="w-3 h-3" /> {label}
    </button>
  );
}

// The one remedy for an imported direction with nothing behind it. The clip is
// the importer's to bring across, so authoring a new version by hand isn't it.
const REIMPORT_REMEDY = 're-import this character to bring its source clip across';

const driftRemedy = ({ approved, hasSourceClip, imported }) => {
  // Evidence, not provenance: the server gates re-derivation on whether the
  // direction's clip is actually on disk, so an imported direction whose clip
  // came across re-derives exactly like a native one. Only a direction with no
  // clip behind it is a dead end — and for an import the fix is re-importing the
  // character, not authoring a new version by hand.
  if (!hasSourceClip) {
    return imported ? REIMPORT_REMEDY : 'import this direction\'s source clip to re-derive it';
  }
  if (approved) return 'reopen this direction to re-derive it from its clip';
  return 'reprocess it from its clip';
};

function DirectionCard({
  recordId, direction, anchorLocked, anchorPath, run, approved, finalized, pending,
  onOpenTrimmer, onGenerate, onApprove, onRetry, onReprocess, onReopen,
  reprocessing, retrying, cycleLabel, drift, targetSaving, imported,
  corrections, onCorrectionChange,
}) {
  const [confirming, setConfirming] = useState(false);
  const [reopening, setReopening] = useState(false);
  const candidate = run?.status === 'candidate' ? run : null;
  // grok renders as an observable TUI session while status is 'rendering'; the
  // deterministic packaging follows as 'postprocessing'. Both block a second
  // Generate (server truth, since the client pending flag drops once the run is
  // persisted). Only 'rendering' has a live Shell session to link to.
  const rendering = run?.status === 'rendering';
  const supersededAnchor = run?.status === 'superseded-anchor';
  // `targetSaving` blocks the render actions without claiming the direction is
  // rendering: the set's cycle target is mid-PATCH, so a queue now would be
  // gated against a value the server hasn't persisted yet (409 target mismatch).
  const inFlight = pending || rendering || run?.status === 'postprocessing';
  const busy = inFlight || targetSaving;
  // Any run that carries a packed strip preview is trimmable — the trim service
  // resolves geometry from the run's own manifest/stripPreview regardless of
  // on-disk layout (native `runs/`, legacy `grok/`, imported `runs/`, or an
  // imagegen redraw), so there's no vendor-directory coupling here anymore. 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) && !supersededAnchor;
  // Before a packaged animation exists, keep the exact locked directional
  // anchor visible in the card. It is the idle/source pose the walk will be
  // conditioned on, and reviewing it here prevents spending a render on a
  // direction whose identity or anatomy is already wrong. A candidate or
  // approved strip replaces it as soon as there is an animation to inspect.
  const hasWalkPreview = Boolean((approved || candidate) && run?.stripPreview?.stripPath);
  const hasSourceClip = hasClip(run);
  // The server stamps the reopen block with the exact same resolver that will
  // validate the POST. A missing block from an older peer remains an ordinary
  // reopen; only a stamped block changes the affordance.
  const reopenCopy = walkUnlockCopy(run?.reopen, { mode: 'reopen', direction });
  const reopenBlocked = Boolean(reopenCopy);
  const statusLabel = approved ? 'approved'
    : (pending || rendering) ? 'rendering…'
      : run?.status === 'postprocessing' ? 'packaging…'
        : supersededAnchor ? 'anchor revised'
          : run?.status || (anchorLocked ? 'ready' : 'anchor not locked');
  // What grok actually delivered, probed server-side — the durable answer to
  // "does the clip length picker do anything?", which used to live only in
  // contradicting code comments (#3022).
  const clipLength = clipLengthLabel(run);

  return (
    <div className="bg-port-bg border border-port-border rounded p-2 space-y-1.5">
      <p className="text-xs text-gray-400 flex items-center justify-between">
        {direction}
        <span className={`text-[10px] ${approved ? 'text-port-success' : run?.status === 'error' ? 'text-port-error' : 'text-gray-500'}`}>
          {approved && <Check className="w-3 h-3 inline mr-0.5" />}{statusLabel}
        </span>
      </p>

      {clipLength && (
        <p
          className={`text-[10px] ${clipLength.mismatch ? 'text-port-warning' : 'text-gray-500'}`}
          title={clipLength.mismatch
            ? 'grok delivered a different clip length than requested — its image_to_video tool renders only 6, 10 or 15 s'
            : 'Source clip length grok delivered (probed from the file)'}
        >
          {clipLength.text}
        </p>
      )}

      {hasWalkPreview && (
        <StripLoop recordId={recordId} stripPreview={run.stripPreview} />
      )}
      {!hasWalkPreview && anchorLocked && anchorPath && (
        <div className="flex items-end gap-2">
          <SpritePreview
            recordId={recordId}
            path={anchorPath}
            alt={`${direction} reference idle pose`}
            className="h-24 w-24 shrink-0 rounded border border-port-border"
            zoomable
          />
          <span className="pb-1 text-[9px] leading-tight text-gray-600">reference idle</span>
        </div>
      )}
      {supersededAnchor && (
        <p className="rounded border border-port-warning/40 px-1.5 py-1 text-[10px] leading-tight text-port-warning">
          Previous walk kept in history · generate again from the current anchor.
        </p>
      )}

      {/* This direction is packaged at a geometry the set is no longer targeting
          (#2985) — surfaced HERE rather than at atlas-compile time, which used to
          be the first and only place a ragged set showed up. The remedy depends
          on what the direction still has behind it: an unapproved candidate can
          be re-derived from its on-disk clip with the Reprocess button below, an
          approved one has to be reopened first, and a clipless import follows
          the server-backed reopen recovery shown below. */}
      {drift && (
        <p className="text-[10px] text-port-warning border border-port-warning/60 rounded px-1.5 py-1 leading-tight">
          {[drift.frameCountDrifts && `${drift.frameCount}f`, drift.fpsDrifts && `${drift.fps}fps`]
            .filter(Boolean).join(' · ')} · re-derive to {cycleLabel}
          <span className="block text-gray-400">
            {driftRemedy({ approved, hasSourceClip, imported })}
          </span>
        </p>
      )}

      {/* The server dropped this run's stripPath because its packed strip is
          gone on disk (stripMissing) — render an explicit indicator in place of
          the blank loop, pointing at the recovery that actually works for this
          direction's state: a finalized direction uses its server-backed walk
          action, while an unapproved candidate can just be regenerated (the
          Generate button below). Deliberately not the status==='error' path, which offers a
          "Retry postprocess" that 409s for a finalized/approved run. */}
      {(approved || candidate) && run?.stripMissing && (
        <p className="text-[10px] text-port-error border border-port-error/60 rounded px-1.5 py-1 leading-tight">
          {/* A missing strip has its own recovery path. The action below carries
              the server's exact reopen/unlock decision, including whether a
              clipless import can be regenerated from its locked anchor. */}
          Walk strip missing on disk — {finalized
            ? 'use the walk action below to regenerate this direction' : 'regenerate to repack it'}.
        </p>
      )}

      {/* grok animates in an observable TUI session — link into the Shell page
          to watch it, and (if needed) type to course-correct or Stop it. The
          session exists only while the render is live ('rendering'). */}
      {rendering && run?.shellSession && (
        <Link
          to={`/shell/${run.shellSession}`}
          title="Watch grok render this walk in the Shell (observe / course-correct / stop)"
          className="flex items-center gap-1 w-full justify-center px-2 py-0.5 text-xs bg-port-card border border-port-accent rounded text-port-accent hover:bg-port-accent hover:text-white"
        >
          <Terminal className="w-3 h-3" /> Watch in Shell
        </Link>
      )}

      {/* The local lane has no PTY to attach to, so its observability is the
          Render Queue row for the job — same slot, same shape, so a rendering
          card is never a dead end on either lane. Mutually exclusive with the
          Shell link above: a run carries a shellSession OR a jobId. */}
      {rendering && !run?.shellSession && run?.jobId && (
        <Link
          to="/system-resources/queues"
          title="Watch this local render in the Render Queue (progress / cancel)"
          className="flex items-center gap-1 w-full justify-center px-2 py-0.5 text-xs bg-port-card border border-port-accent rounded text-port-accent hover:bg-port-accent hover:text-white"
        >
          <Cpu className="w-3 h-3" /> Watch in Render Queue
        </Link>
      )}

      {/* Retry also covers a run wedged at 'postprocessing' (crash between
          the video copy and the packaged save) — the endpoint is the
          documented recovery path and validates readiness server-side. */}
      {(run?.status === 'error' || run?.status === 'postprocessing') && (
        <div className="space-y-1">
          {/* Even when packaging failed, grok still produced a clip — show it so
              the render isn't a dead end. The raw clip carries its own magenta
              matte (not transparent), so no checkerboard behind it. */}
          {run.status === 'error' && hasSourceClip && (
            <video
              src={spriteAssetUrl(recordId, run.sourceVideoPath)}
              className="w-full rounded border border-port-border"
              autoPlay
              loop
              muted
              playsInline
              controls
              aria-label={`raw grok walk clip (${direction})`}
            />
          )}
          {run.status === 'error' && (
            <p role="status" className="text-[10px] text-port-error break-words">{run.postprocessError || 'postprocess failed'}</p>
          )}
          {/* Gated on the in-flight target write (it repacks against the set
              target, so firing it before a target PATCH lands would use the
              value the server still holds) — but deliberately NOT on `busy`:
              that includes status==='postprocessing', which is precisely the
              wedged state this button exists to recover (attachTuiWalkResult
              persists 'postprocessing' before packaging, and nothing normalizes
              it if the server dies mid-package). Disabling on `busy` would make
              the "Re-run postprocess" branch permanently unclickable and leave
              that direction with no enabled action at all. */}
          <button onClick={() => onRetry(run)} disabled={pending || targetSaving || retrying} className="px-2 py-0.5 text-[10px] bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50">
            {retrying ? 'Repacking…' : run.status === 'postprocessing' ? 'Re-run postprocess' : 'Retry postprocess'}
          </button>
        </div>
      )}

      {!finalized && !approved && (
        <div className="space-y-1.5">
          {/* Correction note for the NEXT render (#3134) — the same key the
              asset-collection walk card writes, so a note typed on either
              surface is visible on both and rides whichever Generate fires.
              Hidden when this direction can't be rendered at all. */}
          {anchorLocked && onCorrectionChange && (
            <CorrectionNoteToggle
              noteKey={walkCorrectionKey(direction)}
              label={`${direction} walk cycle`}
              corrections={corrections}
              onChange={onCorrectionChange}
              placeholder="Correction (optional), e.g. the legs barely lift"
            />
          )}
          <button
            onClick={() => onGenerate(direction)}
            disabled={!anchorLocked || busy}
            title={anchorLocked ? undefined : 'Lock this direction\'s reference anchor first'}
            className="flex items-center gap-1 w-full justify-center px-2 py-1 text-xs bg-port-card border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
          >
            {inFlight
              ? <><RefreshCw className="w-3 h-3 animate-spin" /> {run?.status === 'postprocessing' ? 'Packaging…' : 'Rendering…'}</>
              : <><Film className="w-3 h-3" /> {candidate ? 'Regenerate' : 'Generate walk'}</>}
          </button>
          {/* Re-derive the loop from the clip ALREADY on disk at the current
              frame-count/speed — no grok call, no new paid render. This is the
              "make a better/slower cycle from what we have" action. */}
          {candidate && (
            <button
              onClick={() => onReprocess(run)}
              disabled={busy || reprocessing}
              title={`Rebuild this loop from the existing clip at ${cycleLabel} (no regeneration)`}
              className="flex items-center gap-1 w-full justify-center px-2 py-0.5 text-xs bg-port-bg border border-port-border rounded text-gray-300 hover:border-port-accent disabled:opacity-50"
            >
              {reprocessing
                ? <><RefreshCw className="w-3 h-3 animate-spin" /> Reprocessing…</>
                : <><Gauge className="w-3 h-3" /> Reprocess · {cycleLabel}</>}
            </button>
          )}
          {candidate && (
            confirming ? (
              <ConfirmButtonPair
                className="flex-wrap"
                prompt="Approve?"
                confirmText="Yes"
                cancelText="No"
                confirmIcon={Check}
                tone="success"
                ariaLabel={`Confirm approve ${direction}`}
                onConfirm={() => { setConfirming(false); onApprove(direction, candidate.id); }}
                onCancel={() => setConfirming(false)}
              />
            ) : (
              // Approval is where a direction's geometry gets frozen into the
              // set the atlas compiles, so a drifted candidate can't be approved
              // — the server refuses it, and offering the button anyway would
              // just hand back a 409 after the click. Same for a run still
              // packaged by the source pipeline: its per-frame images were never
              // imported, so approving it 409s RUN_FRAMES_MISSING however well its
              // geometry happens to match. Reprocessing from the clip is the way
              // through, and it clears the flag.
              <button
                onClick={() => setConfirming(true)}
                disabled={Boolean(drift) || Boolean(run?.importedPackaging)}
                title={run?.importedPackaging
                  ? 'This run was packaged by the source pipeline, which kept its frames — reprocess it from its clip first'
                  : drift ? `Re-derive this direction to ${cycleLabel} before approving it` : undefined}
                className="min-h-[36px] w-full px-2 py-0.5 text-xs bg-port-success/20 border border-port-success rounded text-port-success disabled:opacity-50"
              >
                Approve
              </button>
            )
          )}
        </div>
      )}

      {/* Re-open just THIS approved direction so it can be regenerated /
          reprocessed / re-approved — for when one walk is too fast or wrong and
          the rest are fine. Un-freezes a finalized set but keeps the other seven
          approvals; the rendered clip is preserved, so re-approval is one click.
          A stamped blocked branch names the fresh-render cost before sending the
          acknowledgement; an ordinary branch stays the compact existing action. */}
      {approved && (reopenBlocked ? (
        <Banner tone="warning" size="sm" icon={RotateCcw} className="space-y-1.5">
          <p className="leading-relaxed">{reopenCopy.text}</p>
          {reopenCopy.action && (reopening ? (
            <ConfirmButtonPair
              prompt={reopenCopy.prompt}
              confirmText={reopenCopy.action}
              confirmIcon={RotateCcw}
              tone="warning"
              ariaLabel={`Confirm reopen ${direction} without source clips`}
              onConfirm={() => {
                setReopening(false);
                onReopen(direction, reopenCopy.acknowledgeNoClips, reopenCopy.toast);
              }}
              onCancel={() => setReopening(false)}
            />
          ) : (
            <button
              onClick={() => setReopening(true)}
              className="flex items-center gap-1 px-1.5 py-0.5 text-xs bg-port-bg border border-port-warning/60 rounded text-port-warning hover:bg-port-warning/10"
            >
              <RotateCcw className="w-3 h-3" /> {reopenCopy.action}
            </button>
          ))}
        </Banner>
      ) : (
        reopening ? (
          <ConfirmButtonPair
            prompt={finalized ? 'Reopen (un-freezes set)?' : 'Reopen this direction?'}
            confirmText="Reopen"
            confirmIcon={RotateCcw}
            tone="warning"
            ariaLabel={`Confirm reopen ${direction}`}
            onConfirm={() => { setReopening(false); onReopen(direction); }}
            onCancel={() => setReopening(false)}
          />
        ) : (
          <button
            onClick={() => setReopening(true)}
            title="Re-open this direction to regenerate or reprocess it (rendered clip is kept)"
            className="flex items-center gap-1 w-full justify-center px-2 py-0.5 text-xs bg-port-bg border border-port-border rounded text-gray-400 hover:border-port-accent hover:text-white"
          >
            <RotateCcw className="w-3 h-3" /> Reopen
          </button>
        )
      ))}

      {/* 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>
  );
}

export default function WalkWorkflow({
  record, reference, walk, renders, duration, onDurationChange, onGenerate,
  onOpenTrimmer = () => {}, onChanged, corrections = null, onCorrectionChange = null,
  providers = null, provider = 'grok', onProviderChange = () => {},
  providersError = null, onRetryProviders = null,
}) {
  const recordId = record.id;
  // The cycle target is server-resolved (app contract → set pin → first approved
  // direction → default) so the client never re-derives the precedence chain.
  // The fallback only covers a walk state fetched by an older client/peer.
  const target = walk?.walkTarget || {
    frameCount: WALK_DEFAULT_FRAME_COUNT, fps: WALK_DEFAULT_FPS, source: 'default', drift: [],
  };
  const { frameCount, fps } = target;
  const driftByDirection = useMemo(
    () => Object.fromEntries((target.drift || []).map((d) => [d.direction, d])),
    [target.drift],
  );
  // Every render action is gated on the target PATCH settling — otherwise the
  // user picks a new target and clicks Generate before the server has it, and
  // the queue-time guard 409s on a value they already changed.
  const [targetSaving, setTargetSaving] = useState(false);
  const manifest = reference?.manifest || null;
  const runs = walk?.runs || [];
  const selection = walk?.selection || null;
  const finalized = Boolean(walk?.walkSet);
  // A source-pipeline import (#2895) still carries directions PortOS cannot
  // compile from. The server stamps both the set-level flag and the precise
  // per-direction list, so the client never re-derives the path convention — and
  // a card reads the fact about ITS OWN direction rather than a set-wide
  // approximation, since directions leave the list one at a time as they are
  // re-derived. An older peer's walk state may carry only the boolean; fall back
  // to it so every direction still reads as imported there.
  const importedWalkSet = Boolean(walk?.walkSet?.imported);
  const importedDirections = walk?.walkSet?.importedDirections || null;
  const isImportedDirection = (direction) => (importedDirections
    ? importedDirections.includes(direction) : importedWalkSet);
  // Whether unlock is refused, and whether that refusal can be acknowledged past,
  // is stamped by the server from the same resolver its own gate uses (#3043) —
  // so the button offered here and the 409 it might hit can never be computed
  // from two different readings of the same set. The copy is shared with the Loop
  // Trimmer's lock block; null means "not blocked, offer the ordinary Unlock".
  const unlockCopy = walkUnlockCopy(walk?.walkSet?.unlock);
  const unlockBlocked = Boolean(unlockCopy);

  // direction → jobId for in-flight video renders. The hook instance is owned
  // by the Sprites page and shared with the asset collection (#2931) so both
  // Generate buttons gate on ONE map — a second instance here would let a
  // Regenerate fired from an asset card leave this button enabled, inviting a
  // duplicate paid render for the same direction. The generate ACTION lives up
  // there too, so both entry points submit through one code path.
  const { pendingJobs } = renders;

  const latestRunByDirection = useMemo(() => {
    const byDir = {};
    for (const run of runs) {
      // runs arrive newest-first; prefer the approved run when one exists.
      if (!byDir[run.direction]) byDir[run.direction] = run;
    }
    for (const [direction, sel] of Object.entries(selection?.directions || {})) {
      const approvedRun = runs.find((r) => r.id === sel.runId);
      if (approvedRun) byDir[direction] = approvedRun;
    }
    return byDir;
  }, [runs, selection]);

  const [approve] = useAsyncAction(async (direction, runId) => {
    await approveSpriteWalk(recordId, { direction, runId }, { silent: true });
    toast.success(`Walk ${direction} approved`);
    onChanged();
  }, { errorMessage: 'Approve failed' });

  // Re-run the deterministic packer on a run's ON-DISK clip at the CURRENT
  // frame-count/speed — the one call shared by the errored-run "Retry" and the
  // candidate "Reprocess" buttons (no grok, no regeneration).
  // Geometry is deliberately NOT sent: the server adopts the set's pinned target
  // for an omitted count/fps, so the request can't 409 against a target this
  // page's state is one refetch behind on (#2985).
  const postprocessRun = (run) => postprocessSpriteWalk(recordId, { runId: run.id }, { silent: true });

  // Retry a wedged/errored run so a recovery also picks up the chosen cycle look.
  const [retryPostprocess, retrying] = useAsyncAction(async (run) => {
    await postprocessRun(run);
    toast.success('Postprocess complete');
    onChanged();
  }, { errorMessage: 'Postprocess failed' });

  // Reprocess a candidate. Track the in-flight direction so only that card spins.
  const [reprocessingDir, setReprocessingDir] = useState(null);
  const [reprocess] = useAsyncAction(async (run) => {
    setReprocessingDir(run.direction);
    try {
      await postprocessRun(run);
      toast.success(`Walk ${run.direction} reprocessed · ${frameCount}f @ ${fps}fps`);
      onChanged();
    } finally {
      setReprocessingDir(null);
    }
  }, { errorMessage: 'Reprocess failed' });

  // Re-open ONE approved direction (finer-grained than the set-wide Unlock).
  const [reopen] = useAsyncAction(async (direction, acknowledgeNoClips = false, successMessage = null) => {
    await reopenSpriteWalk(recordId, { direction, acknowledgeNoClips }, { silent: true });
    toast.success(successMessage || `Walk ${direction} reopened — regenerate or reprocess it`);
    onChanged();
  }, { errorMessage: 'Reopen failed' });

  // Unlock (un-freeze) the finalized walk set. Irreversible-ish (it re-opens
  // every direction), so it's gated behind an inline confirm per the repo's
  // confirmation UX — not a hidden two-click arm or a browser dialog.
  // ONE flag for both entry points below (the header's plain Unlock and the
  // blocked panel's "Unlock anyway"): they are mutually exclusive on
  // `unlockBlocked`, so only one is ever mounted. A third entry point would need
  // its own flag, or it would arm silently alongside whichever of these is live.
  const [unlockConfirm, setUnlockConfirm] = useState(false);
  // `acknowledgeNoClips` is sent ONLY from the blocked-but-regenerable branch,
  // whose panel names what it costs (a fresh render per direction). Every other
  // unlock omits it and keeps the server's refusal — an override the user was
  // never warned about is exactly what the guard exists to prevent.
  const [unlock, unlocking] = useAsyncAction(async (acknowledgeNoClips = false) => {
    await unlockSpriteWalk(recordId, { acknowledgeNoClips }, { silent: true });
    setUnlockConfirm(false);
    toast.success((acknowledgeNoClips && unlockCopy?.toast) || WALK_UNLOCK_TOAST);
    onChanged();
  }, { errorMessage: 'Unlock failed' });

  // The walk workflow only becomes actionable once the main is frozen (the
  // south anchor IS the main); hide it entirely before that.
  if (!manifest?.mainReference?.locked) return null;

  const approvedCount = Object.values(selection?.directions || {})
    .filter((d) => d?.status === 'approved').length;

  const cycleLabel = `${frameCount}f @ ${fps}fps`;
  const driftCount = (target.drift || []).length;

  return (
    <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">
          <Film className="w-4 h-4" /> Walk Cycles
          <span className="text-xs font-normal text-gray-500">
            {finalized ? 'finalized' : `${approvedCount}/8 approved`}
          </span>
        </h3>
        {finalized ? (
          <div className="flex items-center gap-2">
            <p className="text-xs text-port-success flex items-center gap-1">
              <Lock className="w-3 h-3" /> walk set frozen · immutable
            </p>
            {unlockBlocked ? (
              // The block itself is explained (and acted on) in the panel below —
              // it needs more room than this dense row, and a consequence this
              // expensive must not live in a tooltip.
              <span className="text-[10px] text-gray-500">imported · no clips to re-derive</span>
            ) : (
              <UnlockAffordance
                armed={unlockConfirm}
                onArm={() => setUnlockConfirm(true)}
                onCancel={() => setUnlockConfirm(false)}
                onConfirm={() => unlock()}
                busy={unlocking}
                label="Unlock"
                prompt="Re-open all directions?"
                ariaLabel="Confirm unlock walk set"
                title="Un-freeze the walk set to regenerate or re-approve directions (rendered clips are kept)"
                className="bg-port-bg border-port-border text-gray-400 hover:border-port-accent hover:text-white"
              />
            )}
          </div>
        ) : (
          <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
            <CycleTarget
              recordId={recordId}
              target={target}
              disabled={finalized}
              onChanged={onChanged}
              onSavingChange={setTargetSaving}
            />
            <AnimationProviderPicker
              id={`walk-provider-${recordId}`}
              providers={providers}
              provider={provider}
              onChange={onProviderChange}
              disabled={finalized}
              error={providersError}
              onRetry={onRetryProviders}
            />
            <label className="flex items-center gap-1.5 text-xs text-gray-400" htmlFor={`walk-clip-${recordId}`} title={provider === 'local'
                ? "The local model renders on a fixed frame grid, so this length is snapped to the nearest legal clip. Length only affects how much source footage the packer has to choose from, not the walk's speed."
                : "grok renders 6, 10 or 15 s clips — these are the only lengths it offers, and a shorter request comes back as 6s. Length only affects how much source footage the packer has to choose from, not the walk's speed."}>
              Clip
              <select
                id={`walk-clip-${recordId}`}
                value={duration}
                onChange={(e) => onDurationChange(Number(e.target.value))}
                className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
              >
                {GROK_VIDEO_DURATIONS.map((d) => <option key={d} value={d}>{d}s</option>)}
              </select>
            </label>
          </div>
        )}
      </div>

      {/* Why the frozen set refuses a plain Unlock, and the one action that gets
          past it. Before #3043 this was a tooltip on a dead label, which left a
          fully-imported set with no reachable way to revise anything — not the
          cycle target, not one direction. The cost is stated as visible text
          rather than a title, per the repo's "tooltip-only warnings are missed on
          touch" rule; `copy.action` is null when even regeneration is out, and
          then there is genuinely nothing to offer. */}
      {unlockBlocked && (
        <Banner tone="warning" size="sm" icon={Unlock} className="space-y-1.5">
          <p className="leading-relaxed">{unlockCopy.text}</p>
          {unlockCopy.action && (
            <UnlockAffordance
              armed={unlockConfirm}
              onArm={() => setUnlockConfirm(true)}
              onCancel={() => setUnlockConfirm(false)}
              onConfirm={() => unlock(true)}
              busy={unlocking}
              label={unlockCopy.action}
              prompt={unlockCopy.prompt}
              ariaLabel="Confirm unlock walk set without source clips"
              className="bg-port-bg border-port-warning/60 text-port-warning hover:bg-port-warning/10"
            />
          )}
        </Banner>
      )}

      {/* Set-level drift summary: visible BEFORE eight renders are spent, rather
          than as an atlas-compile wall afterwards. Legacy mixed sets (generated
          back when the count/fps were per-render page state) land here on load. */}
      {driftCount > 0 && (
        <p className="text-xs text-port-warning border border-port-warning/60 rounded px-2 py-1.5">
          {driftCount === 1
            ? `1 of 8 packaged directions differs from the ${cycleLabel} target — re-derive it before compiling the atlas.`
            : `${driftCount} of 8 packaged directions differ from the ${cycleLabel} target — re-derive them before compiling the atlas.`}
        </p>
      )}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {(manifest.anchors || []).map((anchor) => (
          <DirectionCard
            key={anchor.direction}
            recordId={recordId}
            direction={anchor.direction}
            anchorLocked={anchor.status === 'locked'}
            anchorPath={anchor.path}
            run={latestRunByDirection[anchor.direction] || null}
            approved={selection?.directions?.[anchor.direction]?.status === 'approved'}
            finalized={finalized}
            pending={Boolean(pendingJobs[anchor.direction])}
            targetSaving={targetSaving}
            drift={driftByDirection[anchor.direction] || null}
            imported={isImportedDirection(anchor.direction)}
            onOpenTrimmer={onOpenTrimmer}
            onGenerate={onGenerate}
            onApprove={approve}
            onRetry={retryPostprocess}
            retrying={retrying}
            onReprocess={reprocess}
            onReopen={reopen}
            reprocessing={reprocessingDir === anchor.direction}
            cycleLabel={cycleLabel}
            corrections={corrections}
            onCorrectionChange={onCorrectionChange}
          />
        ))}
      </div>
    </div>
  );
}