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

44.6 KB
Raw Blame
import { describe, it, expect, vi } from 'vitest';
import {
  render, screen, act, fireEvent, cleanup, waitFor,
} from '@testing-library/react';
import { MemoryRouter } from 'react-router';

// Coverage for the walk viewer's loop preview (#2924). The load-bearing behavior:
// the stepped background animation is derived from the packaged strip's own
// geometry, so a 12-frame imported redraw cycle animates over 12 steps while a
// native 8-phase run keeps stepping 8 times.

vi.mock('../../services/apiSprites.js', () => ({
  generateSpriteWalk: vi.fn(),
  approveSpriteWalk: vi.fn(() => Promise.resolve({})),
  postprocessSpriteWalk: vi.fn(() => Promise.resolve({})),
  unlockSpriteWalk: vi.fn(() => Promise.resolve({})),
  reopenSpriteWalk: vi.fn(() => Promise.resolve({})),
  setSpriteWalkTarget: vi.fn(() => Promise.resolve({})),
}));

import WalkWorkflow from './WalkWorkflow';
import {
  postprocessSpriteWalk, reopenSpriteWalk, setSpriteWalkTarget, unlockSpriteWalk,
} from '../../services/apiSprites.js';

const CELL_PX = 96;

// The render-tracking hook is owned by the Sprites page now (#2931) and passed
// in, so the suite supplies it as a prop instead of mocking the module.
const noRenders = () => ({
  pendingJobs: {}, beginSubmit: vi.fn(), resolveSubmit: vi.fn(), cancelSubmit: vi.fn(),
});

const renderWalk = (stripPreview, props = {}) => {
  const run = {
    id: 'run-east', direction: 'east', status: 'approved', stripPreview,
  };
  render(
    <WalkWorkflow
      record={{ id: 'example-walker' }}
      reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked', path: 'reference/example-walker-east-v1.png' }] } }}
      walk={{
        runs: [run],
        selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
        walkSet: null,
      }}
      renders={noRenders()}
      duration={6}
      onDurationChange={vi.fn()}
      onGenerate={vi.fn()}
      onChanged={vi.fn()}
      {...props}
    />,
  );
  return screen.getByRole('img', { name: 'walk loop preview' });
};

const APPROVED_STRIP = {
  stripPath: 'grok/run-east/generated/example-walk-east-strip.png',
  frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384,
};

describe('WalkWorkflow loop preview', () => {
  it('steps a native 8-frame strip 8 times over its 12fps cycle', () => {
    const loop = renderWalk({
      stripPath: 'grok/walk-east-abc/generated/strip.png',
      frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
    });
    expect(loop.style.animation).toContain('steps(8)');
    expect(loop.style.animation).toContain('0.667s');
    expect(loop.style.backgroundSize).toBe(`${CELL_PX * 8}px ${CELL_PX}px`);
  });

  // The imported redraw cycle (#2924) packs 12 frames — the pre-fix hardcoded
  // steps(8)/-768px scrub cropped it to two thirds of the stride and skewed the gait.
  it('steps an imported 12-frame redraw strip 12 times', () => {
    const loop = renderWalk({
      stripPath: 'imagegen/v19/strip-video-12-clean-alpha.png',
      frameCount: 12, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
    });
    expect(loop.style.animation).toContain('steps(12)');
    expect(loop.style.animation).toContain('1.000s');
    expect(loop.style.backgroundSize).toBe(`${CELL_PX * 12}px ${CELL_PX}px`);
    expect(loop.style.getPropertyValue('--sprite-walk-loop-end')).toBe(`-${CELL_PX * 12}px`);
    // The custom property and the @keyframes rule are two halves of one
    // mechanism — pinning only the property would let the keyframe revert to
    // its pre-fix hardcoded -768px scrub with the suite still green.
    expect(document.querySelector('style').textContent).toContain('var(--sprite-walk-loop-end)');
    expect(loop.style.backgroundImage).toContain('/data/sprites/example-walker/imagegen/v19/strip-video-12-clean-alpha.png');
  });

  it('falls back to the native 8-phase geometry when the strip carries no frame count', () => {
    const loop = renderWalk({ stripPath: 'grok/walk-east-abc/generated/strip.png' });
    expect(loop.style.animation).toContain('steps(8)');
    expect(loop.style.backgroundSize).toBe(`${CELL_PX * 8}px ${CELL_PX}px`);
  });

  // #3020: the packer rewrites the strip IN PLACE, and a CSS background-image at
  // an unchanged URL is reused from the already-decoded image with no request —
  // so the mount's ETag never revalidates. Reprocessing 8f → 12f then stepped the
  // NEW geometry over the OLD 8-cell strip: a jumpy, mis-centered toggle until a
  // manual reload. The content token in the URL is what forces the repaint.
  describe('strip cache-busting', () => {
    it('versions the strip URL with the token the server normalized onto it', () => {
      const loop = renderWalk({ ...APPROVED_STRIP, stripVersion: 'c432029004b5' });
      expect(loop.style.backgroundImage).toContain('?v=c432029004b5');
    });

    it('paints a different URL after a reprocess changes the strip bytes', () => {
      // Unmount between renders — two mounted loops would both match the role
      // query. This is the exact 8f → 12f reprocess the issue reported.
      const before = renderWalk({ ...APPROVED_STRIP, frameCount: 8, stripVersion: 'aaaaaaaaaaaa' }).style.backgroundImage;
      cleanup();
      const after = renderWalk({ ...APPROVED_STRIP, frameCount: 12, stripVersion: 'bbbbbbbbbbbb' }).style.backgroundImage;
      expect(before).not.toBe(after);
    });

    it('leaves a pre-token run on the un-versioned URL rather than ?v=undefined', () => {
      const loop = renderWalk({ ...APPROVED_STRIP });
      expect(loop.style.backgroundImage).toContain(APPROVED_STRIP.stripPath);
      expect(loop.style.backgroundImage).not.toContain('?v=');
    });
  });

  // A strip painted as a CSS background-image fires no onError, so a missing/404
  // file would otherwise render a silent blank box. The server drops the path
  // for a known-missing strip, but a preload probe is the client-side backstop:
  // a strip that fails to load shows an explicit placeholder instead of a gap.
  it('shows a "strip missing" placeholder when the strip fails to load', async () => {
    const OriginalImage = global.Image;
    // Simulate the strip 404ing: fire onerror as soon as src is assigned.
    global.Image = class {
      set src(_v) { if (this.onerror) queueMicrotask(() => this.onerror()); }
    };
    try {
      render(
        <MemoryRouter>
          <WalkWorkflow
            record={{ id: 'example-walker' }}
            reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
            walk={{
              runs: [{ id: 'run-east', direction: 'east', status: 'approved', stripPreview: APPROVED_STRIP }],
              selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
              walkSet: null,
            }}
            renders={noRenders()}
            duration={6}
            onDurationChange={vi.fn()}
            onGenerate={vi.fn()}
            onChanged={vi.fn()}
          />
        </MemoryRouter>,
      );
      expect(await screen.findByText('strip missing')).toBeInTheDocument();
      // The animated loop is NOT rendered in the failed state.
      expect(screen.queryByRole('img', { name: 'walk loop preview' })).toBeNull();
    } finally {
      global.Image = OriginalImage;
    }
  });

  // When the server flags a run stripMissing (its packed strip is gone on disk)
  // it drops the stripPath, so the loop can't render. The card must show an
  // explicit indicator pointing at the recovery that works for the direction's
  // state — regenerate an unapproved/unfinalized direction, use the server-backed
  // walk action for a finalized set — never the status==='error' "Retry
  // postprocess" that would 409.
  const renderMissing = ({ finalized }) => render(
    <MemoryRouter>
      <WalkWorkflow
        record={{ id: 'example-walker' }}
        reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
        walk={{
          runs: [{ id: 'run-east', direction: 'east', status: 'candidate', stripMissing: true, stripPreview: { frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384 } }],
          selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
          walkSet: finalized ? { directions: { east: { status: 'approved' } } } : null,
        }}
        renders={noRenders()}
        duration={6}
        onDurationChange={vi.fn()}
        onGenerate={vi.fn()}
        onChanged={vi.fn()}
      />
    </MemoryRouter>,
  );

  it('shows a regenerate-oriented strip-missing indicator on an unfinalized direction', () => {
    renderMissing({ finalized: false });
    expect(screen.getByText(/Walk strip missing on disk — regenerate to repack it\./)).toBeInTheDocument();
    // No dead "Retry postprocess" button (that path is gated on status==='error').
    expect(screen.queryByRole('button', { name: /Retry postprocess|Re-run postprocess/ })).toBeNull();
    expect(screen.queryByRole('img', { name: 'walk loop preview' })).toBeNull();
  });

  it('points a finalized direction at its server-backed walk action', () => {
    renderMissing({ finalized: true });
    expect(screen.getByText(/Walk strip missing on disk — use the walk action below to regenerate this direction\./)).toBeInTheDocument();
  });

  it('scales the preview box to a non-square cell', () => {
    const loop = renderWalk({
      stripPath: 'grok/walk-east-abc/generated/strip.png',
      frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 192,
    });
    // The box is the checkerboarded wrapper (#2930) — the scrubbing element
    // fills it, so the computed cell height is asserted on the parent.
    expect(loop.parentElement.style.height).toBe(`${CELL_PX / 2}px`);
    expect(loop.style.backgroundSize).toBe(`${CELL_PX * 8}px ${CELL_PX / 2}px`);
  });
});

describe('WalkWorkflow render-lane picker (#4876)', () => {
  const renderPanel = (props = {}) => render(
    <MemoryRouter>
      <WalkWorkflow
        record={{ id: 'example-walker' }}
        reference={{
          manifest: {
            mainReference: { locked: true },
            anchors: [{ direction: 'east', status: 'locked', path: 'reference/example-walker-east-v1.png' }],
          },
        }}
        walk={{ runs: [], selection: { directions: {} }, walkSet: null }}
        renders={noRenders()}
        duration={6}
        onDurationChange={vi.fn()}
        onGenerate={vi.fn()}
        onChanged={vi.fn()}
        {...props}
      />
    </MemoryRouter>,
  );

  const PROVIDERS = [
    { id: 'grok', label: 'Grok (cloud)', ready: true, reason: null },
    { id: 'local', label: 'Local (MiniMax H3)', ready: true, reason: null },
  ];

  it('offers the lane picker beside the clip length once both lanes are known', () => {
    renderPanel({ providers: PROVIDERS, provider: 'grok', onProviderChange: vi.fn() });
    expect(screen.getByLabelText(/Render on/)).toBeInTheDocument();
    expect(screen.getByLabelText(/^Clip/)).toBeInTheDocument();
  });

  it('shows no picker on an install that never learned about a second lane', () => {
    // Default props — an older page build, or a readiness probe that failed.
    renderPanel();
    expect(screen.queryByLabelText(/Render on/)).toBeNull();
  });

  it('hands the chosen lane back to the page', () => {
    const onProviderChange = vi.fn();
    renderPanel({ providers: PROVIDERS, provider: 'grok', onProviderChange });
    fireEvent.change(screen.getByLabelText(/Render on/), { target: { value: 'local' } });
    expect(onProviderChange).toHaveBeenCalledWith('local');
  });

  it('describes the clip length in LOCAL terms when the local lane is selected', () => {
    // The grok copy names 6/10/15 s clips, which is not what H3 renders.
    renderPanel({ providers: PROVIDERS, provider: 'local', onProviderChange: vi.fn() });
    expect(screen.getByLabelText(/^Clip/).closest('label')).toHaveAttribute(
      'title', expect.stringContaining('fixed frame grid'),
    );
  });

  it('offers the Render Queue instead of the Shell for a LOCAL render', () => {
    // The local lane has no PTY to attach to, so its rendering card would
    // otherwise be a dead end with no way to watch or cancel the job.
    renderPanel({
      walk: {
        runs: [{ id: 'walk-east-abc', direction: 'east', status: 'rendering', jobId: 'mjob-1' }],
        selection: { directions: {} },
        walkSet: null,
      },
    });
    expect(screen.getByRole('link', { name: /Watch in Render Queue/ }))
      .toHaveAttribute('href', '/system-resources/queues');
    expect(screen.queryByRole('link', { name: /Watch in Shell/ })).toBeNull();
  });

  it('keeps the Shell link for a grok render, and offers only that one', () => {
    renderPanel({
      walk: {
        runs: [{ id: 'walk-east-abc', direction: 'east', status: 'rendering', shellSession: 'walk-east-abc' }],
        selection: { directions: {} },
        walkSet: null,
      },
    });
    expect(screen.getByRole('link', { name: /Watch in Shell/ })).toBeInTheDocument();
    expect(screen.queryByRole('link', { name: /Watch in Render Queue/ })).toBeNull();
  });
});

describe('WalkWorkflow idle anchor preview', () => {
  it('shows the locked directional anchor until the direction has a packaged animation', () => {
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{
            manifest: {
              mainReference: { locked: true },
              anchors: [{ direction: 'north-east', status: 'locked', path: 'reference/example-walker-north-east-v1.png' }],
            },
          }}
          walk={{ runs: [], selection: { directions: {} }, walkSet: null }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );

    const idle = screen.getByRole('img', { name: 'north-east reference idle pose' });
    expect(idle.getAttribute('src')).toBe('/data/sprites/example-walker/reference/example-walker-north-east-v1.png');
    expect(screen.getByText('reference idle')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Generate walk' })).toBeEnabled();
  });

  it('replaces the idle anchor with the packaged walk preview', () => {
    renderWalk(APPROVED_STRIP);

    expect(screen.queryByRole('img', { name: 'east reference idle pose' })).toBeNull();
    expect(screen.getByRole('img', { name: 'walk loop preview' })).toBeInTheDocument();
  });

  it('returns to the current idle anchor when the previous walk used a superseded anchor', () => {
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{
            manifest: {
              mainReference: { locked: true },
              anchors: [{ direction: 'east', status: 'locked', path: 'reference/example-walker-east-v2.png' }],
            },
          }}
          walk={{
            runs: [{
              id: 'run-east-old',
              direction: 'east',
              status: 'superseded-anchor',
              stripPreview: APPROVED_STRIP,
            }],
            selection: { directions: {} },
            walkSet: null,
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );

    expect(screen.getByRole('img', { name: 'east reference idle pose' }).getAttribute('src'))
      .toBe('/data/sprites/example-walker/reference/example-walker-east-v2.png');
    expect(screen.getByText(/Previous walk kept in history/)).toBeInTheDocument();
    expect(screen.queryByRole('img', { name: 'walk loop preview' })).toBeNull();
    expect(screen.queryByRole('button', { name: /Edit in Loop Trimmer/ })).toBeNull();
    expect(screen.getByRole('button', { name: 'Generate walk' })).toBeEnabled();
  });
});

// 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 now for ANY run that carries a packed strip — the trim service resolves
// geometry layout-agnostically, so the old `grok/`-only gate is gone.
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('renders no inline trim panel', () => {
    renderWalk(APPROVED_STRIP, { onOpenTrimmer: vi.fn() });
    expect(screen.queryByRole('button', { name: /Save trim/ })).toBeNull();
  });

  it('offers the link for an imported/redraw run whose strip is not under grok/', () => {
    // The exact case that left pioneer's east without a trim button: a strip
    // outside grok/ (imported runs/ or an imagegen redraw) is now trimmable.
    const onOpenTrimmer = vi.fn();
    renderWalk({
      stripPath: 'imagegen/v19/clean-alpha.png', frameCount: 12, fps: 12, cellWidth: 384, cellHeight: 384,
    }, { onOpenTrimmer });
    const link = screen.getByRole('button', { name: /Edit in Loop Trimmer/ });
    link.click();
    expect(onOpenTrimmer).toHaveBeenCalledWith('run-east');
  });
});

// Render the workflow with a single run of the given shape. Router-wrapped so
// the card's <Link> (shown while rendering) resolves in every case.
// `walkTarget` is the server-resolved set-level cycle target (#2985); tests that
// care about provenance/drift override it, the rest get the plain default.
const renderRun = (run, { walkTarget, onChanged = vi.fn() } = {}) => render(
  <MemoryRouter>
    <WalkWorkflow
      record={{ id: 'example-walker' }}
      reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
      walk={{
        runs: [run],
        selection: { directions: {} },
        walkSet: null,
        walkTarget: walkTarget || {
          track: 'walk', frameCount: 12, fps: 10, source: 'default', drift: [],
        },
      }}
      renders={noRenders()}
      duration={2}
      onDurationChange={vi.fn()}
      onGenerate={vi.fn()}
      onChanged={onChanged}
    />
  </MemoryRouter>,
);

describe('WalkWorkflow failed-run clip', () => {
  it('renders grok\'s raw clip and the error text when postprocess failed', () => {
    renderRun({
      id: 'walk-east-deadbeef', direction: 'east', status: 'error',
      postprocessError: 'Measured background [0,0,0] is not a usable #FF00FF matte',
      sourceVideoPath: 'runs/walk-east-deadbeef/generated/source-video.mp4',
    });
    const video = screen.getByLabelText('raw grok walk clip (east)');
    expect(video.getAttribute('src')).toBe(
      '/data/sprites/example-walker/runs/walk-east-deadbeef/generated/source-video.mp4',
    );
    expect(screen.getByText(/not a usable #FF00FF matte/)).toBeTruthy();
    expect(screen.getByRole('button', { name: /Retry postprocess/ })).toBeTruthy();
  });

  it('shows only the error text when no clip landed', () => {
    renderRun({
      id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'boom',
    });
    expect(screen.queryByLabelText('raw grok walk clip (east)')).toBeNull();
    expect(screen.getByText('boom')).toBeTruthy();
  });
});

describe('WalkWorkflow observable render', () => {
  it('links to the live Shell session while grok is rendering', () => {
    renderRun({
      id: 'walk-east-abc12345', direction: 'east', status: 'rendering', shellSession: 'walk-east-abc12345',
    });
    const link = screen.getByRole('link', { name: /Watch in Shell/ });
    expect(link.getAttribute('href')).toBe('/shell/walk-east-abc12345');
    // Generate is disabled while rendering (server truth), showing the spinner.
    expect(screen.getByRole('button', { name: /Rendering/ })).toBeDisabled();
  });

  it('shows no shell link once the render has moved on to packaging', () => {
    renderRun({
      id: 'walk-east-abc12345', direction: 'east', status: 'postprocessing', shellSession: 'walk-east-abc12345',
    });
    expect(screen.queryByRole('link', { name: /Watch in Shell/ })).toBeNull();
  });

  it('keeps "Re-run postprocess" clickable on a run wedged at packaging', () => {
    // attachTuiWalkResult persists 'postprocessing' before packaging and nothing
    // normalizes it, so a server death mid-package strands the run there — this
    // button is the documented way out. Gating it on the generic `busy` (which
    // includes status==='postprocessing') would make it permanently dead and
    // leave the direction with no enabled action at all.
    renderRun({
      id: 'walk-east-abc12345', direction: 'east', status: 'postprocessing',
    });
    expect(screen.getByRole('button', { name: /Re-run postprocess/ })).not.toBeDisabled();
  });
});

describe('WalkWorkflow authoring controls', () => {
  it('offers a set-level Cycle target, Preview speed, and grok-real Clip options', () => {
    renderRun({ id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' });
    // Clip length is now just grok's real 6/10/15 s options (shorter was a no-op).
    const clip = screen.getByRole('combobox', { name: /Clip/ });
    expect([...clip.options].map((o) => o.value)).toEqual(['6', '10', '15']);
    // Frame count + speed are ONE set-level target now (#2985), not per-render
    // inputs that can drift between directions.
    expect(screen.getByRole('combobox', { name: /Cycle target/ })).toBeTruthy();
    expect(screen.getByRole('combobox', { name: /Preview speed/ })).toBeTruthy();
    // …and the cycle-duration readout reflects the defaults (12f / 10fps = 1.20s).
    expect(screen.getByText(/1\.20s \/ cycle/)).toBeTruthy();
  });

  it('labels the target with where the value came from', () => {
    renderRun(
      { id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
      {
        walkTarget: {
          frameCount: 8, fps: 12, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
        },
      },
    );
    // The provenance wording is stamped by the server, not re-mapped here, so
    // the label and the 409 message can never describe the target differently.
    expect(screen.getByText('from the first approved direction')).toBeTruthy();
    expect(screen.getByRole('combobox', { name: /Cycle target/ }).value).toBe('8');
  });

  it('renders the target read-only and names the app when the publish binding pins it', () => {
    renderRun(
      { id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
      {
        walkTarget: {
          frameCount: 16,
          fps: 10,
          source: 'app',
          sourceLabel: 'locked by example-game',
          frameCountLocked: true,
          appId: 'example-game',
          drift: [],
        },
      },
    );
    expect(screen.getByRole('combobox', { name: /Cycle target/ }).disabled).toBe(true);
    expect(screen.getByText(/locked by example-game · change it in Publish below/)).toBeTruthy();
    // fps is not in the contract, so it stays editable.
    expect(screen.getByRole('combobox', { name: /Preview speed/ }).disabled).toBe(false);
  });

  it('shows an odd target fps the even-step picker does not list', () => {
    // The speed picker offers even steps, but the server accepts any integer in
    // range — an imported set can be pinned at 15fps. A <select> whose value
    // matches no <option> silently displays the FIRST one, so the control would
    // have claimed "4 fps" while the set was really at 15.
    renderRun(
      { id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
      {
        walkTarget: {
          frameCount: 12, fps: 15, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
        },
      },
    );
    const speed = screen.getByRole('combobox', { name: /Preview speed/ });
    expect(speed.value).toBe('15');
    expect([...speed.options].map((o) => o.value)).toContain('15');
  });

  it('saves a new target to the set and refreshes', async () => {
    const onChanged = vi.fn();
    renderRun(
      { id: 'walk-east-deadbeef', direction: 'east', status: 'error', postprocessError: 'x' },
      { onChanged },
    );
    const select = screen.getByRole('combobox', { name: /Cycle target/ });
    await act(async () => {
      fireEvent.change(select, { target: { value: '14' } });
    });
    expect(setSpriteWalkTarget).toHaveBeenCalledWith(
      'example-walker', { frameCount: 14, fps: 10 }, { silent: true },
    );
    expect(onChanged).toHaveBeenCalled();
  });
});

describe('WalkWorkflow cycle-target drift', () => {
  const DRIFTED = {
    walkTarget: {
      frameCount: 12,
      fps: 10,
      source: 'set',
      drift: [{
        direction: 'east', frameCount: 8, fps: 10, frameCountDrifts: true, fpsDrifts: false,
      }],
    },
  };

  it('badges a packaged direction that no longer matches the target', () => {
    renderRun({
      id: 'walk-east-abc12345',
      direction: 'east',
      status: 'candidate',
      sourceVideoPath: 'runs/walk-east-abc12345/generated/source-video.mp4',
      stripPreview: { stripPath: 'runs/walk-east-abc12345/generated/strip.png', frameCount: 8, fps: 10, cellWidth: 384, cellHeight: 384 },
    }, DRIFTED);
    expect(screen.getByText(/8f · re-derive to 12f @ 10fps/)).toBeTruthy();
    expect(screen.getByText('reprocess it from its clip')).toBeTruthy();
    // …and a set-level summary so it is visible before eight renders are spent.
    expect(screen.getByText(/1 of 8 packaged directions differs from the 12f @ 10fps target/)).toBeTruthy();
    // Approving a drifted candidate would freeze a ragged set the atlas can
    // never compile — the server refuses it, so the button doesn't offer it.
    expect(screen.getByRole('button', { name: 'Approve' }).disabled).toBe(true);
  });

  it('points a drifted direction with no source clip at an import instead', () => {
    renderRun({
      id: 'imported-east',
      direction: 'east',
      status: 'candidate',
      stripPreview: { stripPath: 'runs/imported-east/generated/strip.png', frameCount: 8, fps: 10, cellWidth: 384, cellHeight: 384 },
    }, DRIFTED);
    expect(screen.getByText('import this direction\'s source clip to re-derive it')).toBeTruthy();
  });
});

describe('WalkWorkflow reprocess + reopen', () => {
  it('reprocesses a candidate from its on-disk clip, letting the server apply the set target', async () => {
    renderRun({
      id: 'walk-east-abc12345', direction: 'east', status: 'candidate',
      stripPreview: { stripPath: 'runs/walk-east-abc12345/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384 },
    });
    await act(async () => { screen.getByRole('button', { name: /Reprocess/ }).click(); });
    // Geometry is deliberately omitted — the server adopts the set's pinned
    // target, so the request can't 409 against a target this page is one
    // refetch behind on (#2985).
    expect(postprocessSpriteWalk).toHaveBeenCalledWith(
      'example-walker',
      { runId: 'walk-east-abc12345' },
      { silent: true },
    );
  });

  it('reopens an approved direction after an inline confirm', async () => {
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
          walk={{
            runs: [{ id: 'run-east', direction: 'east', status: 'approved', stripPreview: { stripPath: 'runs/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384 } }],
            selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
            walkSet: null,
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );
    act(() => { screen.getByRole('button', { name: /^Reopen$/ }).click(); });
    // Inline confirm surfaces, then the confirm fires the API.
    await act(async () => { screen.getByRole('button', { name: /^Reopen$/ }).click(); });
    expect(reopenSpriteWalk).toHaveBeenCalledWith(
      'example-walker', { direction: 'east', acknowledgeNoClips: false }, { silent: true },
    );
  });

  it('uses the server-stamped block to offer acknowledged Reopen on a clipless import', async () => {
    reopenSpriteWalk.mockClear();
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
          walk={{
            runs: [{
              id: 'run-east', direction: 'east', status: 'approved',
              reopen: { blocked: true, stranded: ['east'], acknowledgeable: true },
              stripPreview: { stripPath: 'runs/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384 },
            }],
            selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
            walkSet: {
              imported: true,
              directions: { east: { status: 'approved' } },
              unlock: { blocked: true, stranded: ['east'], acknowledgeable: true },
            },
            walkTarget: {
              frameCount: 12, fps: 10, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
            },
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );
    expect(screen.queryByRole('button', { name: /^Reopen$/ })).toBeNull();
    expect(screen.getByText(/Reopening anyway lets east be regenerated/)).toBeTruthy();
    fireEvent.click(screen.getByRole('button', { name: /^Reopen anyway$/ }));
    fireEvent.click(screen.getByRole('button', { name: /^Reopen anyway$/ }));
    await waitFor(() => expect(reopenSpriteWalk).toHaveBeenCalledWith(
      'example-walker', { direction: 'east', acknowledgeNoClips: true }, { silent: true },
    ));
  });

  // The acknowledged unlock is an override of the CLIP requirement only. When the
  // server reports the set is not regenerable either (an unlocked anchor), there
  // is genuinely nothing to offer and the panel must say so rather than hand back
  // a guaranteed 409.
  it('offers no unlock at all when the server says the set is not even regenerable', async () => {
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
          walk={{
            runs: [{ id: 'run-east', direction: 'east', status: 'approved', stripPreview: { stripPath: 'runs/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384 } }],
            selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
            walkSet: {
              imported: true,
              directions: { east: { status: 'approved' } },
              unlock: { blocked: true, stranded: ['east'], acknowledgeable: false },
            },
            walkTarget: {
              frameCount: 12, fps: 10, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
            },
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );
    expect(screen.queryByRole('button', { name: /Unlock/ })).toBeNull();
    expect(screen.getByText(/cannot be regenerated here/)).toBeTruthy();
  });

  it('sends the acknowledgement only from the blocked-but-regenerable confirm', async () => {
    const onChanged = vi.fn();
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
          walk={{
            runs: [{ id: 'run-east', direction: 'east', status: 'approved', stripPreview: { stripPath: 'runs/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384 } }],
            selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
            walkSet: {
              imported: true,
              directions: { east: { status: 'approved' } },
              unlock: { blocked: true, stranded: ['east'], acknowledgeable: true },
            },
            walkTarget: {
              frameCount: 12, fps: 10, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
            },
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={onChanged}
        />
      </MemoryRouter>,
    );
    fireEvent.click(screen.getByRole('button', { name: /Unlock anyway/ }));
    fireEvent.click(screen.getByRole('button', { name: /^Unlock anyway$/ }));
    await waitFor(() => expect(unlockSpriteWalk).toHaveBeenCalledWith(
      'example-walker', { acknowledgeNoClips: true }, { silent: true },
    ));
  });

  // #2993: since the importer brings each run's clip across, an imported
  // direction with its clip on disk is re-derivable exactly like a native one —
  // the server allows reopen/unlock there, so the affordances must be offered.
  // The gate is the clip, not the import label.
  it('offers Reopen and Unlock on an import whose clip IS on disk', async () => {
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
          walk={{
            runs: [{
              id: 'run-east',
              direction: 'east',
              status: 'approved',
              sourceVideoPath: 'grok/run-east/generated/source-video.mp4',
              stripPreview: {
                stripPath: 'grok/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384,
              },
            }],
            selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
            walkSet: { imported: true, importedDirections: ['east'], directions: { east: { status: 'approved' } } },
            walkTarget: {
              frameCount: 12, fps: 10, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
            },
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );
    expect(screen.getByRole('button', { name: /^Reopen$/ })).toBeTruthy();
    expect(screen.getByRole('button', { name: /^Unlock$/ })).toBeTruthy();
    expect(screen.queryByText(/no clips to re-derive/)).toBeNull();
  });

  // Unlock re-opens every direction, so the server refuses it unless EVERY
  // still-imported direction has a clip — a stranded one could be neither
  // reprocessed nor re-approved. The header must mirror that scope rather than
  // "any run anywhere has a clip", or it offers a guaranteed 409.
  it('hides Unlock when one imported direction has no clip, while Reopen stays on the one that does', async () => {
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
          walk={{
            runs: [{
              id: 'run-east',
              direction: 'east',
              status: 'approved',
              sourceVideoPath: 'grok/run-east/generated/source-video.mp4',
              stripPreview: {
                stripPath: 'grok/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384,
              },
            }],
            selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
            walkSet: {
              imported: true,
              importedDirections: ['east', 'north'],
              directions: { east: { status: 'approved' }, north: { status: 'approved' } },
              unlock: { blocked: true, stranded: ['north'], acknowledgeable: true },
            },
            walkTarget: {
              frameCount: 12, fps: 10, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
            },
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );
    expect(screen.queryByRole('button', { name: /^Unlock$/ })).toBeNull();
    expect(screen.getByRole('button', { name: /^Reopen$/ })).toBeTruthy();
  });

  // Once a set is un-frozen (an unlock, or a reopen of some OTHER direction),
  // the remaining source-packaged direction has no walkSet to carry a block.
  // Its stamped run block survives instead, so the client still names the fresh
  // render cost before it sends the acknowledgement.
  it('keeps the acknowledged reopen affordance after the set is un-frozen', async () => {
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
          walk={{
            runs: [{
              id: 'run-east',
              direction: 'east',
              status: 'approved',
              importedPackaging: true,
              reopen: { blocked: true, stranded: ['east'], acknowledgeable: true },
              stripPreview: { stripPath: 'grok/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384 },
            }],
            selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
            walkSet: null,
            walkTarget: {
              frameCount: 12, fps: 10, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
            },
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );
    expect(screen.getByRole('button', { name: /^Reopen anyway$/ })).toBeTruthy();
  });

  // A card does not recreate the source-path/clip rule from legacy import
  // metadata. An unblocked stamp (or a block absent from an older peer) keeps
  // the ordinary Reopen affordance; current servers attach the authoritative
  // block directly to the selected run.
  it('does not derive the reopen block from imported metadata', async () => {
    render(
      <MemoryRouter>
        <WalkWorkflow
          record={{ id: 'example-walker' }}
          reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
          walk={{
            // East carries no clip, but has no server block; the card must not
            // re-create one from the surrounding imported walk metadata.
            runs: [{ id: 'run-east', direction: 'east', status: 'approved', stripPreview: { stripPath: 'runs/run-east/generated/strip.png', frameCount: 12, fps: 10, cellWidth: 384, cellHeight: 384 } }],
            selection: { directions: { east: { status: 'approved', runId: 'run-east' } } },
            walkSet: {
              imported: true,
              importedDirections: ['north'],
              directions: { east: { status: 'approved' }, north: { status: 'approved' } },
            },
            walkTarget: {
              frameCount: 12, fps: 10, source: 'derived', sourceLabel: 'from the first approved direction', drift: [],
            },
          }}
          renders={noRenders()}
          duration={6}
          onDurationChange={vi.fn()}
          onGenerate={vi.fn()}
          onChanged={vi.fn()}
        />
      </MemoryRouter>,
    );
    expect(screen.getByRole('button', { name: /^Reopen$/ })).toBeTruthy();
  });
});

// The delivered-clip-length readout (#3022). grok's image_to_video offers only
// 6/10/15 s and renders 6s for anything shorter, so the requested length is not a
// promise — the card reports what the server probed off the file, and says so
// loudly when the two disagree.
describe('delivered clip length', () => {
  const renderWithRun = (run) => render(
    <MemoryRouter>
      <WalkWorkflow
        record={{ id: 'example-walker' }}
        reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked' }] } }}
        walk={{
          runs: [{ id: 'run-east', direction: 'east', status: 'candidate', ...run }],
          selection: { directions: {} },
          walkSet: null,
        }}
        renders={noRenders()}
        duration={6}
        onDurationChange={vi.fn()}
        onGenerate={vi.fn()}
        onChanged={vi.fn()}
      />
    </MemoryRouter>,
  );

  it('reports the probed clip length', () => {
    renderWithRun({ duration: 6, sourceVideoSeconds: 6.04 });
    expect(screen.getByText('6.0s clip')).toBeTruthy();
  });

  it('flags a delivered length that differs from the request', () => {
    // The exact case the field exists for: asked 2s, grok rendered 6s.
    renderWithRun({ duration: 2, sourceVideoSeconds: 6.04 });
    const badge = screen.getByText('6.0s clip (asked 2s)');
    expect(badge.className).toContain('text-port-warning');
  });

  it('does not treat a rounding-level difference as a mismatch', () => {
    renderWithRun({ duration: 6, sourceVideoSeconds: 6.041667 });
    expect(screen.queryByText(/asked/)).toBeNull();
  });

  it('keeps a truncated clip distinguishable from an unknown one', () => {
    // 0.02s is a real (broken) clip; rounding it to "0.0s clip" would read as
    // the absent/unknown case, which renders nothing at all.
    renderWithRun({ duration: 6, sourceVideoSeconds: 0.02 });
    expect(screen.getByText(/0\.02s clip/)).toBeTruthy();
  });

  it('renders nothing when the clip length is unknown', () => {
    // Absent (older run, or ffprobe unavailable) must NOT read as a 0s clip.
    renderWithRun({ duration: 6 });
    expect(screen.queryByText(/clip$/)).toBeNull();
    expect(screen.queryByText(/0\.0s/)).toBeNull();
  });
});

// Correction notes on the walk card (#3134). The card writes the WALK-namespaced
// key in the page-owned map, so a note typed here (or on the asset-collection
// walk card, which uses the same key) rides the next Generate.
describe('walk correction note (#3134)', () => {
  const renderCard = (props = {}) => render(
    <MemoryRouter>
      <WalkWorkflow
        record={{ id: 'example-walker' }}
        reference={{ manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'locked', path: 'reference/example-walker-east-v1.png' }] } }}
        walk={{ runs: [], selection: { directions: {} }, walkSet: null }}
        renders={noRenders()}
        duration={6}
        onDurationChange={vi.fn()}
        onGenerate={vi.fn()}
        onChanged={vi.fn()}
        {...props}
      />
    </MemoryRouter>,
  );

  it('writes through to the shared map under the walk-namespaced key', () => {
    const onCorrectionChange = vi.fn();
    renderCard({ corrections: {}, onCorrectionChange });
    fireEvent.click(screen.getByRole('button', { name: /Show correction note for east walk cycle/i }));
    fireEvent.change(screen.getByLabelText(/Correction guidance for the east walk cycle/i), {
      target: { value: 'the legs barely lift' },
    });
    const merged = onCorrectionChange.mock.calls[0][0]({ east: 'anchor note' });
    // The anchor's still-image note survives, and the walk note is written to
    // its OWN key — that separation is the whole point of the namespace.
    expect(merged.east).toBe('anchor note');
    expect(merged).toHaveProperty('walk:east');
  });

  it('prefills an existing walk note and leaves the affordance out with no writer', () => {
    renderCard({ corrections: { 'walk:east': 'the legs barely lift' }, onCorrectionChange: vi.fn() });
    expect(screen.getByLabelText(/Correction guidance for the east walk cycle/i))
      .toHaveValue('the legs barely lift');
    cleanup();
    renderCard();
    expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();
  });

  it('hides the note for a direction whose anchor is not locked yet', () => {
    renderCard({
      reference: { manifest: { mainReference: { locked: true }, anchors: [{ direction: 'east', status: 'pending' }] } },
      corrections: {},
      onCorrectionChange: vi.fn(),
    });
    expect(screen.queryByRole('button', { name: /correction note/i })).toBeNull();
  });
});