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

36.9 KB
Raw Blame
const socketHandlers = vi.hoisted(() => new Map());
vi.mock('../services/socket', () => ({ default: {
  on: (event, fn) => { if (!socketHandlers.has(event)) socketHandlers.set(event, new Set()); socketHandlers.get(event).add(fn); },
  off: (event, fn) => socketHandlers.get(event)?.delete(fn),
} }));
const emitModel = async (event, payload) => act(async () => {
  for (const fn of socketHandlers.get(event) || []) fn(payload);
});

import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useNavigate } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import ThreejsModelDetail from './ThreejsModelDetail';

vi.mock('../services/api', () => ({
  deleteThreejsModel: vi.fn(),
  generateThreejsModel: vi.fn(),
  getThreejsModel: vi.fn(),
  getThreejsModelSource: vi.fn(),
  listThreejsModelFamilies: vi.fn(),
  threejsModelSourceUrl: (id) => `/api/threejs-models/${id}/source`,
}));

vi.mock('../hooks/useProviderModels', () => ({
  default: () => ({
    providers: [{ id: 'vision-api', name: 'Vision API', type: 'api', enabled: true }],
    selectedProviderId: 'vision-api',
    selectedModel: '',
    availableModels: [],
    setSelectedProviderId: vi.fn(),
    setSelectedModel: vi.fn(),
    loading: false,
  }),
}));

vi.mock('../components/ProviderModelSelector', () => ({
  default: () => <div>Vision API</div>,
}));

// The preview mounts a react-three-fiber Canvas, which cannot render in jsdom.
vi.mock('../components/threejsModels/ThreejsModelPreview', () => ({
  default: ({ family }) => <div>Model preview {family?.id || 'no family'}</div>,
}));

import { generateThreejsModel, getThreejsModel, listThreejsModelFamilies } from '../services/api';

const baseRecord = {
  id: 'threejs-example',
  name: 'Example Beacon',
  status: 'ready',
  providerId: 'vision-api',
  model: null,
  prompt: '',
  updatedAt: new Date().toISOString(),
  sourceImage: { filename: 'example-beacon.png', path: '/data/images/example-beacon.png' },
  spec: { name: 'Example Beacon', summary: 'A beacon.', detailInventory: [] },
  runs: [],
};

const FAMILY_OPTIONS = [
  { id: 'general', label: 'General (no checklist)', description: 'One general-purpose prompt.' },
  { id: 'vehicle', label: 'Vehicle', description: 'Cars, ships, aircraft.' },
];

const resetMocks = () => {
  vi.clearAllMocks();
  listThreejsModelFamilies.mockResolvedValue(FAMILY_OPTIONS);
};

const RouteSwitcher = () => {
  const navigate = useNavigate();
  return (
    <>
      <button type="button" onClick={() => navigate('/media/threejs/model-b')}>
        Switch to model B
      </button>
      <button type="button" onClick={() => navigate('/media/threejs/model-a')}>
        Switch to model A
      </button>
    </>
  );
};

const renderDetail = (
  initialEntries = ['/media/threejs/threejs-example'],
  { withSwitcher = false } = {},
) => render(
  <MemoryRouter initialEntries={initialEntries}>
    <Routes>
      <Route path="/media/threejs/:id" element={<>{withSwitcher && <RouteSwitcher />}<ThreejsModelDetail /></>} />
    </Routes>
  </MemoryRouter>,
);

const renderLifecycleDetail = (initialEntries) => renderDetail(initialEntries, { withSwitcher: true });

const deferred = () => {
  let resolve;
  let reject;
  const promise = new Promise((fulfill, fail) => {
    resolve = fulfill;
    reject = fail;
  });
  return { promise, resolve, reject };
};

describe('ThreejsModelDetail request lifecycle', () => {
  beforeEach(() => { resetMocks(); getThreejsModel.mockReset(); });
  afterEach(() => { vi.useRealTimers(); });

  it('renders matching events without polling and reconciles reconnect and tab show once', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, status: 'generating' });
    renderDetail();
    await screen.findByText('generating', { exact: true });
    vi.useFakeTimers();
    await act(async () => { vi.advanceTimersByTime(60_000); });
    await emitModel('threejs-model:changed', { id: 'unrelated' });
    expect(getThreejsModel).toHaveBeenCalledTimes(1);
    getThreejsModel.mockResolvedValue({ ...baseRecord, status: 'ready' });
    await emitModel('threejs-model:changed', { id: baseRecord.id });
    expect(screen.getByText('ready', { exact: true })).toBeInTheDocument();
    await emitModel('connect');
    expect(getThreejsModel).toHaveBeenCalledTimes(3);
    Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
    await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });
    await emitModel('threejs-model:changed', { id: baseRecord.id });
    expect(getThreejsModel).toHaveBeenCalledTimes(3);
    Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
    await act(async () => { document.dispatchEvent(new Event('visibilitychange')); });
    expect(getThreejsModel).toHaveBeenCalledTimes(4);
  });

  it('aborts a pending read on route change and ignores its late result', async () => {
    const pending = deferred();
    let oldSignal;
    getThreejsModel.mockImplementation((id, { signal }) => {
      if (id === 'model-a') { oldSignal = signal; return pending.promise; }
      return Promise.resolve({ ...baseRecord, id, name: 'Model B' });
    });
    renderLifecycleDetail(['/media/threejs/model-a']);
    await act(async () => {});
    fireEvent.click(screen.getByRole('button', { name: 'Switch to model B' }));
    expect(oldSignal.aborted).toBe(true);
    await screen.findByText('Model B');
    await act(async () => { pending.resolve({ ...baseRecord, id: 'model-a', name: 'Model A' }); });
    expect(screen.queryByText('Model A')).not.toBeInTheDocument();
  });

  it('coalesces invalidations during a slow read and does not lose the terminal update', async () => {
    getThreejsModel.mockResolvedValueOnce({ ...baseRecord, status: 'generating' });
    renderDetail();
    await screen.findByText('generating', { exact: true });
    const slow = deferred();
    getThreejsModel.mockReturnValueOnce(slow.promise).mockResolvedValue({ ...baseRecord, status: 'ready' });
    await emitModel('threejs-model:changed', { id: baseRecord.id });
    await emitModel('threejs-model:changed', { id: baseRecord.id });
    expect(getThreejsModel).toHaveBeenCalledTimes(2);
    await act(async () => { slow.resolve({ ...baseRecord, status: 'generating' }); });
    expect(screen.getByText('ready', { exact: true })).toBeInTheDocument();
    expect(getThreejsModel).toHaveBeenCalledTimes(3);
  });

  it('releases a timed-out read and recovers on reconnect without recurring requests', async () => {
    vi.useFakeTimers();
    let signal;
    getThreejsModel.mockImplementationOnce((_id, options) => {
      signal = options.signal;
      return new Promise(() => {});
    }).mockResolvedValue(baseRecord);
    renderDetail();
    await act(async () => {});
    await act(async () => { vi.advanceTimersByTime(60_000); });
    expect(signal.aborted).toBe(true);
    expect(getThreejsModel).toHaveBeenCalledTimes(1);
    await emitModel('connect');
    expect(screen.getByText('ready', { exact: true })).toBeInTheDocument();
  });

  it('retries a transient terminal read once and preserves missing records without retries', async () => {
    getThreejsModel.mockResolvedValueOnce({ ...baseRecord, status: 'generating' });
    renderDetail();
    await screen.findByText('generating', { exact: true });
    getThreejsModel.mockRejectedValueOnce(new Error('Temporary outage')).mockResolvedValueOnce(baseRecord);
    await emitModel('threejs-model:changed', { id: baseRecord.id });
    expect(screen.getByText('ready', { exact: true })).toBeInTheDocument();
    expect(getThreejsModel).toHaveBeenCalledTimes(3);
    getThreejsModel.mockRejectedValueOnce({ status: 404 });
    await emitModel('threejs-model:changed', { id: baseRecord.id });
    expect(screen.getByText('That Three.js model does not exist.')).toBeInTheDocument();
    expect(getThreejsModel).toHaveBeenCalledTimes(4);
  });
});

describe('ThreejsModelDetail assembly coverage', () => {
  beforeEach(resetMocks);

  it('lists the findings, tallies them, and states the gate is not a completeness proof', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      coverage: {
        errorCount: 1,
        warningCount: 1,
        noteCount: 0,
        findings: [
          { code: 'fused-parts', severity: 'error', message: 'Two promised features collapsed onto "Hull".' },
          { code: 'orphan-geometry', severity: 'warning', count: 1, message: '1 geometry part is claimed by no entry.' },
        ],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Assembly coverage')).toBeInTheDocument());
    expect(screen.getByText('Two promised features collapsed onto "Hull".')).toBeInTheDocument();
    expect(screen.getByText('1 geometry part is claimed by no entry.')).toBeInTheDocument();
    expect(screen.getByText('1 error · 1 warning · 0 note')).toBeInTheDocument();
    expect(screen.getByText(/never that the spec promised enough/)).toBeInTheDocument();
    // An error-severity finding is what the unsteered refinement will aim at.
    expect(screen.getByText(/will target the errors above/)).toBeInTheDocument();
  });

  it('counts from the findings it rendered rather than the stored tallies', async () => {
    // A record that reached this install without its counts (an older or newer
    // peer, a hand-repaired row) must not print "undefined error".
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      coverage: {
        findings: [{ code: 'folded-detail', severity: 'note', message: 'Minor relief rides on "Hull".' }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Assembly coverage')).toBeInTheDocument());
    expect(screen.getByText('0 error · 0 warning · 1 note')).toBeInTheDocument();
    expect(screen.queryByText(/undefined/)).not.toBeInTheDocument();
    // Notes are not defects, so no refinement is suggested.
    expect(screen.queryByText(/will target the errors above/)).not.toBeInTheDocument();
  });

  it('says nothing went unbuilt on a clean pass, without claiming the spec was complete', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, coverage: { errorCount: 0, warningCount: 0, noteCount: 0, findings: [] } });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Assembly coverage')).toBeInTheDocument());
    expect(screen.getByText('Nothing promised was left unbuilt')).toBeInTheDocument();
    expect(screen.getByText(/never that the spec promised enough/)).toBeInTheDocument();
  });

  it('hides the section entirely for a record generated before the gate existed', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, coverage: null });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());
    expect(screen.queryByText('Assembly coverage')).not.toBeInTheDocument();
  });
});

describe('ThreejsModelDetail cross-section gate', () => {
  beforeEach(resetMocks);

  it('lists the flatness finding and says an unsteered refinement will ask for depth', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      flatness: {
        errorCount: 0,
        warningCount: 1,
        noteCount: 0,
        identityDetailCount: 3,
        flatIdentityDetailCount: 3,
        flatRatio: 1,
        slabPartIds: ['front', 'back', 'fin'],
        findings: [{
          code: 'flat-identity-parts',
          severity: 'warning',
          message: '3 of 3 identity-defining features are built only from flat parts (Front, Back, Fin).',
        }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Cross-section')).toBeInTheDocument());
    expect(screen.getByText('3 of 3 identity-defining features are built only from flat parts (Front, Back, Fin).')).toBeInTheDocument();
    expect(screen.getByText('0 error · 1 warning · 0 note')).toBeInTheDocument();
    expect(screen.getByText(/will also ask for real depth/)).toBeInTheDocument();
  });

  it('reports real depth on a clean pass and stays quiet about refinement', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, flatness: { warningCount: 0, findings: [] } });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Cross-section')).toBeInTheDocument());
    expect(screen.getByText('Identity parts carry real depth')).toBeInTheDocument();
    expect(screen.queryByText(/will also ask for real depth/)).not.toBeInTheDocument();
  });

  it('shows an intentional membrane note without promising depth feedback', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      flatness: {
        errorCount: 0,
        warningCount: 0,
        noteCount: 1,
        identityDetailCount: 1,
        flatIdentityDetailCount: 1,
        flatRatio: 1,
        slabPartIds: ['fin'],
        findings: [{
          code: 'flat-identity-parts',
          severity: 'note',
          message: '1 of 1 identity-defining features are intentional membrane surfaces (Fin).',
        }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Cross-section')).toBeInTheDocument());
    expect(screen.getByText(/intentional membrane surfaces/)).toBeInTheDocument();
    expect(screen.getByText('0 error · 0 warning · 1 note')).toBeInTheDocument();
    expect(screen.queryByText(/will also ask for real depth/)).not.toBeInTheDocument();
  });

  it('hides the section for a record generated before the gate existed', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, flatness: null });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());
    expect(screen.queryByText('Cross-section')).not.toBeInTheDocument();
  });
});

describe('ThreejsModelDetail cross-part penetration gate', () => {
  beforeEach(resetMocks);

  it('lists the buried-part finding and says an unsteered refinement will target it', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      penetration: {
        errorCount: 1,
        warningCount: 0,
        noteCount: 0,
        evaluatedPartCount: 4,
        comparedPairCount: 3,
        undecidedPairCount: 0,
        findings: [{
          code: 'buried-part',
          severity: 'error',
          partIds: ['lens', 'body'],
          message: '1 part(s) are entirely inside another part they are not attached to or parented under ("Lens" inside "Body").',
        }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Cross-part penetration')).toBeInTheDocument());
    expect(screen.getByText('1 part(s) are entirely inside another part they are not attached to or parented under ("Lens" inside "Body").')).toBeInTheDocument();
    expect(screen.getByText('1 error · 0 warning · 0 note')).toBeInTheDocument();
    expect(screen.getByText(/each part to get its own volume/)).toBeInTheDocument();
  });

  it('does not promise a refinement for an undecided note alone', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      penetration: {
        errorCount: 0,
        warningCount: 0,
        noteCount: 1,
        findings: [{
          code: 'undecided-contact',
          severity: 'note',
          partIds: ['peg', 'body'],
          message: '1 unrelated part pair(s) overlap partially ("Peg" and "Body" (22%)).',
        }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Cross-part penetration')).toBeInTheDocument());
    expect(screen.queryByText(/each part to get its own volume/)).not.toBeInTheDocument();
  });

  it('hides the section for a record generated before the gate existed', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, penetration: null });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());
    expect(screen.queryByText('Cross-part penetration')).not.toBeInTheDocument();
  });
});

describe('ThreejsModelDetail physical audit gate', () => {
  beforeEach(resetMocks);

  it('lists the physical audit finding and says an unsteered refinement will target physical conformance defects', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      physicalAudit: {
        errorCount: 0,
        warningCount: 1,
        noteCount: 0,
        evaluatedPartCount: 2,
        evaluatedPoseCount: 1,
        findings: [{
          code: 'floating-part',
          severity: 'warning',
          partIds: ['orb'],
          message: 'Part "Floating Orb" floats unattached in space.',
        }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
    expect(screen.getByText('Part "Floating Orb" floats unattached in space.')).toBeInTheDocument();
    expect(screen.getByText('0 error · 1 warning · 0 note')).toBeInTheDocument();
    expect(screen.getByText(/target physical conformance defects/)).toBeInTheDocument();
  });

  it('reports physical compliance on a clean pass', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      physicalAudit: { errorCount: 0, warningCount: 0, noteCount: 0, findings: [] },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
    expect(screen.getByText('Assembly satisfies physical attachment, exposure, and coplanarity rules')).toBeInTheDocument();
    expect(screen.queryByText(/target physical conformance defects/)).not.toBeInTheDocument();
  });

  it('hides the section for a record generated before the gate existed', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, physicalAudit: null });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());
    expect(screen.queryByText('Physical audit')).not.toBeInTheDocument();
  });
});

describe('ThreejsModelDetail material plausibility gate', () => {
  beforeEach(resetMocks);

  const implausible = {
    materialCount: 3,
    matchedMaterialCount: 2,
    errorCount: 0,
    warningCount: 1,
    noteCount: 0,
    findings: [{
      code: 'implausible-material-values',
      severity: 'warning',
      materialIds: ['oakPanel'],
      family: 'wood',
      channels: [{ channel: 'metalness', value: 0.9, min: 0, max: 0.15 }],
      message: 'Material "oakPanel" reads as wood, but metalness 0.9 is outside the 0–0.15 a wood surface normally sits in.',
    }],
  };

  it('lists the finding and says an unsteered refinement will target it', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, materialPlausibility: implausible });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Material plausibility')).toBeInTheDocument());
    expect(screen.getByText(implausible.findings[0].message)).toBeInTheDocument();
    expect(screen.getByText('0 error · 1 warning · 0 note')).toBeInTheDocument();
    expect(screen.getByText(/values that match the substance/)).toBeInTheDocument();
  });

  it('separates a clean pass from one where no material named a substance', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      materialPlausibility: { materialCount: 2, matchedMaterialCount: 2, findings: [] },
    });
    const { unmount } = renderDetail();
    await waitFor(() => expect(screen.getByText('Recognized materials match their substance')).toBeInTheDocument());
    expect(screen.queryByText(/values that match the substance/)).not.toBeInTheDocument();
    unmount();

    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      materialPlausibility: { materialCount: 2, matchedMaterialCount: 0, findings: [] },
    });
    renderDetail();
    await waitFor(() => expect(screen.getByText('No material named a substance to check')).toBeInTheDocument());
  });

  it('hides the section for a record generated before the gate existed', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, materialPlausibility: null });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());
    expect(screen.queryByText('Material plausibility')).not.toBeInTheDocument();
  });
});

describe('ThreejsModelDetail subject family', () => {
  beforeEach(resetMocks);

  const withFamily = (family) => ({
    ...baseRecord,
    family: 'vehicle',
    coverage: { errorCount: 0, warningCount: 0, noteCount: 0, findings: [], family },
  });

  it('marks each expected component resolved or not and names the orbit views to check', async () => {
    getThreejsModel.mockResolvedValue(withFamily({
      id: 'vehicle',
      label: 'Vehicle',
      components: ['Chassis or hull', 'Glazing', 'Lights'],
      missing: ['Lights'],
      reviewAxes: ['wheelbase and track proportion'],
      orbitViews: ['side profile', 'top-down'],
    }));
    renderDetail();

    await waitFor(() => expect(screen.getByText('Vehicle checklist')).toBeInTheDocument());
    expect(screen.getByText('1 of 3 unaccounted for')).toBeInTheDocument();
    expect(screen.getByText('Lights')).toBeInTheDocument();
    expect(screen.getByText(/side profile, top-down/)).toBeInTheDocument();
    expect(screen.getByText(/wheelbase and track proportion/)).toBeInTheDocument();
    expect(screen.getByText('Model preview vehicle')).toBeInTheDocument();
    // The floor-not-ceiling framing has to reach the user too — otherwise the
    // checklist reads as the whole job rather than the minimum.
    expect(screen.getByText(/floor, not a ceiling/)).toBeInTheDocument();
  });

  it('reports a fully accounted-for checklist without claiming completeness', async () => {
    getThreejsModel.mockResolvedValue(withFamily({
      id: 'vehicle', label: 'Vehicle', components: ['Chassis or hull'], missing: [], reviewAxes: [], orbitViews: [],
    }));
    renderDetail();

    await waitFor(() => expect(screen.getByText('Vehicle checklist')).toBeInTheDocument());
    expect(screen.getByText('Every expected component is accounted for')).toBeInTheDocument();
  });

  it('hides the checklist for a record generated with no family', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      coverage: { errorCount: 0, warningCount: 0, noteCount: 0, findings: [], family: null },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Assembly coverage')).toBeInTheDocument());
    expect(screen.queryByText(/checklist$/)).not.toBeInTheDocument();
    // With no family the coverage footer keeps its original honest caveat.
    expect(screen.getByText(/never that the spec promised enough/)).toBeInTheDocument();
  });

  it('seeds the picker from the record and sends the family with a refinement', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, family: 'vehicle' });
    generateThreejsModel.mockResolvedValue({ ...baseRecord, family: 'general', status: 'generating' });
    renderDetail();

    // The picker renders as soon as the taxonomy lands and is seeded from the
    // record a tick later, so the two fetches can resolve in either order.
    const picker = await screen.findByLabelText('Subject family');
    await waitFor(() => expect(picker).toHaveValue('vehicle'));

    // Switching back to General must turn the checklist OFF for the next pass
    // rather than silently re-applying the record's stored family.
    fireEvent.change(picker, { target: { value: 'general' } });
    fireEvent.click(screen.getByRole('button', { name: /Refine model/ }));

    await waitFor(() => expect(generateThreejsModel).toHaveBeenCalledWith(
      'threejs-example',
      expect.objectContaining({ family: 'general' }),
      { silent: true },
    ));
  });

  it('falls back to General for a family this build no longer ships', async () => {
    // A record written by a build with a larger taxonomy (a downgrade, or a
    // restored backup). Left as-is, the select would carry a value it has no
    // option for: what is on screen stops matching the state behind it, and
    // picking the option it appears to show fires no change event at all.
    getThreejsModel.mockResolvedValue({ ...baseRecord, family: 'kaiju-mecha-hybrid' });
    generateThreejsModel.mockResolvedValue({ ...baseRecord, status: 'generating' });
    renderDetail();

    const picker = await screen.findByLabelText('Subject family');
    await waitFor(() => expect(picker).toHaveValue('general'));
    // The header must not name a different family than the picker is showing.
    expect(screen.queryByText(/kaiju-mecha-hybrid/)).not.toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: /Refine model/ }));
    await waitFor(() => expect(generateThreejsModel).toHaveBeenCalledWith(
      'threejs-example',
      expect.objectContaining({ family: 'general' }),
      { silent: true },
    ));
  });
});

describe('ThreejsModelDetail rig readiness', () => {
  beforeEach(resetMocks);

  it('reports an articulation-ready character with its joint and pivot counts', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      rig: {
        articulationReady: true,
        reasons: [],
        jointCount: 6,
        socketCount: 5,
        attachmentCount: 1,
        anchoredAttachmentCount: 1,
        unanchoredAttachmentCount: 0,
        rootJointId: 'rootJoint',
        subjectType: 'character',
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());
    expect(screen.getByText('Articulation-ready')).toBeInTheDocument();
    expect(screen.getByText('6 joints · 5 pivot sockets · 1 declared attachment (1 anchored, 0 unanchored)')).toBeInTheDocument();
    // The claim has to stay bounded: readiness is not a rigged mesh.
    expect(screen.getByText(/never a skeleton/)).toBeInTheDocument();
  });

  it('reports a static assembly with the reasons rather than a silent pass', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      rig: {
        articulationReady: false,
        reasons: ['The spec declares no articulation graph, so this character is a static assembly.'],
        jointCount: 0,
        socketCount: 0,
        attachmentCount: 0,
        rootJointId: null,
        subjectType: 'character',
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());
    expect(screen.getByText('Static assembly')).toBeInTheDocument();
    expect(screen.getByText('0 joints · 0 pivot sockets · 0 declared attachments')).toBeInTheDocument();
    expect(screen.getByText(/declares no articulation graph/)).toBeInTheDocument();
    expect(screen.queryByText('Articulation-ready')).not.toBeInTheDocument();
  });

  // A record from before the report shipped was never evaluated, which is not
  // the same as having passed — it degrades to static and says so.
  it('degrades a record with no report to an unevaluated static assembly', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, rig: undefined });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());
    expect(screen.getByText('Static assembly')).toBeInTheDocument();
    expect(screen.getByText(/generated before rig readiness was reported/)).toBeInTheDocument();
  });

  it('omits the panel entirely until there is a generated scene', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, spec: null, rig: undefined });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());
    expect(screen.queryByText('Rig readiness')).not.toBeInTheDocument();
  });
});

// An attachment whose anchor could not be measured was never checked, and the
// panel's clean label would otherwise assert that it passed.
describe('ThreejsModelDetail unmeasured attachments', () => {
  beforeEach(resetMocks);

  it('renders an unmeasured attachment as a note rather than letting the panel read clean', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      physicalAudit: {
        findings: [],
        errorCount: 0,
        warningCount: 0,
        noteCount: 0,
        unmeasuredAttachments: [
          { partId: 'hat', anchorPartId: 'head', anchorSocket: null, reason: 'the anchor part has no visible geometry to measure' },
        ],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
    expect(screen.getByText(/Attachment "hat" could not be checked against "head"/)).toBeInTheDocument();
    expect(screen.queryByText('Assembly satisfies physical attachment, exposure, and coplanarity rules')).not.toBeInTheDocument();
  });
});

// Interior clip poses are only as covered as the audit says: the panel names the
// times it measured and the ones the budget left out, and an audit stored before
// that report existed is never presented as having measured the motion.
describe('ThreejsModelDetail clip pose coverage', () => {
  beforeEach(resetMocks);

  const animatedSpec = {
    ...baseRecord.spec,
    animation: {
      cues: [],
      clips: [{
        id: 'swing',
        name: 'Swing',
        durationSeconds: 2,
        sequences: [{ id: 'turn', name: 'Turn', partId: 'arm', startSeconds: 0, endSeconds: 2, channels: { rotationDegrees: { from: [0, 0, 0], to: [0, 0, 360] } } }],
      }],
    },
  };
  const cleanAudit = { errorCount: 0, warningCount: 0, noteCount: 0, findings: [], unmeasuredAttachments: [] };

  it('lists the measured and omitted clip times', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      spec: animatedSpec,
      physicalAudit: {
        ...cleanAudit,
        poseCoverage: {
          status: 'partial',
          measuresAttachments: true,
          budget: 48,
          clips: [{ clipId: 'swing', clipName: 'Swing', sampledTimes: [0, 1, 2], omittedCount: 2, omittedTimes: [0.5, 1.5] }],
        },
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
    expect(screen.getByText('Clip poses checked (the 48-pose budget ran out):')).toBeInTheDocument();
    expect(screen.getByText(/0s, 1s, 2s/)).toBeInTheDocument();
    expect(screen.getByText('; 2 omitted (0.5s, 1.5s)')).toBeInTheDocument();
  });

  it('reads an animated record audited before coverage reporting as unmeasured mid-motion', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, spec: animatedSpec, physicalAudit: cleanAudit });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());
    expect(screen.getByText(/This audit predates interior clip-pose sampling/)).toBeInTheDocument();
    expect(screen.queryByText('Assembly satisfies physical attachment, exposure, and coplanarity rules')).not.toBeInTheDocument();
  });
});

describe('ThreejsModelDetail rig readiness fallbacks', () => {
  beforeEach(resetMocks);

  // A report that reached this install without its counts must not print
  // "undefined joints" — it falls back to what the spec itself declares.
  it('counts from the spec when the stored report arrived without tallies', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      spec: {
        ...baseRecord.spec,
        articulation: {
          joints: [
            { id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },
            { id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: 'shoulder' },
          ],
          attachmentPartIds: [],
          attachments: [{ partId: 'pack', anchorPartId: 'torso', anchorSocket: null, maxOffset: 0.25 }],
        },
      },
      rig: { articulationReady: true, reasons: [] },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());
    expect(screen.getByText('2 joints · 1 pivot socket · 1 declared attachment (1 anchored, 0 unanchored)')).toBeInTheDocument();
    expect(screen.queryByText(/undefined/)).not.toBeInTheDocument();
  });

  // A report written before anchors shipped carries a total and no split.
  // Inferring the split from the total would credit a legacy attachment as
  // anchored — the exact overstatement the split exists to remove — so the
  // panel reads the spec instead.
  it('reads the anchored/unanchored split off the spec when the stored report predates it', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      spec: {
        ...baseRecord.spec,
        articulation: {
          joints: [
            { id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },
            { id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: 'shoulder' },
          ],
          attachmentPartIds: ['pack'],
        },
      },
      rig: { articulationReady: false, reasons: [], jointCount: 2, socketCount: 1, attachmentCount: 1 },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());
    expect(screen.getByText('2 joints · 1 pivot socket · 1 declared attachment (0 anchored, 1 unanchored)')).toBeInTheDocument();
  });
});

describe('ThreejsModelDetail clip inventory', () => {
  beforeEach(resetMocks);

  it('lists the clips the server inventoried, with role, duration and cue count', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      animation: {
        animated: true,
        clipCount: 1,
        clips: [{ id: 'deploy', name: 'Deploy', role: 'deploy', durationSeconds: 2, sequenceCount: 3, cueCount: 1 }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Animation clips')).toBeInTheDocument());
    expect(screen.getByText('Deploy')).toBeInTheDocument();
    expect(screen.getByText('2s · 3 sequences · 1 sound cue')).toBeInTheDocument();
  });

  // A record generated before the inventory shipped still has the clips in its
  // spec, so the panel derives them rather than claiming the model is static.
  it('derives the list from the spec when the record carries no inventory', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      animation: undefined,
      spec: {
        ...baseRecord.spec,
        animation: {
          cues: [],
          clips: [{
            id: 'retract',
            name: 'Retract',
            role: 'retract',
            durationSeconds: 1,
            sequences: [{ id: 'fold', cueId: null }],
          }],
        },
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Animation clips')).toBeInTheDocument());
    expect(screen.getByText('1s · 1 sequence')).toBeInTheDocument();
  });

  it('renders the clip-playback gate for a model whose clips will not play cleanly', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      animation: {
        animated: true,
        clipCount: 1,
        warningCount: 1,
        clips: [{ id: 'deploy', name: 'Deploy', role: 'deploy', durationSeconds: 2, sequenceCount: 1, cueCount: 0 }],
        findings: [{
          code: 'clip-start-pose-mismatch',
          severity: 'warning',
          message: 'clip Deploy is authored against a pose the assembly does not build',
        }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Clip playback')).toBeInTheDocument());
    expect(screen.getByText(/clip Deploy is authored against a pose/)).toBeInTheDocument();
    expect(screen.getByText('0 error · 1 warning · 0 note')).toBeInTheDocument();
  });

  // The gate also reports an articulation graph with no clip to play it, which
  // by definition arrives on a model that declared no clips at all.
  it('renders a clip finding raised against a model with no clips', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      animation: {
        animated: false,
        clipCount: 0,
        warningCount: 1,
        clips: [],
        findings: [{
          code: 'articulation-without-clips',
          severity: 'warning',
          message: 'the spec declares an articulation graph over 4 joints but no animation clip',
        }],
      },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Clip playback')).toBeInTheDocument());
    expect(screen.getByText(/declares an articulation graph over 4 joints/)).toBeInTheDocument();
  });

  // A static assembly evaluates to an empty finding list, which is not a verdict
  // about clips — it never declared any.
  it('shows no clip-playback gate for a static assembly that was evaluated', async () => {
    getThreejsModel.mockResolvedValue({
      ...baseRecord,
      animation: { animated: false, clipCount: 0, warningCount: 0, clips: [], findings: [] },
    });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());
    expect(screen.queryByText('Clip playback')).not.toBeInTheDocument();
  });

  it('shows no clip panel for a static assembly', async () => {
    getThreejsModel.mockResolvedValue({ ...baseRecord, animation: null });
    renderDetail();

    await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());
    expect(screen.queryByText('Animation clips')).not.toBeInTheDocument();
  });
});