Free Motion Capture for Everyone πβ¨
TypeScript
Merge pull request #827
jonmatthis1a82cd03c1d6
diff --git a/.github/workflows/build-installers-pyinstaller.yml b/.github/workflows/build-installers-pyinstaller.ymlindex d152a39a..09895b25 100644--- a/.github/workflows/build-installers-pyinstaller.yml+++ b/.github/workflows/build-installers-pyinstaller.yml@@ -7,13 +7,19 @@ on:tags:- 'v*'workflow_dispatch:+ inputs:+ variant:+ description: 'Build variant'+ type: choice+ options: [cpu, cuda, both]+ default: bothenv:FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: truejobs:# βββββββββββββββββββββββββββββββββββββββββββββββββββββββ- # BUILD β runs on all 5 platform/arch combos+ # BUILD β runs on all platform/arch/variant combos# βββββββββββββββββββββββββββββββββββββββββββββββββββββββbuild:runs-on: ${{ matrix.os }}@@ -21,63 +27,74 @@ jobs:fail-fast: falsematrix:include:- # Windows x64 ships both a CUDA (GPU-accelerated) and a CPU-only- # variant β same OS/arch, different onnxruntime backend, selected via- # `uv sync --extra ${{ matrix.variant }}` and FREEMOCAP_BUILD_VARIANT.- # Linux x64 ships both variants too. CUDA's release assets exceed- # GitHub's 2GB release-asset limit, so the release job publishes- # them to Cloudflare R2 instead of the GitHub Release (see the- # "release" job below). macOS and Linux arm64 only ever build the- # CPU variant: macOS has no CUDA path, and NVIDIA's PyPI CUDA- # wheels used here are x86_64-only.+ # ββ Windows ββ- os: windows-latestplatform: windowsarch: x64- variant: cuda- label: windows-x64-cuda+ variant: cpu+ label: windows-x64-cpuserver-binary: freemocap_server.exeelectron-arch: x64+ install-gpu: false- os: windows-latestplatform: windowsarch: x64- variant: cpu- label: windows-x64-cpu+ variant: cuda+ label: windows-x64-cudaserver-binary: freemocap_server.exeelectron-arch: x64-#-# # macOS is Apple-Silicon only: onnxruntime (pulled via skellytracker) ships-# # no macOS x86_64 wheels, so an Intel-Mac build can't resolve its ML backend.-# - os: macos-15-intel-# platform: macos-# arch: x64-# variant: cpu-# label: macos-x64-intel-# server-binary: freemocap_server-# electron-arch: x64-#+ install-gpu: true++ # ββ macOS Intel (macos-13 is the last Intel runner) ββ+ - os: macos-13+ platform: macos+ arch: x64+ variant: gpu+ label: macos-x64-intel+ server-binary: freemocap_server+ electron-arch: x64+ install-gpu: true++ # ββ macOS Apple Silicon ββ- os: macos-latestplatform: macosarch: arm64- variant: cpu+ variant: gpulabel: macos-arm64-apple-siliconserver-binary: freemocap_serverelectron-arch: arm64+ install-gpu: true++ # ββ Linux x64 CPU (fits on GitHub Releases) ββ- os: ubuntu-22.04platform: linuxarch: x64- variant: cuda- label: linux-x64-cuda+ variant: cpu+ label: linux-x64-cpuserver-binary: freemocap_serverelectron-arch: x64+ install-gpu: false+ # ββ Linux x64 CUDA (goes to R2 β too large for GitHub) ββ- os: ubuntu-22.04platform: linuxarch: x64- variant: cpu- label: linux-x64-cpu+ variant: cuda+ label: linux-x64-cudaserver-binary: freemocap_serverelectron-arch: x64+ install-gpu: true++ # ββ Linux ARM64 CPU only (onnxruntime-gpu has no aarch64 wheels) ββ+ - os: ubuntu-22.04-arm+ platform: linux+ arch: arm64+ variant: cpu+ label: linux-arm64-cpu+ server-binary: freemocap_server+ electron-arch: arm64+ install-gpu: falsesteps:- name: Checkout code@@ -92,7 +109,8 @@ jobs:if (-not "${{ secrets.AZURE_TENANT_ID }}") { $missingSecrets += "AZURE_TENANT_ID" }if (-not "${{ secrets.AZURE_CLIENT_ID }}") { $missingSecrets += "AZURE_CLIENT_ID" }if (-not "${{ secrets.AZURE_CLIENT_SECRET }}") { $missingSecrets += "AZURE_CLIENT_SECRET" }- if (-not "freemocap") { $missingSecrets += "TRUSTED_SIGNING_ACCOUNT_NAME" }+ if (-not "${{ secrets.TRUSTED_SIGNING_ACCOUNT_NAME }}") { $missingSecrets += "TRUSTED_SIGNING_ACCOUNT_NAME" }+ if (-not "${{ secrets.CERTIFICATE_PROFILE_NAME }}") { $missingSecrets += "CERTIFICATE_PROFILE_NAME" }if ($missingSecrets.Count -gt 0) {Write-Error "Missing required secrets for code signing: $($missingSecrets -join ', ')"@@ -168,7 +186,8 @@ jobs:libxrender1 \libv4l-dev \libfuse2 \- upx-ucl+ upx-ucl \+ binutils# ββ macOS UPX for binary compression ββ- name: Install UPX (macOS)@@ -180,8 +199,6 @@ jobs:uses: actions/setup-node@v6with:node-version: '22'- cache: 'npm'- cache-dependency-path: freemocap-ui/package-lock.json- name: Set up Pythonuses: actions/setup-python@v6@@ -191,14 +208,29 @@ jobs:- name: Install uv and enable cacheuses: astral-sh/setup-uv@cec208311dfd045dd5311c1add060b2062131d57with:- enable-cache: true- cache-suffix: ${{ matrix.label }}+ enable-cache: false- name: Create venvrun: uv venv- - name: Install the project dependencies- run: uv sync --no-default-groups --group ${{ matrix.variant }}+ # ββ Conditional dependency install ββ+ # CPU variant: swap skellytracker[recommended] β skellytracker[mediapipe]+ # (installs mediapipe but zero NVIDIA CUDA packages β AppImage fits on GitHub)+ # CUDA variant: keep skellytracker[recommended] (full CUDA 12 + TensorRT stack)+ - name: Install dependencies (CPU variant)+ if: "!matrix.install-gpu"+ shell: bash+ run: |+ echo "=== CPU BUILD β swapping to skellytracker[mediapipe] (no NVIDIA packages) ==="+ sed -i 's/"skellytracker\[recommended\]"/"skellytracker[mediapipe]"/' pyproject.toml+ grep 'skellytracker' pyproject.toml+ uv sync++ - name: Install dependencies (CUDA variant)+ if: matrix.install-gpu+ run: |+ echo "=== CUDA BUILD β using skellytracker[recommended] (full GPU stack) ==="+ uv sync- name: Verify installation 1/3run: uv pip show freemocap@@ -230,26 +262,21 @@ jobs:# ββ PyInstaller build ββ- name: Build with PyInstaller- env:- FREEMOCAP_BUILD_VARIANT: ${{ matrix.variant }}run: |uv pip install pyinstalleruv run pyinstaller ./freemocap.spec --clean# ββ Move server binary into freemocap-ui/ ββ- # PyInstaller onedir output is a directory (dist/freemocap_server/) containing- # the exe plus its _internal/ support files β always named "freemocap_server"- # regardless of platform (the .exe extension only applies to the exe inside it).- name: Move server binary into freemocap-ui (Windows)if: matrix.platform == 'windows'run: |- Move-Item -Path ".\dist\freemocap_server" -Destination ".\freemocap-ui\freemocap_server"+ Move-Item -Path ".\dist\${{ matrix.server-binary }}" -Destination ".\freemocap-ui\${{ matrix.server-binary }}"- name: Move server binary into freemocap-ui (macOS/Linux)if: matrix.platform != 'windows'run: |- mv "./dist/freemocap_server" "./freemocap-ui/freemocap_server"- chmod +x "./freemocap-ui/freemocap_server/${{ matrix.server-binary }}"+ mv "./dist/${{ matrix.server-binary }}" "./freemocap-ui/${{ matrix.server-binary }}"+ chmod +x "./freemocap-ui/${{ matrix.server-binary }}"# ββ Windows code signing (server binary) ββ- name: Sign freemocap_server.exe with Trusted Signing@@ -262,35 +289,29 @@ jobs:endpoint: https://eus.codesigning.azure.net/trusted-signing-account-name: freemocapcertificate-profile-name: freemocap- files: ${{ github.workspace }}\freemocap-ui\freemocap_server\${{ matrix.server-binary }}+ files: ${{ github.workspace }}\freemocap-ui\freemocap_server.exefile-digest: SHA256timestamp-rfc3161: http://timestamp.acs.microsoft.comtimestamp-digest: SHA256# ββ macOS code signing (server binary) ββ- # Onedir ships many loose .dylib/.so files under _internal/ that notarization- # also requires to be signed, not just the main executable.- name: Sign freemocap_server with codesignif: matrix.platform == 'macos'run: |- echo "Signing nested binaries in freemocap_server/_internal..."- find "./freemocap-ui/freemocap_server/_internal" -type f \( -name "*.dylib" -o -name "*.so" \) -exec \- codesign --force --options runtime --sign "Developer ID Application" --timestamp {} \;-- echo "Signing main executable..."codesign --force --options runtime --sign "Developer ID Application" \--timestamp \- "./freemocap-ui/freemocap_server/${{ matrix.server-binary }}"- codesign --verify --verbose "./freemocap-ui/freemocap_server/${{ matrix.server-binary }}"+ "./freemocap-ui/${{ matrix.server-binary }}"+ codesign --verify --verbose "./freemocap-ui/${{ matrix.server-binary }}"echo "Server binary signed and verified successfully"+# ββ Upload server-only artifact ββ- name: Upload server binary artifactuses: actions/upload-artifact@v7with:name: server-${{ matrix.label }}path: |- freemocap-ui/freemocap_server/+ freemocap-ui/${{ matrix.server-binary }}include-hidden-files: true# ββ Electron build ββ@@ -299,46 +320,23 @@ jobs:- name: Validate server binary present and executableshell: bashrun: |- echo "Checking for server binary at ./freemocap-ui/freemocap_server/${{ matrix.server-binary }}"- if [ ! -d "./freemocap-ui/freemocap_server" ] || [ ! -f "./freemocap-ui/freemocap_server/${{ matrix.server-binary }}" ]; then- echo "::error::Server binary not found: ./freemocap-ui/freemocap_server/${{ matrix.server-binary }}"+ echo "Checking for server binary at ./freemocap-ui/${{ matrix.server-binary }}"+ if [ ! -f "./freemocap-ui/${{ matrix.server-binary }}" ]; then+ echo "::error::Server binary not found: ./freemocap-ui/${{ matrix.server-binary }}"ls -la ./freemocap-ui || trueexit 1fi-- # The launcher loads everything from its sibling _internal/ directory,- # so its absence means the onedir tree was moved or collected wrong.- if [ ! -d "./freemocap-ui/freemocap_server/_internal" ]; then- echo "::error::Missing _internal/ next to the server launcher"- ls -la ./freemocap-ui/freemocap_server- exit 1- fi-echo "Found server binary:"- ls -la "./freemocap-ui/freemocap_server/${{ matrix.server-binary }}"+ ls -la "./freemocap-ui/${{ matrix.server-binary }}"# On Unix-like, ensure executable bit is setif [ "${{ matrix.platform }}" != "windows" ]; then- if [ ! -x "./freemocap-ui/freemocap_server/${{ matrix.server-binary }}" ]; then+ if [ ! -x "./freemocap-ui/${{ matrix.server-binary }}" ]; thenecho "Server binary is not executable, setting +x"- chmod +x "./freemocap-ui/freemocap_server/${{ matrix.server-binary }}" || true+ chmod +x "./freemocap-ui/${{ matrix.server-binary }}" || truefifi- - name: Cache Electron build tooling- uses: actions/cache@v4- with:- path: |- ~/.cache/electron- ~/.cache/electron-builder- ~/Library/Caches/electron- ~/Library/Caches/electron-builder- ~/AppData/Local/electron/Cache- ~/AppData/Local/electron-builder/Cache- key: electron-cache-${{ matrix.os }}-${{ hashFiles('freemocap-ui/package-lock.json') }}- restore-keys: |- electron-cache-${{ matrix.os }}--- name: Install UI dependenciesrun: |cd freemocap-ui@@ -376,6 +374,104 @@ jobs:cd freemocap-uinpm run build -- --${{ matrix.electron-arch }} --publish never+ # ββ Architecture validation (Linux) ββ+ # Prevents ARM binaries from being mislabeled as x64 (or vice versa).+ # Uses readelf to inspect the ELF header Machine field.+ - name: Validate binary architecture (Linux)+ if: matrix.platform == 'linux'+ run: |+ echo "=== Validating binary architecture ==="+ for appimage in freemocap-ui/release/*/*.AppImage; do+ [ -f "$appimage" ] || continue+ BIN_ARCH=$(readelf -h "$appimage" | awk '/Machine:/{print $NF}')+ case "${{ matrix.arch }}" in+ x64) EXPECTED="X86-64" ;;+ arm64) EXPECTED="AArch64" ;;+ esac+ if [ "$BIN_ARCH" != "$EXPECTED" ]; then+ echo "::error::ARCHITECTURE MISMATCH DETECTED!"+ echo "::error:: File: $appimage"+ echo "::error:: Actual: $BIN_ARCH"+ echo "::error:: Expected: $EXPECTED"+ echo "::error::"+ echo "::error:: This build produced a binary for the WRONG architecture."+ echo "::error:: Possible causes:"+ echo "::error:: - Electron-builder ignored the --${{ matrix.electron-arch }} CLI flag"+ echo "::error:: - electron-builder.json 'arch' array still contains both architectures"+ echo "::error:: - Cross-compilation misconfiguration"+ echo "::error::"+ echo "::error:: Refusing to publish. Fix the build config and re-run."+ exit 1+ fi+ echo "β Architecture OK: $(basename "$appimage") = $BIN_ARCH"+ done+ # Also validate .deb if present+ for deb in freemocap-ui/release/*/*.deb; do+ [ -f "$deb" ] || continue+ # .deb contains a data.tar.* with the binary; check the ar archive header+ DEB_ARCH=$(dpkg-deb --info "$deb" 2>/dev/null | awk '/Architecture:/{print $NF}')+ if [ -n "$DEB_ARCH" ]; then+ case "${{ matrix.arch }}" in+ x64) EXPECTED_DEB="amd64" ;;+ arm64) EXPECTED_DEB="arm64" ;;+ esac+ if [ "$DEB_ARCH" != "$EXPECTED_DEB" ]; then+ echo "::error::DEB ARCHITECTURE MISMATCH! $deb = $DEB_ARCH, expected $EXPECTED_DEB"+ exit 1+ fi+ echo "β DEB architecture OK: $(basename "$deb") = $DEB_ARCH"+ fi+ done++ # ββ R2 upload for CUDA (oversized) builds ββ+ # CUDA builds bundle NVIDIA runtime libraries (~1.5 GB) and exceed+ # GitHub's 2 GB file size limit. They go to Cloudflare R2 instead.+ - name: Upload CUDA builds to Cloudflare R2+ if: matrix.variant == 'cuda'+ shell: bash+ env:+ R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}+ R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}+ R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }}+ R2_BUCKET: ${{ secrets.R2_BUCKET }}+ run: |+ if [ -z "$R2_ACCESS_KEY_ID" ] || [ -z "$R2_BUCKET" ]; then+ echo "::warning::R2 credentials not configured β skipping R2 upload"+ echo "::warning::Set R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_ENDPOINT, R2_BUCKET secrets"+ exit 0+ fi++ echo "=== Uploading CUDA builds to Cloudflare R2 ==="+ pip install awscli++ VERSION="${GITHUB_REF#refs/tags/v}"+ if [ -z "$VERSION" ] || [ "$VERSION" = "$GITHUB_REF" ]; then+ # Not a tag push β use run number as version placeholder+ VERSION="dev-${{ github.run_number }}"+ fi++ for file in freemocap-ui/release/*/*.AppImage freemocap-ui/release/*/*.deb; do+ [ -f "$file" ] || continue+ ext="${file##*.}"+ aws s3 cp "$file" \+ "s3://${R2_BUCKET}/releases/v${VERSION}/freemocap_${VERSION}_${{ matrix.label }}.${ext}" \+ --endpoint-url "${R2_ENDPOINT}" \+ --no-progress+ echo "R2: freemocap_${VERSION}_${{ matrix.label }}.${ext}"+ done++ # Upload auto-update metadata for the CUDA variant+ for yml in freemocap-ui/release/*/latest-linux.yml; do+ [ -f "$yml" ] || continue+ aws s3 cp "$yml" \+ "s3://${R2_BUCKET}/releases/v${VERSION}/latest-linux-${{ matrix.variant }}.yml" \+ --endpoint-url "${R2_ENDPOINT}" \+ --no-progress+ echo "R2: latest-linux-${{ matrix.variant }}.yml"+ done++ echo "=== R2 upload complete ==="+# ββ Windows installer signing ββ- name: Sign Electron installer with Trusted Signingif: matrix.platform == 'windows'@@ -425,19 +521,8 @@ jobs:include-hidden-files: true# ββ Upload auto-update metadata (latest*.yml) ββ- # electron-updater supports only one update channel per platform/arch,- # and the app can't tell CUDA and CPU builds apart at runtime (see- # update-handler.ts) β so whichever variant we point a channel at gets- # silently offered to installs of the OTHER variant too. Windows tracks- # CUDA safely (both variants fit under GitHub's 2GB release-asset- # limit). Linux tracks nothing for now: CUDA is disabled for being- # oversized, and CPU is deliberately NOT used as a stand-in channel,- # since that would silently swap existing CUDA installs onto a non-GPU- # build on their next update check. Everyone on Linux gets new- # installers manually via the release page until Linux has real- # per-variant channels.- name: Upload auto-update metadata (Windows)- if: matrix.platform == 'windows' && matrix.variant == 'cuda'+ if: matrix.platform == 'windows'uses: actions/upload-artifact@v7with:name: update-metadata-${{ matrix.label }}@@ -446,7 +531,7 @@ jobs:include-hidden-files: true- name: Upload auto-update metadata (macOS)- if: matrix.platform == 'macos'+ if: matrix.platform == 'macos' && matrix.arch == 'x64'uses: actions/upload-artifact@v7with:name: update-metadata-${{ matrix.label }}@@ -454,16 +539,23 @@ jobs:freemocap-ui/release/**/latest-mac.ymlinclude-hidden-files: true- # Linux's channel is disabled entirely (see comment above) β neither- # variant is safe to publish as a shared channel right now.-# - name: Upload auto-update metadata (Linux)-# if: matrix.platform == 'linux' && matrix.arch == 'x64' && matrix.variant == 'cpu'-# uses: actions/upload-artifact@v7-# with:-# name: update-metadata-${{ matrix.label }}-# path: |-# freemocap-ui/release/**/latest-linux.yml-# include-hidden-files: true+ - name: Upload auto-update metadata (macOS ARM)+ if: matrix.platform == 'macos' && matrix.arch == 'arm64'+ uses: actions/upload-artifact@v7+ with:+ name: update-metadata-${{ matrix.label }}+ path: |+ freemocap-ui/release/**/latest-mac.yml+ include-hidden-files: true++ - name: Upload auto-update metadata (Linux)+ if: matrix.platform == 'linux'+ uses: actions/upload-artifact@v7+ with:+ name: update-metadata-${{ matrix.label }}+ path: |+ freemocap-ui/release/**/latest-linux.yml+ include-hidden-files: true# ββ macOS keychain cleanup ββ@@ -475,12 +567,16 @@ jobs:if [ -f "$KEYCHAIN_PATH" ]; thensecurity delete-keychain "$KEYCHAIN_PATH"fi+# βββββββββββββββββββββββββββββββββββββββββββββββββββββββ# RELEASE β only runs on tag pushes (e.g. v2.0.0)## Downloads all build artifacts and renames them with- # human-readable platform/arch labels for the GitHub- # Release page.+ # human-readable platform/arch/variant labels for the+ # GitHub Release page.+ #+ # CPU variants β GitHub Releases (fit under 2 GB limit)+ # CUDA variants β Cloudflare R2 (uploaded during build)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββrelease:needs: build@@ -499,59 +595,40 @@ jobs:- name: Prepare release assetsrun: |- mkdir -p release-assets r2-assets+ mkdir -p release-assets# Extract version from tag (e.g. refs/tags/v2.0.0 β 2.0.0)VERSION="${GITHUB_REF#refs/tags/v}"echo "VERSION=$VERSION"- # ββ Server binaries ββ+ # ββ Server binaries (all variants β small enough for GitHub) ββ# Artifact directories are named server-<label>, e.g.:- # server-windows-x64-cuda, server-windows-x64-cpu,- # server-macos-arm64-apple-silicon, server-linux-x64-cuda,- # server-linux-x64-cpu- # Strip the "server-" prefix to get the human-readable suffix.- # Each artifact is a PyInstaller onedir folder (exe + _internal/ support- # files), so it's zipped into a single release asset rather than copied.- # linux-x64-cuda's zip exceeds GitHub's 2GB release-asset limit, so it- # goes to r2-assets/ (uploaded to Cloudflare R2) instead of release-assets/.+ # server-windows-x64-cpu, server-windows-x64-cuda,+ # server-macos-x64-intel, server-macos-arm64-apple-silicon,+ # server-linux-x64-cpu, server-linux-x64-cuda, server-linux-arm64-cpufor dir in artifacts/server-*; dolabel=$(basename "$dir" | sed 's/^server-//')if [ -f "$dir/freemocap_server.exe" ]; then- exe_name="freemocap_server.exe"+ cp "$dir/freemocap_server.exe" "release-assets/freemocap_server_${VERSION}_${label}.exe"elif [ -f "$dir/freemocap_server" ]; then- exe_name="freemocap_server"+ cp "$dir/freemocap_server" "release-assets/freemocap_server_${VERSION}_${label}"else- echo "::error::No server binary found in $dir"- exit 1+ echo "::warning::No server binary found in $dir β skipping"fi-- chmod +x "$dir/$exe_name" || true-- if [ "$label" = "linux-x64-cuda" ]; then- dest="r2-assets"- else- dest="release-assets"- fi- (cd "$dir" && zip -r -q -X "$OLDPWD/$dest/freemocap_server_${VERSION}_${label}.zip" .)done- # ββ App installers ββ- # Artifact directories are named installer-<label>, e.g.:- # installer-windows-x64-cuda, installer-windows-x64-cpu,- # installer-macos-arm64-apple-silicon, etc.- # Electron-builder names only contain the arch (x64/arm64),- # so we rename each file to: freemocap_<VERSION>_<label>.<ext>- # Same linux-x64-cuda β r2-assets/ routing as above.+ # ββ App installers β all except Linux CUDA (which goes to R2) ββ+ # CPU installers + Windows CUDA fit under GitHub's 2 GB file limit.+ # Linux CUDA bundles NVIDIA runtime libraries (~1.5 GB extra, >2 GB total)+ # and is uploaded to Cloudflare R2 during the build job instead.for dir in artifacts/installer-*; dolabel=$(basename "$dir" | sed 's/^installer-//')- if [ "$label" = "linux-x64-cuda" ]; then- dest="r2-assets"- else- dest="release-assets"- fi+ # Skip Linux CUDA β it goes to R2+ case "$label" in+ linux-*-cuda) continue ;;+ esacfind "$dir" -type f \( \-name '*.exe' -o \@@ -561,30 +638,12 @@ jobs:-name '*.deb' \\) | while read -r file; doext="${file##*.}"- cp "$file" "$dest/freemocap_${VERSION}_${label}.${ext}"+ cp "$file" "release-assets/freemocap_${VERSION}_${label}.${ext}"donedoneecho "=== Release assets ==="ls -lh release-assets/- echo "=== R2 assets (Linux CUDA) ==="- ls -lh r2-assets/-- - name: Upload Linux CUDA build to Cloudflare R2- env:- AWS_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}- AWS_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}- AWS_DEFAULT_REGION: auto- run: |- VERSION="${GITHUB_REF#refs/tags/v}"- for file in r2-assets/*; do- echo "Uploading $(basename "$file") to R2..."- aws s3 cp "$file" "s3://freemocap-releases/${VERSION}/$(basename "$file")" \- --endpoint-url "${{ secrets.CLOUDFLARE_R2_S3_ENDPOINT }}" \- --no-progress- done-- echo "=== Uploaded to R2 under ${VERSION}/ ==="- name: Prepare auto-update metadatarun: |@@ -593,40 +652,52 @@ jobs:# Copy latest.yml files from update-metadata artifacts and patch# the file references to match the renamed release asset names.- # Windows: latest.yml (CUDA variant is the auto-update channel β see- # the "Upload auto-update metadata" step comment in the build job)- if [ -d "artifacts/update-metadata-windows-x64-cuda" ]; then- YML=$(find artifacts/update-metadata-windows-x64-cuda -name 'latest.yml' | head -1)+ # Windows: latest.yml+ if [ -d "artifacts/update-metadata-windows-x64-cpu" ]; then+ YML=$(find artifacts/update-metadata-windows-x64-cpu -name 'latest.yml' | head -1)if [ -n "$YML" ]; then- # Replace electron-builder's FreeMoCap_<ver>_<arch>_installer.exe- # reference with the renamed asset. The prefix is case-tolerant- # because electron uses the "FreeMoCap" productName casing.- sed -i "s|[Ff]ree[Mm]o[Cc]ap_.*_installer\.exe|freemocap_${VERSION}_windows-x64-cuda.exe|g" "$YML"+ # Replace the original artifact filename with the renamed one+ sed -i "s|freemocap_.*_installer\.exe|freemocap_${VERSION}_windows-x64-cpu.exe|g" "$YML"cp "$YML" "release-assets/latest.yml"- echo "Copied latest.yml for Windows"+ echo "Copied latest.yml for Windows (CPU)"fifi- # macOS: latest-mac.yml (Apple Silicon only β see the build matrix)- MAC_YML=$(find artifacts/update-metadata-macos-arm64-apple-silicon -name 'latest-mac.yml' 2>/dev/null | head -1)+ # macOS: latest-mac.yml (combine x64 and arm64 entries)+ # electron-updater picks the right arch from a single latest-mac.yml+ MAC_YML=""+ for dir in artifacts/update-metadata-macos-*; do+ found=$(find "$dir" -name 'latest-mac.yml' 2>/dev/null | head -1)+ if [ -n "$found" ] && [ -z "$MAC_YML" ]; then+ MAC_YML="$found"+ fi+ doneif [ -n "$MAC_YML" ]; then- # Patch electron-builder's FreeMoCap_<ver>_<arch>_installer.zip reference- # to the renamed release asset (case-tolerant prefix).- sed -i "s|[Ff]ree[Mm]o[Cc]ap_.*_installer\.zip|freemocap_${VERSION}_macos-arm64-apple-silicon.zip|g" "$MAC_YML"+ # Patch filenames to match renamed assets+ sed -i "s|freemocap_.*_installer\.zip|freemocap_${VERSION}_macos-x64-intel.zip|g" "$MAC_YML"cp "$MAC_YML" "release-assets/latest-mac.yml"echo "Copied latest-mac.yml for macOS"fi- # Linux: no update channel published right now β see the comment- # above the "Upload auto-update metadata" step in the build job.- # if [ -d "artifacts/update-metadata-linux-x64-cpu" ]; then- # YML=$(find artifacts/update-metadata-linux-x64-cpu -name 'latest-linux.yml' | head -1)- # if [ -n "$YML" ]; then- # sed -i "s|[Ff]ree[Mm]o[Cc]ap_.*\.AppImage|freemocap_${VERSION}_linux-x64-cpu.AppImage|g" "$YML"- # cp "$YML" "release-assets/latest-linux.yml"- # echo "Copied latest-linux.yml for Linux"- # fi- # fi+ # Linux CPU: latest-linux.yml+ if [ -d "artifacts/update-metadata-linux-x64-cpu" ]; then+ YML=$(find artifacts/update-metadata-linux-x64-cpu -name 'latest-linux.yml' | head -1)+ if [ -n "$YML" ]; then+ sed -i "s|freemocap_.*\.AppImage|freemocap_${VERSION}_linux-x64-cpu.AppImage|g" "$YML"+ cp "$YML" "release-assets/latest-linux.yml"+ echo "Copied latest-linux.yml for Linux (CPU)"+ fi+ fi++ # Also include linux-arm64-cpu latest-linux.yml if present+ if [ -d "artifacts/update-metadata-linux-arm64-cpu" ]; then+ YML=$(find artifacts/update-metadata-linux-arm64-cpu -name 'latest-linux.yml' | head -1)+ if [ -n "$YML" ]; then+ echo "Linux ARM64 latest-linux.yml available at: $YML"+ # Note: electron-updater currently only supports one latest-linux.yml;+ # ARM64 auto-update metadata is available for future use.+ fi+ fiecho "=== Final release assets ==="ls -lh release-assets/@@ -650,32 +721,3 @@ jobs:--generate-notes \--title "$TAG"fi-- - name: Add Cloudflare R2 links to release notes- env:- GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}- run: |- TAG="${GITHUB_REF#refs/tags/}"- VERSION="${GITHUB_REF#refs/tags/v}"- R2_PUBLIC_URL="https://pub-0a275a10417e425c94e48de393793129.r2.dev"-- gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json body -q .body > current-notes.md-- if grep -q "Linux (CUDA/GPU build)" current-notes.md; then- echo "R2 download links already present in release notes β skipping"- exit 0- fi-- {- echo ""- echo "---"- echo ""- echo "**Linux (CUDA/GPU build)** β too large for a GitHub release asset, hosted separately:"- echo ""- for file in r2-assets/*; do- name=$(basename "$file")- echo "- [$name](${R2_PUBLIC_URL}/${VERSION}/${name})"- done- } >> current-notes.md-- gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --notes-file current-notes.mddiff --git a/freemocap-docs/docs/architecture/api-boundary.mdx b/freemocap-docs/docs/architecture/api-boundary.mdxindex aa4643c2..f3ff940f 100644--- a/freemocap-docs/docs/architecture/api-boundary.mdx+++ b/freemocap-docs/docs/architecture/api-boundary.mdx@@ -309,14 +309,15 @@ Pipeline phases: `queued` β `setting_up` β `processing_videos` β `aggregat{"message_type": "tracker_schemas","schemas": {- "mediapipe_pose": {- "keypoint_names": ["nose", "left_eye", ...],- "connections": [[0, 1], [1, 2], ...]+ "rtmpose_wholebody": {+ "name": "rtmpose_wholebody",+ "tracked_points": ["nose", "left_eye", ...],+ "connections": [["left_shoulder", "left_elbow"], ["left_elbow", "left_wrist"], ...]}}}```-Note: message type is `"tracker_schemas"` (plural). The `schemas` field is a dict of tracker_id β TrackedObjectDefinition β multiple schemas are sent in one message.+Note: message type is `"tracker_schemas"` (plural). The `schemas` field is a dict of tracker name β `TrackerDefinition` β each with `name`, `tracked_points`, and name-pair `connections` (from `core/tracking/tracker_definitions.py`, e.g. `RTMPOSE_WHOLEBODY_DEFINITION`). Multiple schemas are sent in one message. See [Tracking Integration](/docs/architecture/tracking-integration).### Client β Server Messagesdiff --git a/freemocap-docs/docs/architecture/backend-calibration.mdx b/freemocap-docs/docs/architecture/backend-calibration.mdxindex adfc2785..11b83502 100644--- a/freemocap-docs/docs/architecture/backend-calibration.mdx+++ b/freemocap-docs/docs/architecture/backend-calibration.mdx@@ -9,7 +9,7 @@ import { AiGeneratedBanner, Tip } from '@freemocap/skellydocs';# Calibration-Calibration estimates each camera's position, orientation, and lens parameters by observing a known physical target β a ChArUco board β from multiple viewpoints. The output is a `CalibrationResult`: a set of camera models that enable 3D triangulation.+Calibration estimates each camera's position, orientation, and lens parameters by observing a known physical target β a ChArUco board β from multiple viewpoints. The output is a `CalibrationResult`: a set of camera models that enable 3D triangulation. ChArUco detection and the `CharucoBoardDefinition` geometry come from [SkellyTracker](https://freemocap.github.io/skellytracker/); calibration consumes the resulting `Observation`s.## When Calibration Runsdiff --git a/freemocap-docs/docs/architecture/backend-mocap.mdx b/freemocap-docs/docs/architecture/backend-mocap.mdxindex 756f04a5..acbe85ae 100644--- a/freemocap-docs/docs/architecture/backend-mocap.mdx+++ b/freemocap-docs/docs/architecture/backend-mocap.mdx@@ -20,20 +20,20 @@ Mocap processing takes 2D pose detections from multiple camera views, triangulatRTMPose is a top-down pose estimation model from MMPose, running via ONNX Runtime. It's the default skeleton detector for both realtime and posthoc pipelines.**Configuration** (`RTMPoseDetectorConfig`):-- `mode`: "balanced" (default), "speed", or "accuracy" β trades off inference time vs detection quality-- `confidence_threshold`: minimum confidence for a keypoint to be included (default: 5, range 0β10)+- `model_name`: RTMPose model variant (e.g. `"rtmw-x-l_256x192"`) β trades off inference time vs detection quality+- `confidence_threshold`: minimum confidence for a keypoint to be kept (a float, e.g. `0.004`)**Two deployment modes:**| Mode | Where it runs | Tradeoff ||---|---|---|-| **Inline** | Each CameraNode/VideoNode runs its own detector | Simpler, no inter-camera dependency, higher total GPU memory |-| **Centralized GPU** | `RealtimeSkeletonInferenceNode` batches all cameras | One CUDA context, one ONNX session, batched inference, lower latency |+| **Centralized GPU** (realtime default) | `RealtimeSkeletonInferenceNode` batches all cameras | One CUDA context, one `OnnxSession`, batched `process_batch`, lower latency |+| **Inline** (per-camera fallback / posthoc) | Each CameraNode/VideoNode runs its own `Tracker` | Simpler, no inter-camera dependency, higher total GPU memory |-In centralized GPU mode:-- CameraNodes skip skeleton detection entirely+In centralized GPU mode (the realtime default):+- CameraNodes skip skeleton detection entirely (they still run ChArUco on CPU)- `RealtimeSkeletonInferenceNode` reads raw frames from all camera ring buffers-- Calls `session.predict_batch(images)` β one ONNX `session.run` for all cameras simultaneously+- Calls `tracker.process_batch(images_dict)` β one batched SkellyTracker call (one ONNX `session.run` per model) for all cameras simultaneously- TensorRT engine compilation on first run (1β3 minutes, cached)- GPU OOM recovery: catches `MemoryError`, rebuilds session (up to 3 retries)@@ -43,7 +43,7 @@ Runs alongside skeleton detection to find ChArUco board markers. Used for calibr### Detector Config Flexibility-Posthoc pipelines accept any `BaseDetectorConfig`, so they can work with CharUco (for calibration), MediaPipe (legacy skeleton), or RTMPose (current skeleton). The realtime pipeline is currently RTMPose-focused.+Posthoc pipelines build a SkellyTracker `Tracker` from a `TrackerConfig` / `DetectionStageConfig`, so they can work with ChArUco (for calibration), MediaPipe, or RTMPose β MediaPipe and RTMPose are both first-class skeleton detectors. The realtime pipeline defaults to RTMPose but can also run MediaPipe (in per-camera mode).## Skeleton Filtering Pipeline (Realtime)@@ -113,32 +113,35 @@ The `Triangulator` (`core/tasks/triangulation/triangulator.py`, ~578 lines) is a## Posthoc Mocap Task-Orchestrated by `posthoc_mocap_task.py` (~150 lines):+Orchestrated by `run_posthoc_mocap_aggregator_task()` in `posthoc_mocap_task.py`:-1. Receives collected observations from all VideoNodes-2. Builds `BaseRecorder` per camera (for saving per-camera detection data)-3. Validates observations are `RTMPoseObservation` or `MediapipeObservation`-4. Loads calibration TOML (most recent or specified path), copies into recording folder-5. Calls `skeleton_from_mediapipe_observation_recorders()` for triangulated 3D skeleton-6. Saves `tracker_schema.json` alongside outputs (keypoint names, connections)-7. Optionally triggers Blender export+1. Receives `frame_observations` β a per-frame list of `{camera_id: Observation}` collected from all VideoNodes (unified SkellyTracker `Observation`s)+2. Builds an `ObservationBuffer` per camera and accumulates each camera's observations+3. Resolves the calibration TOML (explicit path wins; otherwise the most-recent successful calibration) and copies it into the recording folder+4. Calls `skeleton_from_mediapipe_observation_recorders(detector=β¦, observation_recorders=β¦, β¦)` to triangulate the 3D skeleton into `output_data/`+5. Writes `tracker_schema.json` from the active `TrackerDefinition` (e.g. `RTMPOSE_WHOLEBODY_DEFINITION`)+6. Optionally triggers Blender export## Output Artifacts-After mocap processing, a recording folder contains:--| File | Content |-|---|---|-| `mediapipe_body_3d_xyz.npy` | Body keypoints in 3D (num_frames Γ num_keypoints Γ 3) |-| `mediapipe_right_hand_right_hand.npy` | Right hand keypoints |-| `mediapipe_left_hand_left_hand.npy` | Left hand keypoints |-| `mediapipe_face_3d_xyz.npy` | Face mesh keypoints |-| `mediapipe_body_total_body_center_of_mass.npy` | Whole-body center of mass trajectory |-| `mediapipe_body_segment_center_of_mass.npy` | Per-segment center of mass trajectories |-| `{name}_data.parquet` | Primary mocap data store (all data in one file) |-| `tracker_schema.json` | Keypoint names and skeleton connections |-| `{name}_calibration.toml` | Calibration used for this recording |-| `{name}.blend` | Blender export (if enabled) |+After mocap processing, results are written under the recording folder:++```text+recording_folder/+βββ synchronized_videos/ Input camera videos+βββ annotated_videos/ Videos with detected 2D keypoints drawn on+βββ output_data/ Reconstructed + post-processed 3D data+β βββ *.npy 3D keypoint arrays (frames Γ keypoints Γ 3), CoM, etc.+β βββ *.csv+β βββ *.parquet Primary tabular mocap data store+β βββ per_camera_weights.npy+βββ tracker_schema.json Keypoint names + connections (from the TrackerDefinition)+βββ <calibration>.toml Calibration used for this recording (copied in)+βββ <name>.blend Blender export (if enabled)+```++For the end-user walkthrough that produces these, see the+[Post-Hoc Motion Capture guide](/docs/guides/posthoc-mocap).## Blender Export@@ -162,7 +165,7 @@ Since the posthoc pipeline was ported from V1 while the realtime pipeline was bu|---|---|---|| Filtering | One Euro + velocity gate + rigid-body correction | V1 filtering pipeline (being updated) || Triangulation | DLT with subset-ensemble outlier rejection | DLT with configurable outlier rejection |-| Detector | RTMPose (ONNX) | RTMPose or MediaPipe (configurable) |+| Detector | RTMPose (default); MediaPipe in per-camera mode | RTMPose or MediaPipe (configurable) || Output format | WebSocket streaming | .npy + .parquet files |-These gaps are known and will be closed as the posthoc pipeline is updated to match the realtime pipeline's filtering and triangulation approach.+These gaps are known and will be closed as the posthoc pipeline is updated to match the realtime pipeline's filtering and triangulation approach. See the [Post-Hoc Motion Capture guide](/docs/guides/posthoc-mocap) for the current user-facing limitations (e.g. the **3D Reconstruction** filter settings β Point Gate, One Euro, FABRIK β are not yet passed into posthoc processing).diff --git a/freemocap-docs/docs/architecture/backend-overview.mdx b/freemocap-docs/docs/architecture/backend-overview.mdxindex 55343fb3..4310a97e 100644--- a/freemocap-docs/docs/architecture/backend-overview.mdx+++ b/freemocap-docs/docs/architecture/backend-overview.mdx@@ -29,7 +29,10 @@ skellycam/ β Camera domainβββ skellycam-rust/ Rust rewrite (in development)skellytracker/ β Pose estimation domain- (RTMPose, CharUco detection)+βββ skellytracker/ Unified Tracker β Session β Detector API+β (MediaPipe, RTMPose, YOLOX, ArUco, ChArUco;+β batched multi-camera inference)+βββ skellytracker-docs/ SkellyTracker documentation siteskellydocs/ β Shared Docusaurus theme (npm package)(@freemocap/skellydocs)@@ -47,7 +50,7 @@ graph TDendsubgraph Track["skellytracker/"]- Tracker["Pose Estimation<br/>RTMPose, CharUco"]+ Tracker["Pose Estimation<br/>unified Tracker API<br/>+ batched inference"]endBackend -->|"imports"| SkellyBackend@@ -58,6 +61,8 @@ graph TD<Tip shortInfo="SkellyCam has its own documentation at freemocap.github.io/skellycam. SkellyCam owns camera detection, configuration, shared memory ring buffers, and recording to disk. Freemocap imports SkellyCam as a library and builds pipelines on top of it." />+<Tip shortInfo="SkellyTracker has its own documentation at freemocap.github.io/skellytracker. It owns pose estimation β the unified Tracker β Session β Detector API, the detectors (MediaPipe, RTMPose, YOLOX, ArUco, ChArUco), and batched multi-camera inference. Freemocap imports it as a library; see the Tracking Integration page." />+## FastAPI ApplicationThe backend is a FastAPI app created by `create_fastapi_app()` in `app/app.py` and served by Uvicorn on port **53117**.@@ -142,6 +147,7 @@ This split is deliberate: commands are request/response and fit REST naturally.The following pages dive into each subsystem in detail:- [Pipeline Architecture](/docs/architecture/backend-pipeline-architecture) β Realtime and posthoc pipelines, node topology, phases+- [Tracking Integration](/docs/architecture/tracking-integration) β How FreeMoCap builds and drives SkellyTracker (batched inference, tracker schemas)- [WebSocket Server](/docs/architecture/backend-websocket-server) β The three concurrent asyncio tasks, backpressure, serialization- [Calibration](/docs/architecture/backend-calibration) β Anipose solver, calibration state tracker, camera models- [Mocap & Skeleton Processing](/docs/architecture/backend-mocap) β Pose detection, skeleton filtering, triangulation, Blender export@@ -152,4 +158,4 @@ The following pages dive into each subsystem in detail:- **SkellyCam architecture**: [freemocap.github.io/skellycam/docs/technical/architecture](https://freemocap.github.io/skellycam/docs/technical/architecture) β Camera detection, shared memory ring buffers, recording, frame synchronization- **SkellyCam WebSocket protocol**: [freemocap.github.io/skellycam/docs/technical/websocket-protocol](https://freemocap.github.io/skellycam/docs/technical/websocket-protocol)-- **SkellyTracker**: Pose estimation (RTMPose, CharUco) β integrated as a library dependency+- **SkellyTracker**: [freemocap.github.io/skellytracker](https://freemocap.github.io/skellytracker/) β the unified Tracker β Session β Detector API, detectors, sessions, and batched multi-camera inference. Integrated as a library dependency; see [Tracking Integration](/docs/architecture/tracking-integration).diff --git a/freemocap-docs/docs/architecture/backend-pipeline-architecture.mdx b/freemocap-docs/docs/architecture/backend-pipeline-architecture.mdxindex 73be156f..48d83aaf 100644--- a/freemocap-docs/docs/architecture/backend-pipeline-architecture.mdx+++ b/freemocap-docs/docs/architecture/backend-pipeline-architecture.mdx@@ -20,7 +20,7 @@ Pipelines are the central abstraction of the FreeMoCap backend. A pipeline takes| **Accuracy** | Best-effort (frame dropping is acceptable) | Highest possible (no drops, full dataset) || **Lifetime** | Long-lived, bound to camera group | Fire-and-forget, ends when video ends || **Dataset access** | Current frame only | Full video (forward/backward, global context) |-| **GPU inference** | Batched centralized node (optional) | Inline per video node |+| **GPU inference** | Batched centralized node (default) | Inline per video node || **Output** | WebSocket β frontend (streaming) | Files on disk β playback |```mermaid@@ -97,12 +97,12 @@ CameraGroup (shared memory ring buffers, one per camera)βΌCameraNodes (one child process per camera)β Reads from ring buffer, blocks on ProcessFrameNumberTopic- β Runs CharUcoDetector and RTMPoseDetector inline+ β Runs ChArUco detection inline (CPU); skeleton only in per-camera modeβ Publishes CameraNodeOutputMessage per frameβ- βΌ (optionally)-RealtimeSkeletonInferenceNode (centralized GPU, optional)- β Batched ONNX inference across all cameras+ βΌ (default: use_centralized_inference=True)+RealtimeSkeletonInferenceNode (centralized GPU β the default skeleton path)+ β One OnnxSession; tracker.process_batch() batches all cameras in one callβ Drains to latest frame (drops stale frames)β Publishes SkeletonInferenceResultMessageβ@@ -126,22 +126,22 @@ Each camera gets its own child process running a `CameraNode`:1. **Reads frames** from the camera's `CameraSharedMemoryRingBuffer` (shared memory, no copy)2. **Blocks on `ProcessFrameNumberTopic`** β the aggregator tells it which frame to process (up to 5ms timeout)-3. **Runs detectors inline**: `RTMPoseDetector` for skeleton, `CharucoDetector` (from skellytracker) for calibration markers+3. **Runs trackers inline** via `tracker_factory` (`core/tracking/`): a ChArUco `Tracker` (CPU) for calibration markers, and β only in per-camera mode β a skeleton `Tracker` (RTMPose or MediaPipe). Each is a SkellyTracker `Tracker`; the node calls `tracker.process_image(image, frame_number, state)`.4. **Applies image rotation** from camera metadata (if the camera is physically rotated)5. **Verifies frame_number** matches the requested frame β detects ring buffer overwrites (camera writing faster than pipeline reads)6. **Publishes `CameraNodeOutputMessage`** per frame (observations + metadata)7. **On exception**: calls `ipc.kill_everything()` β the nuclear option. A camera node crash means the pipeline can't produce valid output, so everything stops.-In **centralized GPU mode**, CameraNodes skip skeleton detection β the `RealtimeSkeletonInferenceNode` handles it separately.+**By default** (`use_centralized_inference=True`) CameraNodes run **ChArUco only** and skip skeleton detection β the centralized `RealtimeSkeletonInferenceNode` does batched skeleton inference for all cameras. Inline per-camera skeleton detection is the `use_centralized_inference=False` fallback (more GPU memory, no batching; useful for CPU-bound setups). See [Tracking Integration](/docs/architecture/tracking-integration).### RealtimeSkeletonInferenceNode (`realtime_skeleton_inference_node.py`, ~435 lines)-Optional dedicated GPU worker for batched ONNX inference. When enabled:+The **default** skeleton path (`use_centralized_inference=True`): a dedicated GPU worker doing batched inference for all cameras. See [Tracking Integration](/docs/architecture/tracking-integration) for how the tracker is built.-1. **One CUDA context, one `RTMPoseSession`** β avoids per-node GPU context switching overhead+1. **One CUDA context, one `OnnxSession` + `Tracker`** (built via `tracker_factory`) β avoids per-node GPU context switching overhead2. **Subscribes to `ProcessFrameNumberTopic`**, drains to the latest frame (drops stale frames when GPU falls behind)3. **Reads images directly** from per-camera ring buffers (read-only, no copy)-4. **Calls `session.predict_batch(images)`** β one ONNX `session.run` per multi-camera frame+4. **Calls `tracker.process_batch(images_dict)`** β one batched SkellyTracker call (one ONNX `session.run` per model) for all cameras at once5. **Publishes `SkeletonInferenceResultMessage`** β per-camera skeleton observations keyed by frame_number6. **GPU OOM recovery**: catches `MemoryError`, rebuilds session (up to 3 retries), skips the affected frame7. **TensorRT engine compilation** available when configured with execution provider `"trt"` (1β3 minutes on first run, cached on subsequent runs). The default execution provider is `"cuda"`.@@ -200,7 +200,7 @@ Output files on disk β Playback via REST APIEach video gets a child process:1. **Reads frames** via OpenCV `cv2.VideoCapture` (sequential, no frame dropping)-2. **Creates detector** from config (any `BaseDetectorConfig` β charuco, mediapipe, RTMPose)+2. **Builds a SkellyTracker `Tracker`** from its `TrackerConfig` / `DetectionStageConfig` (ChArUco, MediaPipe, or RTMPose) and calls `tracker.process_image()` per frame3. **Publishes `VideoNodeOutputMessage`** per frame (detection observations)4. **Annotated video output**: layers detection annotations on frames- Tries H.264 ("avc1") encoder first, falls back to mp4vdiff --git a/freemocap-docs/docs/architecture/backend-recording-structure.mdx b/freemocap-docs/docs/architecture/backend-recording-structure.mdxindex 6aaeb6de..18ac40fc 100644--- a/freemocap-docs/docs/architecture/backend-recording-structure.mdx+++ b/freemocap-docs/docs/architecture/backend-recording-structure.mdx@@ -24,16 +24,10 @@ Every recording session β whether calibration, mocap, or both β produces a sβ βββ annotated/ # Videos with detection overlaysβ βββ camera_0_annotated.mp4β βββ ...- βββ output/ # Per-stage processed artifacts (canonical)- β βββ mediapipe_body_3d_xyz.npy- β βββ mediapipe_face_3d_xyz.npy- β βββ mediapipe_right_hand_right_hand.npy- β βββ mediapipe_left_hand_left_hand.npy- β βββ mediapipe_body_total_body_center_of_mass.npy- β βββ mediapipe_body_segment_center_of_mass.npy- β βββ calibration_observations.json- β βββ ...- β (legacy: output_data/ also supported for backward compatibility)+ βββ output/ # Per-stage processed artifacts+ β βββ *.npy # 3D keypoints, center-of-mass, etc.+ β βββ *.csv+ β βββ *.parquetβββ logs/ # Per-recording log filesβββ {name}_calibration.toml # Authoritative calibration dataβββ {name}_recording_info.json # Camera configs + recording type tags@@ -41,6 +35,10 @@ Every recording session β whether calibration, mocap, or both β produces a sβββ {name}.blend # Blender export (optional)```+:::note Current runtime layout+The synchronized camera videos are recorded by [SkellyCam](https://freemocap.github.io/skellycam/). The recording and post-hoc pipelines currently still write the **legacy** layout β `synchronized_videos/`, `annotated_videos/`, `output_data/`, and `{recording_name}_camera_calibration.toml` (see `system/default_paths.py` and the [Post-Hoc Motion Capture guide](/docs/guides/posthoc-mocap)). `RecordingStructure.validate_layout()` accepts **both** layouts and reports which markers are present; the `videos/β¦` + `output/` layout above is the migration target.+:::+## RecordingStructure ModelThe `RecordingStructure` Pydantic model (`system/recording_structure/recording_structure.py`, ~178 lines) provides computed properties for all canonical paths:@@ -50,23 +48,25 @@ class RecordingStructure(BaseModel):base_directory: Pathrecording_name: str- # Computed properties+ # Computed properties (all @computed_field)@propertydef full_path(self) -> Path: ...@property- def synchronized_videos_dir(self) -> Path: ...+ def videos_synchronized_dir(self) -> Path: ... # {full}/videos/synchronized+ @property+ def videos_annotated_dir(self) -> Path: ... # {full}/videos/annotated@property- def annotated_videos_dir(self) -> Path: ...+ def output_dir(self) -> Path: ... # {full}/output@property- def output_dir(self) -> Path: ...+ def logs_dir(self) -> Path: ...@propertydef calibration_toml_path(self) -> Path: ...@property+ def recording_info_path(self) -> Path: ...+ @propertydef data_parquet_path(self) -> Path: ...@propertydef blend_path(self) -> Path: ...- @property- def recording_info_path(self) -> Path: ...````validate_layout()` checks both canonical (`output/`) and legacy (`output_data/`) layouts, providing backward compatibility with recordings from older versions.diff --git a/freemocap-docs/docs/architecture/backend-websocket-server.mdx b/freemocap-docs/docs/architecture/backend-websocket-server.mdxindex f9ec2569..18eff60e 100644--- a/freemocap-docs/docs/architecture/backend-websocket-server.mdx+++ b/freemocap-docs/docs/architecture/backend-websocket-server.mdx@@ -121,7 +121,7 @@ A send lock (`asyncio.Lock`) prevents concurrent writes to the same WebSocket co## Tracker Schemas-On connection, the server sends `TrackerSchemasMessage` containing `RTMPOSE_WHOLEBODY_DEFINITION`. This tells the frontend:+On connection, the server sends `TrackerSchemasMessage` containing every active tracker's `TrackerDefinition` β e.g. `rtmpose_wholebody`, `mediapipe_wholebody`, and the canonical body/hand schemas (`collect_active_tracker_schemas()`). This tells the frontend:- What keypoints exist (names and indices)- How keypoints connect (skeleton lines to draw)- Without hardcoding any skeleton topology in the frontenddiff --git a/freemocap-docs/docs/architecture/old-vs-new-comparison.mdx b/freemocap-docs/docs/architecture/old-vs-new-comparison.mdxdeleted file mode 100644index 339540e6..00000000--- a/freemocap-docs/docs/architecture/old-vs-new-comparison.mdx+++ /dev/null@@ -1,135 +0,0 @@-----sidebar_position: 14-title: Old vs New UI Comparison------import { AiGeneratedBanner, Tip } from '@freemocap/skellydocs';--<AiGeneratedBanner />--# Old vs New UI Comparison--The new `freemocap-ui` is a ground-up rewrite of `freemocap-ui-old`. The conceptual architecture is the same (Redux slices, WebSocket + REST, `HashRouter`, `react-resizable-panels`), but the implementation shed MUI and adopted a custom CSS utility-class system.--This page is a reference for developers who worked on the old UI and need to understand what changed, what's missing, and how to port features.--## What Changed--### Styling: MUI β Custom CSS--| Concern | Old UI | New UI |-|---|---|---|-| Component library | MUI v5 (`@mui/material`) | Custom components in `src/components/ui-components/` |-| Theming | `ThemeProvider` + `paperbase-theme.ts` (~200 lines of MUI overrides) | CSS custom properties in `color.css` (no JS theme provider) |-| Styling method | MUI `sx` prop, Tailwind directives | Hand-rolled utility classes (`flex`, `gap-2`, `bg-darkgray`, `br-2`) |-| Dark/light mode | Runtime theme toggle | CSS custom property swap (light theme not yet implemented) |-| Scrollbar styling | Per-component `sx` | Global `::-webkit-scrollbar` rules in `App.css` |--The philosophy shift: styles moved from JavaScript to CSS. When porting an old component, replace:-- MUI `sx={{ ... }}` props β utility classes in `className`-- MUI components (`<Box>`, `<Stack>`, `<Typography>`) β plain `<div>`/`<span>` with utility classes-- `ThemeProvider` theme access β CSS custom properties (available everywhere, no hook needed)--### Routing--| Old UI | New UI |-|---|---|-| `/` β `/welcome` | `/` β `/streaming` |-| `/welcome` (landing page) | **Removed** |-| `/streaming` (live cameras) | `/streaming` (same) |-| `/browse` (recording list) | `/browse` β redirect to `/playback` |-| `/playback` (synced video) | `/playback` (same) |-| `/active-recording` (status) | `/active-recording` (same) |--### Layout--| Old UI | New UI |-|---|---|-| Sidebar sections drag-reorderable via `@dnd-kit` | Sidebar sections are static |-| Bottom panel: tabbed (framerate + pipeline tabs) | Bottom panel: framerate left, log terminal right (streaming/active-recording); log terminal only (playback) |-| Bottom panel always visible | Bottom panel collapsed by default |--### Redux Slices--| Old UI (14 slices) | New UI (13 slices) |-|---|---|-| `pupilLabs` | **Removed** |-| All other 13 slices | Same structure, same names (plus `theme` slice exists on disk but is not registered in the store) |--The `locale` slice exists in both but the keyboard shortcut toggle (`Ctrl+Shift+L`) is commented out in the new UI. Language switching still works through the `LanguageSwitcher` component dropdown.--## Features Removed--### Pupil Labs Integration-The `pupil-labs` Redux slice and `PupilLabsPanel` component were removed. Pupil Labs is an eye-tracking hardware/software system that could optionally feed gaze data into the mocap pipeline. If this feature needs to return, the old implementation is in `freemocap-ui-old/src/store/slices/pupil-labs/` and `freemocap-ui-old/src/components/control-panels/pupil-labs-panel/`.--### Welcome Page-The `/welcome` route with logo, "Connect to Cameras" CTA, language switcher, telemetry toggle, and external links was removed. The root now redirects directly to `/streaming`. A `WelcomeModal` component exists in the new UI (shown on first launch), but it's a modal, not a full page.--### Drag-and-Drop Sidebar Reordering-The old UI used `@dnd-kit/core` to let users reorder sidebar sections by dragging. The new UI has a fixed section order. The old implementation is in `freemocap-ui-old/src/layout/content/SidePanelContent.tsx`.--### Dedicated Recording Browser Page-The old UI had a `/browse` route with a full-page recording browser. In the new UI, the recording browser is a sidebar section (`RecordingBrowserSection`) visible on the Playback and Active Recording tabs.--## Potentially Vestigial Code--### videos Redux Slice-The `videos` slice in `src/store/slices/videos/` tracks video folder selection and file browsing. In practice, playback now uses `playbackData` slice (cached bundles) and `PlaybackContext` (loaded videos, timestamps, sources). The `videos` slice appears to have no active consumers β but verify before removing.--### locale Slice Toggle-The `locale` slice has `localeToggled` action for cycling between current and previous locale via `Ctrl+Shift+L`. This is wired in `useKeyboardShortcuts.ts` but the menu action dispatch in `useMenuActions.ts` has the toggle commented out. The slice itself is still used for `localeChanged` (normal switching via dropdown).--### Worker File Duplication-Files like `frame-decode.worker.ts` and `offscreen-renderer.worker.ts` exist in both old and new UIs. The new UI's versions are the canonical ones. The old UI's copies can be ignored.--## Migration Guide: Porting an Old Feature to the New UI--### Step 1: Copy the logic, not the components-The Redux slices and thunks are architecturally identical between old and new. Start by ensuring the slice exists in the new UI. If it doesn't (like `pupil-labs`), copy the slice directory and add it to `store.ts`.--### Step 2: Rewrite the component shell-Replace MUI components with plain HTML elements and utility classes:--```-Old: <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, p: 2 }}>-New: <div className="flex flex-col gap-2 p-2">--Old: <Typography variant="h6">Title</Typography>-New: <h3>Title</h3> (styling via parent or utility class)--Old: <Button variant="contained" color="primary">Click</Button>-New: <ButtonSm text="Click" onClick={handler} /> (or a custom button component)-```--### Step 3: Replace MUI icons-The old UI used MUI's `@mui/icons-material`. The new UI uses custom SVG icons referenced as CSS classes:--```-Old: <SettingsIcon />-New: <div className="icon settings-icon" />-```--Check `src/assets/icons/` for available icons and `src/styles/icons.css` for their class names.--### Step 4: Convert styles from `sx` to utility classes-MUI's `sx` prop maps to CSS properties. Find the equivalent utility class:--| MUI `sx` | New utility class |-|---|---|-| `display: 'flex'` | `flex` |-| `flexDirection: 'column'` | `flex-col` |-| `gap: '8px'` | `gap-2` (rough mapping) |-| `padding: '8px'` | `p-2` |-| `backgroundColor: '...'` | `bg-dark`, `bg-darkgray`, `bg-primary`, etc. |-| `borderRadius: '8px'` | `br-2` |-| `overflow: 'hidden'` | `overflow-hidden` |-| Colors referencing theme | Semantic color utility classes (`text-success`, `bg-danger-surface`, etc.) |--If a utility class doesn't exist for what you need, add it following the existing naming convention in `App.css`.--### Step 5: Decide: Context, Redux, or ref?-New state in a ported feature needs a home. Follow the decision tree:-- Survives navigation? β Redux slice-- Only needed by a subtree? β React Context-- Changes at frame rate? β `useRef`diff --git a/freemocap-docs/docs/architecture/overview.mdx b/freemocap-docs/docs/architecture/overview.mdxindex 357f0d9f..91afa55b 100644--- a/freemocap-docs/docs/architecture/overview.mdx+++ b/freemocap-docs/docs/architecture/overview.mdx@@ -69,12 +69,12 @@ freemocap/ββββ freemocap-docs/ This documentation site (Docusaurus v3 + SkellyDocs)β-βββ shared/ Shared assets (charuco boards, logos, macOS packaging)-β-βββ freemocap-ui-old/ Previous MUI-based frontend (superseded)+βββ shared/ Shared assets (charuco boards, logos, macOS packaging)```-<Tip shortInfo="The old UI (freemocap-ui-old/) still exists in the repo but is no longer developed. See the Old vs New Comparison page for what changed." />+FreeMoCap builds on two sibling projects, each with its own docs site:+[**SkellyCam**](https://freemocap.github.io/skellycam/) (the camera backend) and+[**SkellyTracker**](https://freemocap.github.io/skellytracker/) (the pose-estimation backend).## Communication Flow@@ -126,7 +126,7 @@ Every decision β backend selection, config flag, feature toggle β should hav### Zero Backwards Compatibility (Aspirational)-New code targets the current architecture without shims or migration layers. However, the project retains some legacy compatibility: the `RecordingStructure` model supports both canonical and legacy recording layouts, the old MUI-based UI still exists in `freemocap-ui-old/` as a reference, and some pipeline configs offer legacy operating modes (e.g., inline vs centralized GPU inference). Legacy support is pragmatic β it keeps existing recordings usable while the system evolves.+New code targets the current architecture without shims or migration layers. However, the project retains some legacy compatibility: the `RecordingStructure` model supports both canonical and legacy recording layouts, and some pipeline configs offer legacy operating modes (e.g., inline per-camera skeleton detection vs the default centralized GPU inference). Legacy support is pragmatic β it keeps existing recordings usable while the system evolves.## Quick Referencediff --git a/freemocap-docs/docs/architecture/tracking-integration.mdx b/freemocap-docs/docs/architecture/tracking-integration.mdxnew file mode 100644index 00000000..e659c082--- /dev/null+++ b/freemocap-docs/docs/architecture/tracking-integration.mdx@@ -0,0 +1,101 @@+---+sidebar_position: 14+title: Tracking Integration (SkellyTracker)+---++import { AiGeneratedBanner, Tip } from '@freemocap/skellydocs';++<AiGeneratedBanner />++# Tracking Integration (SkellyTracker)++FreeMoCap does not implement pose estimation itself β it delegates that to+[**SkellyTracker**](https://freemocap.github.io/skellytracker/), which exposes a+unified `Tracker β Session β Detector` API and owns **batched multi-camera+inference**. This page documents the seam: how the FreeMoCap backend builds and+drives SkellyTracker `Tracker`s.++<Tip shortInfo="SkellyTracker has its own docs at freemocap.github.io/skellytracker. It owns the detector implementations (MediaPipe, RTMPose, YOLOX, ArUco, ChArUco), the ONNX/CoreML sessions, temporal smoothing, and the batched process_batch() inference call. FreeMoCap orchestrates it across cameras and consumes the resulting Observations." />++## The bridge: `tracker_factory.py`++Every `Tracker.create()` call lives in one module β+`core/tracking/tracker_factory.py` β so that detector-registry import side effects,+config construction, and session creation happen in exactly one place. Other+modules import these builders rather than constructing trackers directly.++| Builder | Backend session | Produces |+|---|---|---|+| `build_charuco_tracker(board_def)` | `CpuSession` | ChArUco board detector (calibration markers) |+| `build_skeleton_onnx_session(batch_size, model_name, β¦)` | `OnnxSession` | Shared RTMPose + YOLOX session (batch size = camera count) |+| `build_skeleton_tracker(onnx_session, β¦)` | (uses the OnnxSession above) | Body-pose `Tracker` (YOLOX person crop β RTMPose) with `BBoxPolicyConfig` |+| `build_mediapipe_tracker(β¦)` | `MediaPipeSession` | MediaPipe body + hands + face `Tracker` |++Each builder returns a SkellyTracker `Tracker` (and, where relevant, the+`Session` so the caller can `close()` it). Per frame, FreeMoCap calls+`tracker.process_image(image, frame_number, state)` (single) or+`tracker.process_batch(images_dict, β¦)` (multi-camera) and receives an+`Observation` + updated `TrackerState`.++## Two inference modes++Skeleton inference runs in one of two modes, selected by+`RealtimePipelineConfig.use_centralized_inference` (**default: `True`**).++```mermaid+flowchart TB+ subgraph Central["Centralized (default) β use_centralized_inference=True"]+ direction TB+ RB["per-camera ring buffers"] --> SIN["RealtimeSkeletonInferenceNode<br/>one OnnxSession"]+ SIN -->|"tracker.process_batch({cam: image})"| BATCH["one batched GPU call<br/>for all cameras"]+ CNc["CameraNodes<br/>(ChArUco only, CPU)"]+ end+ subgraph PerCam["Per-camera fallback β use_centralized_inference=False"]+ direction TB+ CNp["each CameraNode builds its own skeleton Tracker<br/>tracker.process_image(...)"]+ end+```++- **Centralized (default).** The dedicated `RealtimeSkeletonInferenceNode` owns a+ single `OnnxSession` and calls `tracker.process_batch(images_dict)` β **one+ batched GPU call per frame for all cameras**. In this mode `CameraNode`s run+ **ChArUco detection only** (CPU) and skip skeleton inference.+- **Per-camera (fallback).** With `use_centralized_inference=False`, each+ `CameraNode` builds its own skeleton `Tracker` and calls `process_image()`+ itself. This uses more GPU memory and has no batching benefit β it's mainly+ useful for CPU-bound setups or when a single dedicated GPU worker isn't+ desired.++See [Pipeline Architecture](./backend-pipeline-architecture.mdx) for how these+nodes fit into the realtime pipeline, and+[SkellyTracker's multi-camera batching guide](https://freemocap.github.io/skellytracker/guides/multi-camera-batching)+for how `process_batch` works internally.++## Tracker schemas++So the frontend can render keypoints and skeleton connections without hardcoding+any tracker's layout, the backend sends a **tracker-schema handshake** on connect.+Each active tracker is described by a `TrackerDefinition`+(`core/tracking/tracker_definitions.py` β e.g. `RTMPOSE_WHOLEBODY_DEFINITION`,+`MEDIAPIPE_WHOLEBODY_DEFINITION`), carrying its `tracked_points` and `connections`.+These are sent as a `TrackerSchemasMessage` over the WebSocket. See the+[API Boundary](./api-boundary.mdx) page for the message shape.++## Who owns what++| Concern | Owner |+|---|---|+| Detector implementations (MediaPipe, RTMPose, YOLOX, ArUco, ChArUco) | SkellyTracker |+| ONNX / CoreML sessions, execution-provider selection | SkellyTracker |+| Batched multi-camera inference (`process_batch` / `run_batched`) | SkellyTracker |+| Temporal smoothing (bbox policy, keypoint filtering) | SkellyTracker |+| Building/configuring trackers for FreeMoCap's needs (`tracker_factory`) | FreeMoCap |+| Running trackers across camera/video nodes; collecting `Observation`s | FreeMoCap |+| Triangulation, skeleton filtering, calibration, export | FreeMoCap |++## Cross-references++- **SkellyTracker docs**: [freemocap.github.io/skellytracker](https://freemocap.github.io/skellytracker/)+ β the `Tracker β Session β Detector` API, detectors, sessions, and batched inference.+- [Pipeline Architecture](./backend-pipeline-architecture.mdx) β realtime/posthoc node topology.+- [Mocap & Skeleton Processing](./backend-mocap.mdx) β what happens to the `Observation`s downstream.diff --git a/freemocap-docs/docs/development/building.mdx b/freemocap-docs/docs/development/building.mdxindex ce9458f1..7ff4c7b7 100644--- a/freemocap-docs/docs/development/building.mdx+++ b/freemocap-docs/docs/development/building.mdx@@ -75,14 +75,14 @@ Build and deployment workflows live in `.github/workflows/`:| Workflow | Purpose ||---|---|-| `build-installers.yml` | Builds platform-specific installers on push to main |+| `build-installers-pyinstaller.yml` | Builds platform-specific installers on push to main || `deploy-docs.yml` | Builds and deploys this documentation site to GitHub Pages || `test.yml` | Runs backend + frontend tests on PR |## Versioning-- **Backend version**: `v1.4.7` (in `freemocap/__init__.py`), managed by `bumpver`+- **Backend version**: `v2.0.0-alpha.11` (in `freemocap/__init__.py`), managed by `bumpver`- **Frontend version**: `2.0.0-alpha.1` (in `freemocap-ui/package.json`)- **Electron updater**: `electron-updater` handles auto-updates for installed releases-<Tip shortInfo="The version numbers are currently out of sync between the Python backend (v1.4.7) and the frontend (v2.0.0-alpha.1). This reflects the v2 rewrite of the frontend while the backend is being incrementally updated." />+<Tip shortInfo="Both the Python backend (v2.0.0-alpha.x) and the frontend (v2.0.0-alpha.x) are on the v2 alpha line. The two are bumped independently, so the exact alpha/patch numbers may differ." />diff --git a/freemocap-docs/docs/guides/blender-export.mdx b/freemocap-docs/docs/guides/blender-export.mdxindex c9d89a07..99ee4a56 100644--- a/freemocap-docs/docs/guides/blender-export.mdx+++ b/freemocap-docs/docs/guides/blender-export.mdx@@ -11,10 +11,14 @@ import { AiGeneratedBanner, Tip } from '@freemocap/skellydocs';FreeMoCap can export processed mocap data directly to Blender, creating a complete 3D scene with skeleton mesh, camera frustums, and lighting.+:::note MediaPipe only (for now)+Blender export currently works with **MediaPipe** mocap output only β RTMPose 3D data does not yet have a working Blender export. See the [Post-Hoc Motion Capture guide](/docs/guides/posthoc-mocap).+:::+## Prerequisites- **Blender** installed on your system (detected automatically or specified manually)-- A **processed recording** with mocap data (all `.npy` files present in the `output/` directory)+- A **processed recording** with mocap data (all required `.npy` files present in the recording's output data directory)- The `freemocap_blender_addon` (installed automatically by the backend)## Export Flowdiff --git a/freemocap-docs/docs/guides/camera-setup.mdx b/freemocap-docs/docs/guides/camera-setup.mdxindex c61f0109..0467e034 100644--- a/freemocap-docs/docs/guides/camera-setup.mdx+++ b/freemocap-docs/docs/guides/camera-setup.mdx@@ -67,7 +67,7 @@ FreeMoCap uses a **ChArUco board** for camera calibration. You need a printed Ch- **Board files** are in `shared/charuco/` in the repository- Print on rigid material (foam board, cardboard) for flatness-- Standard board: 5Γ7 squares, with ArUco markers in the white squares+- Standard board: a letter-size ChArUco layout (configurable in the calibration settings), with ArUco markers in the white squares- The board dimensions must match the calibration config in the UI## Camera Configurationdiff --git a/freemocap-docs/docs/guides/gpu-setup.mdx b/freemocap-docs/docs/guides/gpu-setup.mdxindex 83c53e05..45988c72 100644--- a/freemocap-docs/docs/guides/gpu-setup.mdx+++ b/freemocap-docs/docs/guides/gpu-setup.mdx@@ -1,5 +1,5 @@----sidebar_position: 1+sidebar_position: 4title: GPU & ONNX Setup---@@ -9,7 +9,7 @@ import { AiGeneratedBanner, Tip } from '@freemocap/skellydocs';# GPU & ONNX Runtime Setup-FreeMoCap uses ONNX Runtime for GPU-accelerated pose detection via RTMPose. GPU acceleration significantly improves realtime pipeline throughput β especially with multiple cameras.+FreeMoCap uses ONNX Runtime for GPU-accelerated pose detection via RTMPose. GPU acceleration significantly improves realtime pipeline throughput β especially with multiple cameras. The models and execution-provider selection are implemented in [SkellyTracker](https://freemocap.github.io/skellytracker/guides/gpu-setup); FreeMoCap configures them through the pipeline.## How GPU Detection Works@@ -51,7 +51,7 @@ When `use_centralized_inference=True`, a single `RealtimeSkeletonInferenceNode`### Inline Mode (Per-Camera)-When `use_centralized_inference=False`, each `CameraNode` runs its own `RTMPoseDetector` inline. This is the legacy path and uses more GPU memory but has no inter-camera dependency.+When `use_centralized_inference=False`, each `CameraNode` builds its own skeleton `Tracker` (via `tracker_factory`) and runs it inline. This per-camera fallback uses more GPU memory and gives up batching, but has no inter-camera dependency β useful for CPU-bound or single-camera setups.## GPU OOM Recoverydiff --git a/freemocap-docs/docs/guides/posthoc-mocap.mdx b/freemocap-docs/docs/guides/posthoc-mocap.mdxindex 1ad7f077..ef33f932 100644--- a/freemocap-docs/docs/guides/posthoc-mocap.mdx+++ b/freemocap-docs/docs/guides/posthoc-mocap.mdx@@ -1,8 +1,17 @@+---+title: Post-Hoc Motion Capture+sidebar_position: 1+---++import { AiGeneratedBanner } from '@freemocap/skellydocs';++<AiGeneratedBanner generationType="human-generated" />+# FreeMoCap Alpha: Running Post-Hoc Motion CapturePost-hoc motion capture processes previously recorded, synchronized camera videos and reconstructs a 3D skeleton. Use this workflow when you have already recorded a session and want to processβor reprocessβit with RTMPose or MediaPipe.-> **Alpha note:** This is an early build. Expect bugs, crahses, and for this documentation and workflow to change significantly before the final release.+> **Alpha note:** This is an early build. Expect bugs, crashes, and for this documentation and workflow to change significantly before the final release.## Before you begin@@ -49,7 +58,7 @@ Under **Calibration**, confirm that the correct camera calibration is loaded. Yo> **Important:** A calibration is only valid while the cameras remain in the same positions and orientations. If any camera moved, create a new calibration before processing.-*Bug*: When selecting calibration videos, make sure to select the outer top-level recording folder (so the foldering CONTAINING the `synchronized_videos` subfolder) or else it will not find the calibration videos. We will fix this in a future update.+*Bug*: When selecting calibration videos, make sure to select the outer top-level recording folder (the folder CONTAINING the `synchronized_videos` subfolder) or else it will not find the calibration videos. We will fix this in a future update.### 4. Choose a detectordiff --git a/freemocap-docs/docs/notes/api-notes.mdx b/freemocap-docs/docs/notes/api-notes.mdxindex 52df989c..e1e2dd84 100644--- a/freemocap-docs/docs/notes/api-notes.mdx+++ b/freemocap-docs/docs/notes/api-notes.mdx@@ -4,10 +4,15 @@ title: API Notes----# API notes+import { AiGeneratedBanner } from '@freemocap/skellydocs';+<AiGeneratedBanner />-# Current API structure+# API Notes++The canonical endpoint reference is the [API Boundary](/docs/architecture/api-boundary) page; SkellyCam's `/skellycam/*` routes are documented in the [SkellyCam docs](https://freemocap.github.io/skellycam/). Below is a compact route sketch and the planned API redesign.++## Current routes (sketch)```WebSocket/websocket/connect@@ -49,7 +54,7 @@ SkellyCam```-# Planned+## Planned redesign (sketch)```WebSocketdiff --git a/freemocap-ui/electron-builder.json b/freemocap-ui/electron-builder.jsonindex 6756ab15..cdc309cd 100644--- a/freemocap-ui/electron-builder.json+++ b/freemocap-ui/electron-builder.json@@ -76,12 +76,10 @@"category": "Video","target": [{- "target": "AppImage",- "arch": ["x64", "arm64"]+ "target": "AppImage"},{- "target": "deb",- "arch": ["x64", "arm64"]+ "target": "deb"}],"artifactName": "${productName}_${version}_${arch}.${ext}",diff --git a/freemocap-ui/electron/main/ipc.ts b/freemocap-ui/electron/main/ipc.tsindex 3caa0f49..968c847f 100644--- a/freemocap-ui/electron/main/ipc.ts+++ b/freemocap-ui/electron/main/ipc.ts@@ -4,8 +4,15 @@ import {api} from './api';import superjson from 'superjson';import type {MenuBuildParams} from './services/menu-builder';import {buildApplicationMenu} from './services/menu-builder';+import {getBaseDataFolder} from './base-folder';export function setupIPC(): void {+ // Synchronous handoff so the renderer can seed its store with a real path (never '')+ // before the first React render β see preload/index.ts and useAppStore's initial state.+ ipcMain.on('get-base-data-folder-sync', (event) => {+ event.returnValue = getBaseDataFolder();+ });+ipcMain.handle('trpc', async (_event, { path, input }) => {try {const caller = api.createCaller({});diff --git a/freemocap-ui/electron/main/services/menu-builder.ts b/freemocap-ui/electron/main/services/menu-builder.tsindex 1b151c9a..a5ab6648 100644--- a/freemocap-ui/electron/main/services/menu-builder.ts+++ b/freemocap-ui/electron/main/services/menu-builder.ts@@ -24,6 +24,7 @@ export type MenuAction =| 'toggle-fullscreen'| 'toggle-locale'| 'check-for-updates'+ | 'start-tutorial'| `change-locale:${string}`;export interface LocaleEntry {@@ -41,6 +42,7 @@ export interface MenuLabels {menuLoadTestData: string;menuClearActiveRecording: string;menuHelp: string;+ menuTakeTour: string;menuDetectCameras: string;menuConnectCameras: string;menuCloseAllCameras: string;@@ -77,6 +79,7 @@ const DEFAULT_LABELS: MenuLabels = {menuLoadTestData: 'Load Test Data',menuClearActiveRecording: 'Clear Active Recording',menuHelp: 'Help',+ menuTakeTour: 'Take the Tour',menuDetectCameras: 'Detect Cameras',menuConnectCameras: 'Connect Cameras',menuCloseAllCameras: 'Close All Cameras',@@ -280,6 +283,11 @@ function buildHelpMenu(t: MenuLabels): MenuItemConstructorOptions {return {label: t.menuHelp,submenu: [+ {+ label: t.menuTakeTour,+ click: () => sendMenuAction('start-tutorial'),+ },+ { type: 'separator' },{label: t.menuDocumentation,click: () => {diff --git a/freemocap-ui/electron/preload/index.ts b/freemocap-ui/electron/preload/index.tsindex 43d769a7..467f56fa 100644--- a/freemocap-ui/electron/preload/index.ts+++ b/freemocap-ui/electron/preload/index.ts@@ -2,6 +2,11 @@ import {contextBridge, ipcRenderer} from 'electron';// Expose a simple tRPC bridge + menu action listener + menu label updatercontextBridge.exposeInMainWorld('electronAPI', {+ // Resolved synchronously (override-or-default, see electron/main/base-folder.ts) so the+ // renderer's Redux store can seed recording paths with a real value before first render β+ // never an empty string. See ipc.ts's 'get-base-data-folder-sync' handler.+ baseDataFolder: ipcRenderer.sendSync('get-base-data-folder-sync') as string,+invoke: (path: string, input?: unknown) =>ipcRenderer.invoke('trpc', { path, input }),diff --git a/freemocap-ui/src/app/AppContent.tsx b/freemocap-ui/src/app/AppContent.tsxindex 54943ebf..59d3a88c 100644--- a/freemocap-ui/src/app/AppContent.tsx+++ b/freemocap-ui/src/app/AppContent.tsx@@ -12,7 +12,7 @@ import { getLocaleDirection } from "@/i18n";import { fetchAllRecordings } from "@/store/slices/recording-status/recording-status-thunks";import { WelcomeModal } from "@/components/ui-components/WelcomeModal";import { SettingsModal } from "@/components/ui-components/SettingsModal";-import { useHydrateDataFolder } from "@/hooks/useHydrateDataFolder";+import { TutorialProvider, TourController } from "@/components/tutorial";export const AppContent = function () {const { i18n } = useTranslation();@@ -21,9 +21,6 @@ export const AppContent = function () {const [welcomeOpen, setWelcomeOpen] = React.useState(true);const [settingsOpen, setSettingsOpen] = React.useState(false);- // Seed recording directories from the configured base data folder on startup.- useHydrateDataFolder();-// The native menu's "Settingsβ¦" fires this event (see useMenuActions).React.useEffect(() => {const openSettings = () => setSettingsOpen(true);@@ -43,13 +40,16 @@ export const AppContent = function () {return (<HashRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}><AutoUpdateProvider>- <PlaybackProvider>- <BasePanelLayout onOpenWelcome={() => setWelcomeOpen(true)}>- <BaseContentRouter />- </BasePanelLayout>- <WelcomeModal open={welcomeOpen} onClose={() => setWelcomeOpen(false)} />- <SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)} />- </PlaybackProvider>+ <TutorialProvider>+ <PlaybackProvider>+ <BasePanelLayout onOpenWelcome={() => setWelcomeOpen(true)}>+ <BaseContentRouter />+ </BasePanelLayout>+ <WelcomeModal open={welcomeOpen} onClose={() => setWelcomeOpen(false)} />+ <SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)} />+ <TourController />+ </PlaybackProvider>+ </TutorialProvider><UpdateBanner /><PipelineProgressSnackbar /></AutoUpdateProvider>diff --git a/freemocap-ui/src/components/control-panels/recording-info-panel/RecordingInfoPanel.tsx b/freemocap-ui/src/components/control-panels/recording-info-panel/RecordingInfoPanel.tsxindex a3a7acad..cfacf6e1 100644--- a/freemocap-ui/src/components/control-panels/recording-info-panel/RecordingInfoPanel.tsx+++ b/freemocap-ui/src/components/control-panels/recording-info-panel/RecordingInfoPanel.tsx@@ -1,6 +1,5 @@import React, { useEffect, useState } from "react";import {- recordingInfoUpdated,startRecording,stopRecording,useAppDispatch,@@ -25,7 +24,6 @@ import {import { processMocapRecording } from "@/store/slices/mocap/mocap-thunks";import { DelayRecordingStartControl } from "./recording-subcomponents/DelayRecordingStartControl";import { MicrophoneSelector } from "@/components/control-panels/recording-info-panel/recording-subcomponents/MicrophoneSelector";-import { useElectronIPC } from "@/services/electron-ipc/electron-ipc";import { useServer } from "@/services/server/ServerContextProvider";import { getTimestampString } from "@/store/slices/recording/getTimestampString";import { StartStopRecordingButton } from "./recording-subcomponents/StartStopRecordingButton";@@ -63,7 +61,6 @@ export const RecordingInfoPanel: React.FC = () => {getTimestampString(),);- const { isElectron, api } = useElectronIPC();const { connectedCameraIds } = useServer();const { t } = useTranslation();const noCamerasConnected = connectedCameraIds.length === 0;@@ -95,29 +92,6 @@ export const RecordingInfoPanel: React.FC = () => {return () => clearTimeout(timer);}, [dispatch, pendingOperation]);- useEffect(() => {- if (- recordingInfo?.recordingDirectory?.startsWith("~") &&- isElectron &&- api- ) {- api.fileSystem.getHomeDirectory- .query()- .then((homePath: string) => {- const updatedDirectory = recordingInfo.recordingDirectory- .replace("~", homePath)- .replace(/\\/g, "/");- dispatch(- recordingInfoUpdated({ recordingDirectory: updatedDirectory }),- );- })- .catch((error: unknown) => {- console.error("Failed to get home directory:", error);- throw error;- });- }- }, [recordingInfo.recordingDirectory, isElectron, api, dispatch]);-useEffect(() => {if (countdown === null) return;if (countdown > 0) {diff --git a/freemocap-ui/src/components/control-panels/recording-info-panel/recording-subcomponents/StartStopRecordingButton.tsx b/freemocap-ui/src/components/control-panels/recording-info-panel/recording-subcomponents/StartStopRecordingButton.tsxindex fe6975c2..7cfb4e21 100644--- a/freemocap-ui/src/components/control-panels/recording-info-panel/recording-subcomponents/StartStopRecordingButton.tsx+++ b/freemocap-ui/src/components/control-panels/recording-info-panel/recording-subcomponents/StartStopRecordingButton.tsx@@ -44,6 +44,7 @@ export const StartStopRecordingButton: React.FC<StartStopButtonProps> = ({const buttonEl = (<button+ data-onboarding="recording:start-recording"className={clsx("accent text-nowrap flex flex-row flex-1 gap-1 br-1 button sm min-w-fit-content flex-inline text-left items-center full-width primary justify-center",isRecording ? "record-button-active" : isPending ? "record-button-pending" : "accent",diff --git a/freemocap-ui/src/components/tutorial/TourController.tsx b/freemocap-ui/src/components/tutorial/TourController.tsxnew file mode 100644index 00000000..59e832c1--- /dev/null+++ b/freemocap-ui/src/components/tutorial/TourController.tsx@@ -0,0 +1,132 @@+import React, {useEffect, useRef} from 'react';+import {useLocation, useNavigate} from 'react-router-dom';+import {useTranslation} from 'react-i18next';+import {useTutorial} from './TutorialContext';+import type {TourAction} from './types';+import {TourOverlay} from './TourOverlay';+import {TourSpotlight} from './TourSpotlight';+import {TourPointerBubble} from './TourPointerBubble';+import {TourPointerFallback} from './TourPointerFallback';+import '@/styles/tutorial.css';++function isSelectorVisible(selector: string): boolean {+ const el = document.querySelector(selector) as HTMLElement | null;+ if (!el || !document.body.contains(el)) return false;+ const style = window.getComputedStyle(el);+ if (style.display === 'none' || style.visibility === 'hidden') return false;+ const rect = el.getBoundingClientRect();+ return rect.width > 0 && rect.height > 0;+}++// Whether an action's visibility guards allow it to fire right now.+function actionShouldFire(a: TourAction): boolean {+ if (a.unlessVisible && isSelectorVisible(a.unlessVisible)) return false;+ if (a.onlyIfVisible && !isSelectorVisible(a.onlyIfVisible)) return false;+ return true;+}++// Mounted once (inside HashRouter). Reads the active step and renders the right+// chrome for its kind. Owns the two cross-cutting concerns a step shouldn't:+// routing to a step's declared route, and global keyboard shortcuts.+export const TourController: React.FC = () => {+ const {t} = useTranslation();+ const navigate = useNavigate();+ const location = useLocation();+ const {isTourActive, currentStep, next, back, skip} = useTutorial();++ // Navigate to the step's route when it differs from where we are. Guarding on+ // the path difference keeps this from looping on every render.+ useEffect(() => {+ if (!isTourActive || !currentStep?.route) return;+ if (location.pathname !== currentStep.route) navigate(currentStep.route);+ }, [isTourActive, currentStep?.route, location.pathname, navigate]);++ // Per-step side effects. On each step change: run the previous step's onExit+ // (e.g. close the panel it opened), then the current step's onEnter (e.g. open a+ // panel β retried because the target may mount just after a route change). Doing+ // the close here (not via the app's click-outside) makes it work for keyboard nav+ // too. When the tour ends, the last step's onExit still runs.+ const prevExitRef = useRef<TourAction | undefined>(undefined);+ useEffect(() => {+ const runOnce = (a: TourAction | undefined) => {+ if (!a || a.type !== 'click' || !actionShouldFire(a)) return;+ (document.querySelector(a.target) as HTMLElement | null)?.click();+ };++ const exit = prevExitRef.current;+ const enter = currentStep?.onEnter;+ // If the new step is just going to re-open the same panel this one opened,+ // don't close-then-reopen it (that's the flicker). onEnter's own guard keeps+ // it from double-toggling.+ const enterSupersedesExit =+ !!enter && enter.type === 'click' && !!exit && exit.type === 'click' && enter.target === exit.target;+ if (!enterSupersedesExit) runOnce(exit);++ if (!isTourActive) {+ prevExitRef.current = undefined;+ return;+ }+ prevExitRef.current = currentStep?.onExit;++ if (!enter || enter.type !== 'click') return;+ let cancelled = false;+ let tries = 0;+ const attempt = () => {+ if (cancelled || !actionShouldFire(enter)) return;+ const el = document.querySelector(enter.target) as HTMLElement | null;+ if (el) {+ el.click();+ return;+ }+ if (tries++ < 15) setTimeout(attempt, 100);+ };+ const start = setTimeout(attempt, 60);+ return () => {+ cancelled = true;+ clearTimeout(start);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isTourActive, currentStep?.id]);++ // Esc skips; β/β step back/forward during pointer steps (overlays use buttons).+ useEffect(() => {+ if (!isTourActive) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ skip();+ return;+ }+ if (currentStep?.kind === 'pointer') {+ if (e.key === 'ArrowRight') next();+ else if (e.key === 'ArrowLeft') back();+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [isTourActive, currentStep, next, back, skip]);++ if (!isTourActive || !currentStep) return null;++ if (currentStep.kind === 'pointer') {+ const target = currentStep.target;+ return (+ <>+ {target && <TourSpotlight target={target}/>}+ {target && (+ <TourPointerBubble+ target={target}+ title={t(currentStep.titleKey)}+ text={t(currentStep.textKey)}+ position={currentStep.position ?? 'pos-right'}+ offsetTop={currentStep.offsetTop}+ />+ )}+ {/* Safety net: shows the same controls if the target can't be highlighted. */}+ <TourPointerFallback/>+ </>+ );+ }++ // 'branch' | 'info'+ return <TourOverlay/>;+};diff --git a/freemocap-ui/src/components/tutorial/TourNav.tsx b/freemocap-ui/src/components/tutorial/TourNav.tsxnew file mode 100644index 00000000..2b23128f--- /dev/null+++ b/freemocap-ui/src/components/tutorial/TourNav.tsx@@ -0,0 +1,61 @@+import React from 'react';+import {useTranslation} from 'react-i18next';+import ButtonSm from '@/components/ui-components/ButtonSm';+import {useTutorial} from './TutorialContext';++// The tour's navigation row: step label + Back / Deeper / Next, plus a quiet Skip.+// Rendered directly inside the pointer bubble (and the fallback card), so the+// controls sit right where the user is reading. "Deeper" only appears on steps+// that declare a sub-tour; it's a detour that rejoins the main path.+export const TourNav: React.FC = () => {+ const {t} = useTranslation();+ const {currentStep, stepLabel, canGoBack, canGoDeeper, next, back, deeper, skip} = useTutorial();+ const docsUrl = currentStep?.docsUrl;++ return (+ <div className="tour-nav flex flex-col gap-1">+ {docsUrl && (+ <ButtonSm+ iconClass="learn-icon"+ text={t('tour.controls.docs')}+ rightSideIcon="externallink"+ textColor="text-gray"+ className="tour-docs-link"+ onClick={() => window.open(docsUrl, '_blank')}+ />+ )}+ <span className="tour-step-counter text sm text-gray">{stepLabel}</span>+ <div className="tour-nav-buttons flex flex-row items-center gap-1">+ <ButtonSm+ text={t('tour.controls.back')}+ buttonType="quaternary"+ className="flex-1 justify-center"+ onClick={back}+ disabled={!canGoBack}+ />+ {canGoDeeper && (+ <ButtonSm+ text={t('tour.controls.deeper')}+ buttonType="secondary"+ textColor="text-white"+ className="flex-1 justify-center"+ onClick={deeper}+ />+ )}+ <ButtonSm+ text={t('tour.controls.next')}+ textColor="text-white"+ className="primary accent flex-1 justify-center"+ onClick={next}+ />+ </div>+ <ButtonSm+ text={t('tour.controls.skip')}+ buttonType="tertiary"+ textColor="text-gray"+ className="tour-skip-link"+ onClick={skip}+ />+ </div>+ );+};diff --git a/freemocap-ui/src/components/tutorial/TourOverlay.tsx b/freemocap-ui/src/components/tutorial/TourOverlay.tsxnew file mode 100644index 00000000..70f05b6d--- /dev/null+++ b/freemocap-ui/src/components/tutorial/TourOverlay.tsx@@ -0,0 +1,71 @@+import React from 'react';+import {useTranslation} from 'react-i18next';+import ButtonSm from '@/components/ui-components/ButtonSm';+import ButtonCard from '@/components/ui-components/ButtonCard';+import IconButton from '@/components/ui-components/IconButton';+import {useTutorial} from './TutorialContext';++// Centered modal for 'branch' and 'info' steps. Reuses the .splash-overlay+// backdrop for visual consistency with WelcomeModal, but uses its own compact+// modal box (the .splash-modal box is fixed to the two-column welcome layout).+// A single choice renders as one primary button (intro/finish); 2+ choices render+// as ButtonCards, matching the welcome screen's direction picker.+export const TourOverlay: React.FC = () => {+ const {t} = useTranslation();+ const {currentStep, choose, skip} = useTutorial();++ if (!currentStep || (currentStep.kind !== 'branch' && currentStep.kind !== 'info')) return null;++ const choices = currentStep.choices ?? [];+ const isSingle = choices.length === 1;++ return (+ <div+ className="splash-overlay reveal fadeIn tour-overlay"+ style={{position: 'fixed', inset: 0, zIndex: 340}}+ onClick={skip}+ >+ <div+ className="tour-modal bg-dark border-1 border-black br-2 flex flex-col p-1 reveal fade"+ style={{width: 460, maxWidth: '90vw'}}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="bg-middark br-1 flex flex-col gap-3 p-3 pos-rel">+ <IconButton+ icon="close-icon"+ onClick={skip}+ className="pos-abs top-2 right-2 tertiary"+ />++ <h1 className="title flex flex-col gap-1">+ <span className="text-white">{t(currentStep.titleKey)}</span>+ </h1>++ <p className="text md text-gray" style={{whiteSpace: 'pre-line'}}>+ {t(currentStep.textKey)}+ </p>++ {isSingle ? (+ <ButtonSm+ text={t(choices[0].labelKey)}+ textColor="text-white"+ className="primary accent full-width justify-center"+ onClick={() => choose(choices[0].id)}+ />+ ) : (+ <div className="flex gap-2 mt-2">+ {choices.map((c) => (+ <ButtonCard+ key={c.id}+ text={t(c.labelKey)}+ iconClass={`${c.iconClass ?? ''} icon-size-42`}+ onClick={() => choose(c.id)}+ />+ ))}+ </div>+ )}+ </div>+ </div>+ </div>+ );+};diff --git a/freemocap-ui/src/components/tutorial/TourPointerBubble.tsx b/freemocap-ui/src/components/tutorial/TourPointerBubble.tsxnew file mode 100644index 00000000..cbd27564--- /dev/null+++ b/freemocap-ui/src/components/tutorial/TourPointerBubble.tsx@@ -0,0 +1,54 @@+import React from 'react';+import clsx from 'clsx';+import {FloatingOnboarding} from '@/hooks/floatingOnboarding';+import {TourNav} from './TourNav';+import type {TourPosition} from './types';++// The contextual callout for a pointer step. It reuses the exact class recipe+// from PromptTooltip so it inherits the tooltip chrome from styles/tooltips.css:+// - .prompt-tooltip-container β pointer-events:auto + fixed width+// - .tooltip-container + .pos-* β the arrow triangle and offset toward the target+// The Back/Next/Skip controls live right here on the bubble (via TourNav) so they+// sit in the user's eyeline next to the target β not pinned to the screen edge.+interface BubbleProps {+ title: string;+ text: string;+ position: TourPosition;+ __floatingOnboardingUnmount?: () => void;+}++const Bubble: React.FC<BubbleProps> = ({title, text, position}) => (+ <div+ className={clsx(+ 'prompt-tooltip-container text-wrap border-1 border-solid border-mid-black tooltip-container elevated-sharp',+ position,+ 'p-01 br-3 bg-dark',+ )}+ >+ <div className="floating-tooltip-inner gap-2 flex flex-col pos-rel br-2 border-1 border-solid border-blue p-2">+ {title && (+ <div className="tooltip-title-holder flex flex-row pos-rel">+ <h3 className="text-white text lg mb-2">{title}</h3>+ </div>+ )}+ <div className="tooltip-description-holder flex flex-row pos-rel">+ <p className="text-white text md" style={{whiteSpace: 'pre-line'}}>{text}</p>+ </div>+ <TourNav/>+ </div>+ </div>+);++interface TourPointerBubbleProps {+ target: string;+ title: string;+ text: string;+ position: TourPosition;+ offsetTop?: number;+}++export const TourPointerBubble: React.FC<TourPointerBubbleProps> = ({target, title, text, position, offsetTop}) => (+ <FloatingOnboarding target={target} className="tour-bubble-layer" offsetTop={offsetTop}>+ <Bubble title={title} text={text} position={position}/>+ </FloatingOnboarding>+);diff --git a/freemocap-ui/src/components/tutorial/TourPointerFallback.tsx b/freemocap-ui/src/components/tutorial/TourPointerFallback.tsxnew file mode 100644index 00000000..c7625708--- /dev/null+++ b/freemocap-ui/src/components/tutorial/TourPointerFallback.tsx@@ -0,0 +1,55 @@+import React, {useEffect, useState} from 'react';+import {useTranslation} from 'react-i18next';+import {useTutorial} from './TutorialContext';+import {TourNav} from './TourNav';++// Mirror of FloatingOnboarding's own visibility test: is the anchor present,+// on-screen, and non-zero?+function isTargetVisible(selector: string): boolean {+ const el = document.querySelector(selector) as HTMLElement | null;+ if (!el || !document.body.contains(el)) return false;+ const style = window.getComputedStyle(el);+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;+ const rect = el.getBoundingClientRect();+ return rect.width > 0 && rect.height > 0;+}++// Safety net for pointer steps: the Back/Next/Skip controls normally live on the+// anchored bubble, but that bubble can't render when its target is hidden+// (collapsed panel, wrong route, not yet mounted). When that happens this renders+// the SAME controls on a prominent centered card so the tour can never soft-lock.+// It stays hidden while the target is visible β the bubble owns the controls then.+export const TourPointerFallback: React.FC = () => {+ const {t} = useTranslation();+ const {currentStep} = useTutorial();+ const [targetHidden, setTargetHidden] = useState(false);+ const target = currentStep?.target;++ useEffect(() => {+ setTargetHidden(false);+ if (!target) return;+ let interval: ReturnType<typeof setInterval> | undefined;+ // Grace period so normal step transitions don't flash the fallback before+ // the target mounts.+ const timeout = setTimeout(() => {+ const check = () => setTargetHidden(!isTargetVisible(target));+ check();+ interval = setInterval(check, 400);+ }, 900);+ return () => {+ clearTimeout(timeout);+ if (interval) clearInterval(interval);+ };+ }, [target]);++ if (!currentStep || currentStep.kind !== 'pointer' || !targetHidden) return null;++ return (+ <div className="tour-pointer-fallback bg-dark border-1 border-solid border-blue br-3 elevated-sharp p-2 flex flex-col gap-2">+ <h3 className="text-white text lg">{t(currentStep.titleKey)}</h3>+ <p className="text-white text md" style={{whiteSpace: 'pre-line'}}>{t(currentStep.textKey)}</p>+ <p className="tour-control-caption text sm text-gray">{t('tour.controls.targetHidden')}</p>+ <TourNav/>+ </div>+ );+};diff --git a/freemocap-ui/src/components/tutorial/TourSpotlight.tsx b/freemocap-ui/src/components/tutorial/TourSpotlight.tsxnew file mode 100644index 00000000..c35617a0--- /dev/null+++ b/freemocap-ui/src/components/tutorial/TourSpotlight.tsx@@ -0,0 +1,23 @@+import React from 'react';+import {FloatingOnboarding} from '@/hooks/floatingOnboarding';++// The ring/dim visual. It's a component (not a bare <div>) so it can absorb the+// `__floatingOnboardingUnmount` prop FloatingOnboarding injects via cloneElement,+// keeping it off the DOM node.+const SpotlightRing: React.FC<{__floatingOnboardingUnmount?: () => void}> = () => (+ <div className="tour-spotlight"/>+);++interface TourSpotlightProps {+ target: string;+}++// Dims the app and highlights the current pointer target. Reuses+// FloatingOnboarding purely for positioning β it sizes a fixed box to the target,+// and the box-shadow in .tour-spotlight does the dimming. Purely visual+// (pointer-events: none); it does not trap clicks.+export const TourSpotlight: React.FC<TourSpotlightProps> = ({target}) => (+ <FloatingOnboarding target={target} className="tour-spotlight-layer">+ <SpotlightRing/>+ </FloatingOnboarding>+);diff --git a/freemocap-ui/src/components/tutorial/TutorialContext.tsx b/freemocap-ui/src/components/tutorial/TutorialContext.tsxnew file mode 100644index 00000000..2b8b27af--- /dev/null+++ b/freemocap-ui/src/components/tutorial/TutorialContext.tsx@@ -0,0 +1,234 @@+import React, {createContext, useCallback, useContext, useEffect, useMemo, useReducer, useState} from 'react';+import {loadFromStorage, saveToStorage} from '@/store/persistence';+import {TOURS} from './tours';+import {emitTourEvent} from './telemetry';+import type {Tour, TourStep} from './types';++// βββ Durable completion flag ββββββββββββββββββββββββββββββββββββββββββββββββββ+// One-shot flag persisted through the app's storage SSOT (store/persistence.ts,+// 'freemocap:' prefix). Read once at startup to drive the first-run nudge; written+// when a tour is finished or skipped so the app stops nudging.+const STORAGE_KEY = 'tutorial';++interface TutorialPersisted {+ completed: boolean;+}++// βββ Runtime state (transient, per session) βββββββββββββββββββββββββββββββββββ+interface TutorialState {+ status: 'idle' | 'active';+ activeTourId: string | null;+ currentStepId: string | null;+ history: string[]; // outgoing step ids, pushed on every forward move; popped by back()+}++const initialState: TutorialState = {+ status: 'idle',+ activeTourId: null,+ currentStepId: null,+ history: [],+};++type Action =+ | {type: 'START'; tourId: string; stepId: string}+ | {type: 'GOTO'; stepId: string} // forward move: remember where we came from+ | {type: 'BACK'} // pop history+ | {type: 'END'};++function reducer(state: TutorialState, action: Action): TutorialState {+ switch (action.type) {+ case 'START':+ return {status: 'active', activeTourId: action.tourId, currentStepId: action.stepId, history: []};+ case 'GOTO':+ if (state.currentStepId === null) return state;+ return {...state, currentStepId: action.stepId, history: [...state.history, state.currentStepId]};+ case 'BACK': {+ if (state.history.length === 0) return state;+ const history = state.history.slice(0, -1);+ const prev = state.history[state.history.length - 1];+ return {...state, currentStepId: prev, history};+ }+ case 'END':+ return initialState;+ default:+ return state;+ }+}++// Walk the tour's default path (first choice / linear `next`) from the start so+// the pointer bubble can show a stable "Step N of M". Branches off this path fall+// back to history depth (handled in the value computation below).+function computeDefaultPath(tour: Tour): string[] {+ const path: string[] = [];+ const seen = new Set<string>();+ let id: string | undefined = tour.startStepId;+ while (id && !seen.has(id)) {+ seen.add(id);+ path.push(id);+ const step: TourStep | undefined = tour.steps[id];+ if (!step) break;+ const nextId: string | undefined = step.kind === 'pointer' ? step.next : step.choices?.[0]?.next;+ id = nextId || undefined;+ }+ return path;+}++// The ordered sub-steps of a main step's "deeper" sub-tour: follow `deeper` then+// `next` until the chain rejoins the main path (or ends). Used to number sub-steps+// as parent.N (e.g. 2.1, 2.2).+function subChain(tour: Tour, parentId: string, defaultPath: string[]): string[] {+ const onMain = new Set(defaultPath);+ const chain: string[] = [];+ let id: string | undefined = tour.steps[parentId]?.deeper;+ while (id && !onMain.has(id) && !chain.includes(id)) {+ chain.push(id);+ id = tour.steps[id]?.next;+ }+ return chain;+}++interface TutorialContextValue {+ isTourActive: boolean;+ completed: boolean;+ currentStep: TourStep | null;+ stepIndex: number; // 1-based position on the main path (parent index for sub-steps)+ stepTotal: number; // main-path length+ stepLabel: string; // display label: "2 / 7" on the main path, "2.1" in a sub-tour+ canGoBack: boolean;+ canGoDeeper: boolean; // true when the current step has a "deeper" sub-tour+ startTour: (tourId: string) => void;+ next: () => void;+ back: () => void;+ deeper: () => void;+ choose: (choiceId: string) => void;+ skip: () => void;+}++const TutorialContext = createContext<TutorialContextValue | null>(null);++export const TutorialProvider: React.FC<{children: React.ReactNode}> = ({children}) => {+ const [state, dispatch] = useReducer(reducer, initialState);+ const [completed, setCompleted] = useState<boolean>(+ () => loadFromStorage<TutorialPersisted>(STORAGE_KEY, {completed: false}).completed,+ );++ const activeTour = state.activeTourId ? TOURS[state.activeTourId] : null;+ const currentStep = activeTour && state.currentStepId ? activeTour.steps[state.currentStepId] ?? null : null;++ const markCompleted = useCallback(() => {+ saveToStorage<TutorialPersisted>(STORAGE_KEY, {completed: true});+ setCompleted(true);+ }, []);++ const {stepIndex, stepTotal, stepLabel} = useMemo(() => {+ if (!activeTour || !state.currentStepId) return {stepIndex: 0, stepTotal: 0, stepLabel: ''};+ const path = computeDefaultPath(activeTour);+ const total = path.length;+ const onPath = path.indexOf(state.currentStepId);+ if (onPath >= 0) {+ // Main-path step β "N / total".+ return {stepIndex: onPath + 1, stepTotal: total, stepLabel: `${onPath + 1} / ${total}`};+ }+ // Sub-tour step β number it off its parent: "parent.sub" (e.g. "2.1").+ const parentId = activeTour.steps[state.currentStepId]?.parentStepId;+ const parentIndex = parentId ? path.indexOf(parentId) + 1 : state.history.length + 1;+ const chain = parentId ? subChain(activeTour, parentId, path) : [];+ const subIndex = chain.indexOf(state.currentStepId) + 1;+ const label = parentIndex && subIndex ? `${parentIndex}.${subIndex}` : `${parentIndex}`;+ return {stepIndex: parentIndex, stepTotal: total, stepLabel: label};+ }, [activeTour, state.currentStepId, state.history.length]);++ const startTour = useCallback((tourId: string) => {+ const tour = TOURS[tourId];+ if (!tour) throw new Error(`Unknown tour id: ${tourId}`);+ emitTourEvent('tour_started', {tourId});+ dispatch({type: 'START', tourId, stepId: tour.startStepId});+ }, []);++ // Natural end: the user advanced past the last step (a step whose next is empty).+ const completeTour = useCallback(() => {+ emitTourEvent('tour_completed', {tourId: state.activeTourId, stepId: state.currentStepId});+ markCompleted();+ dispatch({type: 'END'});+ }, [state.activeTourId, state.currentStepId, markCompleted]);++ // Move to a step id; an empty/absent id means "past the end" β complete the tour.+ const goto = useCallback((stepId: string | undefined) => {+ if (!stepId) {+ completeTour();+ return;+ }+ dispatch({type: 'GOTO', stepId});+ }, [completeTour]);++ const next = useCallback(() => {+ if (!currentStep) return;+ const nextId = currentStep.kind === 'pointer'+ ? currentStep.next+ : currentStep.choices?.[0]?.next; // default = first choice+ goto(nextId);+ }, [currentStep, goto]);++ const choose = useCallback((choiceId: string) => {+ if (!currentStep) return;+ const choice = currentStep.choices?.find((c) => c.id === choiceId);+ if (!choice) throw new Error(`Unknown choice "${choiceId}" on step "${currentStep.id}"`);+ goto(choice.next);+ }, [currentStep, goto]);++ const back = useCallback(() => dispatch({type: 'BACK'}), []);++ // Detour into the current step's "deeper" sub-tour (its first sub-step).+ const deeper = useCallback(() => {+ if (!currentStep?.deeper) return;+ emitTourEvent('tour_deeper', {tourId: state.activeTourId, stepId: state.currentStepId});+ goto(currentStep.deeper);+ }, [currentStep, goto, state.activeTourId, state.currentStepId]);++ // Early exit: skip button, Esc, or clicking the overlay backdrop. The step id+ // records exactly where the user bailed β the key drop-off signal.+ const skip = useCallback(() => {+ emitTourEvent('tour_skipped', {tourId: state.activeTourId, stepId: state.currentStepId, stepIndex, stepTotal});+ markCompleted();+ dispatch({type: 'END'});+ }, [state.activeTourId, state.currentStepId, stepIndex, stepTotal, markCompleted]);++ // Funnel middle: one event per step entry (forward or back), so drop-off+ // between any two steps is visible. Keyed on step id so it fires once per view.+ useEffect(() => {+ if (!state.activeTourId || !state.currentStepId) return;+ emitTourEvent('tour_step_viewed', {+ tourId: state.activeTourId,+ stepId: state.currentStepId,+ stepIndex,+ stepTotal,+ kind: currentStep?.kind,+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [state.activeTourId, state.currentStepId]);++ const value = useMemo<TutorialContextValue>(() => ({+ isTourActive: state.status === 'active',+ completed,+ currentStep,+ stepIndex,+ stepTotal,+ stepLabel,+ canGoBack: state.history.length > 0,+ canGoDeeper: !!currentStep?.deeper,+ startTour,+ next,+ back,+ deeper,+ choose,+ skip,+ }), [state.status, state.history.length, completed, currentStep, stepIndex, stepTotal, stepLabel, startTour, next, back, deeper, choose, skip]);++ return <TutorialContext.Provider value={value}>{children}</TutorialContext.Provider>;+};++export function useTutorial(): TutorialContextValue {+ const ctx = useContext(TutorialContext);+ if (!ctx) throw new Error('useTutorial must be used within a TutorialProvider');+ return ctx;+}diff --git a/freemocap-ui/src/components/tutorial/index.ts b/freemocap-ui/src/components/tutorial/index.tsnew file mode 100644index 00000000..0a4bc496--- /dev/null+++ b/freemocap-ui/src/components/tutorial/index.ts@@ -0,0 +1,4 @@+export {TutorialProvider, useTutorial} from './TutorialContext';+export {TourController} from './TourController';+export {TOURS} from './tours';+export type {Tour, TourStep, TourChoice, TourStepKind, TourPosition} from './types';diff --git a/freemocap-ui/src/components/tutorial/telemetry.ts b/freemocap-ui/src/components/tutorial/telemetry.tsnew file mode 100644index 00000000..2c410186--- /dev/null+++ b/freemocap-ui/src/components/tutorial/telemetry.ts@@ -0,0 +1,30 @@+import {serverUrls} from '@/constants/server-urls';++// Tour lifecycle events form a funnel so we can see WHERE people drop off, not+// just how many finish:+// tour_started β tour_step_viewed (once per step) β tour_completed | tour_skipped+// The step id on tour_skipped is the most actionable signal β it's the exact step+// people abandon on.+export type TourEvent =+ | 'tour_started'+ | 'tour_step_viewed'+ | 'tour_deeper'+ | 'tour_completed'+ | 'tour_skipped';++// Fire-and-forget. Telemetry is best-effort instrumentation at a system boundary:+// it must never disrupt the tour, so network/serialization failures are swallowed.+// The backend no-ops when the user has opted out (see /freemocap/telemetry/track),+// so the opt-in decision stays in one place and we don't re-check it here.+export function emitTourEvent(event: TourEvent, payload: Record<string, unknown>): void {+ try {+ void fetch(serverUrls.endpoints.trackTelemetry, {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({eventType: event, payload}),+ keepalive: true, // let the event flush even if a route change unmounts us+ }).catch(() => {});+ } catch {+ // ignore β telemetry must never break the tour+ }+}diff --git a/freemocap-ui/src/components/tutorial/tours/getting-started.ts b/freemocap-ui/src/components/tutorial/tours/getting-started.tsnew file mode 100644index 00000000..999bcc7b--- /dev/null+++ b/freemocap-ui/src/components/tutorial/tours/getting-started.ts@@ -0,0 +1,193 @@+import type {Tour} from '../types';+import {EXTERNAL_URLS} from '@/constants/external-urls';++// v1 getting-started tour β the main "first touch" path a new user follows:+// welcome β server connection β camera connection β realtime pipeline+// β calibration (with a docs hand-off) β record mocap β finish+//+// All pointer steps live on the /streaming view. The engine also supports+// branching (see TourStep.choices) β this tour just runs linearly for now. Deeper+// per-topic tutorials can be added later as their own tours in the registry.+export const gettingStartedTour: Tour = {+ id: 'getting-started',+ startStepId: 'welcome',+ steps: {+ welcome: {+ id: 'welcome',+ kind: 'info',+ titleKey: 'tour.welcome.title',+ textKey: 'tour.welcome.text',+ choices: [+ {id: 'start', labelKey: 'tour.welcome.start', next: 'server-connection'},+ ],+ },++ 'server-connection': {+ id: 'server-connection',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="connection:server-connection"]',+ position: 'pos-bottom-right',+ titleKey: 'tour.server.title',+ textKey: 'tour.server.text',+ deeper: 'server-connection.1',+ next: 'camera-connection',+ },+ // ββ Server-connection sub-tour (steps 2.1, 2.2) β rejoins the main path at+ // camera-connection. A sub-step just sets parentStepId + chains via next.+ 'server-connection.1': {+ id: 'server-connection.1',+ parentStepId: 'server-connection',+ kind: 'pointer',+ route: '/streaming',+ target: '.connection-container',+ position: 'pos-right',+ offsetTop: 150,+ // Open the connection panel so the sub-tour can point at its innards.+ // The dropdown closes on the next outside click, so each sub-step reopens it.+ onEnter: {+ type: 'click',+ target: '[data-onboarding="connection:server-connection"] .connection-status-button-opener',+ unlessVisible: '.connection-container',+ },+ onExit: {+ type: 'click',+ target: '[data-onboarding="connection:server-connection"] .connection-status-button-opener',+ onlyIfVisible: '.connection-container',+ },+ titleKey: 'tour.serverDeep.status.title',+ textKey: 'tour.serverDeep.status.text',+ next: 'server-connection.2',+ },+ 'server-connection.2': {+ id: 'server-connection.2',+ parentStepId: 'server-connection',+ kind: 'pointer',+ route: '/streaming',+ target: '.connection-container',+ position: 'pos-right',+ offsetTop: 150,+ onEnter: {+ type: 'click',+ target: '[data-onboarding="connection:server-connection"] .connection-status-button-opener',+ unlessVisible: '.connection-container',+ },+ onExit: {+ type: 'click',+ target: '[data-onboarding="connection:server-connection"] .connection-status-button-opener',+ onlyIfVisible: '.connection-container',+ },+ titleKey: 'tour.serverDeep.toggle.title',+ textKey: 'tour.serverDeep.toggle.text',+ next: 'camera-connection',+ },+ 'camera-connection': {+ id: 'camera-connection',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="camera:connect-camera"]',+ position: 'pos-bottom-left',+ titleKey: 'tour.camera.title',+ textKey: 'tour.camera.text',+ deeper: 'camera-connection.1',+ next: 'realtime-pipeline',+ },+ // ββ Camera-connection sub-tour (steps 3.1, 3.2) β rejoins at realtime-pipeline.+ 'camera-connection.1': {+ id: 'camera-connection.1',+ parentStepId: 'camera-connection',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="camera:connect-camera"]',+ position: 'pos-bottom-left',+ titleKey: 'tour.cameraDeep.detect.title',+ textKey: 'tour.cameraDeep.detect.text',+ next: 'camera-connection.2',+ },+ 'camera-connection.2': {+ id: 'camera-connection.2',+ parentStepId: 'camera-connection',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="camera:connect-camera"]',+ position: 'pos-bottom-left',+ titleKey: 'tour.cameraDeep.settings.title',+ textKey: 'tour.cameraDeep.settings.text',+ next: 'realtime-pipeline',+ },+ 'realtime-pipeline': {+ id: 'realtime-pipeline',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="realtime:pipeline"]',+ position: 'pos-bottom-right',+ titleKey: 'tour.realtime.title',+ textKey: 'tour.realtime.text',+ deeper: 'realtime-pipeline.1',+ next: 'calibration',+ },+ // ββ Realtime-pipeline sub-tour (steps 4.1, 4.2) β rejoins at calibration.+ 'realtime-pipeline.1': {+ id: 'realtime-pipeline.1',+ parentStepId: 'realtime-pipeline',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="realtime:pipeline"]',+ position: 'pos-bottom-right',+ titleKey: 'tour.realtimeDeep.controls.title',+ textKey: 'tour.realtimeDeep.controls.text',+ next: 'realtime-pipeline.2',+ },+ 'realtime-pipeline.2': {+ id: 'realtime-pipeline.2',+ parentStepId: 'realtime-pipeline',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="realtime:pipeline"]',+ position: 'pos-bottom-right',+ titleKey: 'tour.realtimeDeep.recording.title',+ textKey: 'tour.realtimeDeep.recording.text',+ next: 'calibration',+ },+ calibration: {+ id: 'calibration',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="calibration:what-is-calibration"]',+ position: 'pos-bottom-left',+ titleKey: 'tour.calibration.title',+ textKey: 'tour.calibration.text',+ docsUrl: EXTERNAL_URLS.DOCS,+ next: 'recording',+ },+ recording: {+ id: 'recording',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="recording:start-recording"]',+ position: 'pos-top-left',+ titleKey: 'tour.recording.title',+ textKey: 'tour.recording.text',+ next: 'nav-tabs',+ },+ 'nav-tabs': {+ id: 'nav-tabs',+ kind: 'pointer',+ route: '/streaming',+ target: '[data-onboarding="nav:tabs"]',+ position: 'pos-bottom-left',+ titleKey: 'tour.tabs.title',+ textKey: 'tour.tabs.text',+ next: 'finish',+ },+ finish: {+ id: 'finish',+ kind: 'info',+ titleKey: 'tour.finish.title',+ textKey: 'tour.finish.text',+ choices: [+ {id: 'done', labelKey: 'tour.finish.done', next: ''},+ ],+ },+ },+};diff --git a/freemocap-ui/src/components/tutorial/tours/index.ts b/freemocap-ui/src/components/tutorial/tours/index.tsnew file mode 100644index 00000000..81cd0865--- /dev/null+++ b/freemocap-ui/src/components/tutorial/tours/index.ts@@ -0,0 +1,9 @@+import type {Tour} from '../types';+import {gettingStartedTour} from './getting-started';++// Registry of all tours. A new tour is one import + one entry here.+export const TOURS: Record<string, Tour> = {+ 'getting-started': gettingStartedTour,+};++export type TourId = keyof typeof TOURS;diff --git a/freemocap-ui/src/components/tutorial/types.ts b/freemocap-ui/src/components/tutorial/types.tsnew file mode 100644index 00000000..d0408d51--- /dev/null+++ b/freemocap-ui/src/components/tutorial/types.ts@@ -0,0 +1,84 @@+// Tutorial step-graph model.+//+// A tour is a directed graph of steps keyed by id. Navigation is data-driven:+// a step declares where it goes next (linear `next`, or a set of `choices` that+// branch). Adding content never touches the engine β a new step is one object in+// a tour's `steps` map, a new branch is one entry in `choices`, a new tour is one+// file plus one line in the registry (tours/index.ts).++// Position of the pointer bubble relative to its anchor. Matches the `pos-*`+// arrow classes in styles/tooltips.css.+export type TourPosition =+ | 'pos-top' | 'pos-top-left' | 'pos-top-right'+ | 'pos-bottom' | 'pos-bottom-left' | 'pos-bottom-right'+ | 'pos-left' | 'pos-right';++// - 'branch': centered overlay with 2+ labelled choices, each routing to a+// different next step. The first choice is the implicit default.+// - 'pointer': anchors a bubble to a real element (via a data-onboarding+// selector) and advances linearly through `next`.+// - 'info': centered overlay with exactly one implicit choice. Same renderer as+// 'branch' β used for intro / "you're all set" screens that branches converge on.+export type TourStepKind = 'branch' | 'pointer' | 'info';++// Side effect run when a step is entered, so a step can expand the part of the UI+// it's about (open a panel, expand a row). v1 supports a single action: click a DOM+// element. `unlessVisible` makes it idempotent β skip the click if that selector is+// already on-screen, so re-entering the step doesn't toggle an open panel shut.+export interface TourAction {+ type: 'click';+ target: string; // CSS selector of the control to click+ unlessVisible?: string; // skip the click if this selector is already visible (for "open")+ onlyIfVisible?: string; // skip the click unless this selector is visible (for "close")+}++export interface TourChoice {+ id: string;+ labelKey: string; // i18n key, resolved with t()+ iconClass?: string; // optional icon class for ButtonCard+ next: string; // id of the step this choice leads to+}++export interface TourStep {+ id: string;+ kind: TourStepKind;+ titleKey: string; // i18n key+ textKey: string; // i18n key+ // Route the controller navigates to before showing this step (HashRouter+ // path). Omitted = stay on the current route.+ route?: string;+ // 'pointer' only: CSS selector of the anchor element, e.g.+ // '[data-onboarding="camera:connect-camera"]'.+ target?: string;+ position?: TourPosition;+ // Nudge the bubble down (+) / up (β) from its anchored position, in px. Handy+ // when a step points at a tall element (e.g. an opened panel) and centering+ // would push the bubble off-screen.+ offsetTop?: number;+ // Optional side effects: onEnter runs when the step is shown (e.g. open the panel+ // it explains); onExit runs when leaving it (e.g. close that panel again). onExit+ // makes cleanup work for every input method, not just mouse click-outside.+ onEnter?: TourAction;+ onExit?: TourAction;+ // Optional "Read the docs β" link shown on the step, for steps that hand off to+ // deeper documentation (e.g. calibration).+ docsUrl?: string;+ // 'branch'/'info' only. For 'info', a single choice acts as the sole button.+ choices?: TourChoice[];+ // 'pointer' only: the next step id. Omitted = this is the last step.+ next?: string;+ // Main-path step only: id of the first step of this step's "deeper" sub-tour.+ // When set, the step shows a Back / Deeper / Next control. The sub-tour is a+ // chain of steps (via `next`) whose last `next` rejoins the main path, so+ // "Deeper" is a detour that returns to the flow.+ deeper?: string;+ // Sub-tour step only: id of the main-path step this belongs to. Used to number+ // sub-steps off the parent (e.g. parent step 2 β sub-steps 2.1, 2.2).+ parentStepId?: string;+}++export interface Tour {+ id: string;+ startStepId: string;+ steps: Record<string, TourStep>;+}diff --git a/freemocap-ui/src/components/ui-components/MainNavTabs.tsx b/freemocap-ui/src/components/ui-components/MainNavTabs.tsxindex 0a48114e..6f4a0731 100644--- a/freemocap-ui/src/components/ui-components/MainNavTabs.tsx+++ b/freemocap-ui/src/components/ui-components/MainNavTabs.tsx@@ -1,68 +1,13 @@import React, { useCallback, useMemo } from "react";import { useLocation, useNavigate } from "react-router-dom";-import { useAppDispatch, useAppSelector } from "@/store";-import {- activeRecordingCleared,- selectActiveRecordingFullPath,- selectActiveRecordingName,-} from "@/store/slices/active-recording/active-recording-slice";-import { useElectronIPC } from "@/services";-import IconButton from "@/components/ui-components/IconButton";+// Active-recording responsibilities were folded into the Playback tab, so only+// these two top-level modes remain.const NAV_TABS = [- { path: '/streaming', label: 'Streaming' },- { path: '/playback', label: 'Playback' },- { path: '/active-recording', label: 'Active Recording' },+ { path: '/streaming', label: 'Streaming', onboarding: 'nav:streaming' },+ { path: '/playback', label: 'Playback', onboarding: 'nav:playback' },] as const;-const ActiveRecordingLabel: React.FC = () => {- const dispatch = useAppDispatch();- const recordingName = useAppSelector(selectActiveRecordingName);- const fullPath = useAppSelector(selectActiveRecordingFullPath);- const { api } = useElectronIPC();-- const handleOpenFolder = async (e: React.MouseEvent) => {- e.stopPropagation();- if (!fullPath) return;- try {- await api?.fileSystem.openFolder.mutate({ path: fullPath });- } catch (err) {- console.error('Failed to open recording folder:', err);- }- };-- const handleClearRecording = (e: React.MouseEvent) => {- e.stopPropagation();- dispatch(activeRecordingCleared());- };-- return (- <span className="flex flex-row items-center gap-1">- <span className="text-gray">Active Recording</span>- {recordingName ? (- <span- className="flex flex-row text-nowrap tag text sm text-white"- style={{ fontFamily: 'monospace', maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}- title={fullPath ?? recordingName}- onClick={handleOpenFolder}- >- {recordingName}- <IconButton- icon="close-icon"- iconSize="icon-size-12"- className="ml-1"- onClick={handleClearRecording}- style={{ lineHeight: 1 }}- title="Clear active recording"- />- </span>- ) : (- <span className="text sm text-gray" style={{ fontStyle: 'italic' }}>(none)</span>- )}- </span>- );-};-export const MainNavTabs = () => {const location = useLocation();const navigate = useNavigate();@@ -78,20 +23,18 @@ export const MainNavTabs = () => {return (<div className="main-tab-bar main-tab-bar-container pos-abs top-0 left-0 main-segmented-control-container">- <div className="segmented-control-container bg-middark br-2 gap-1 p-1 z-1 flex flex-row">+ <div data-onboarding="nav:tabs" className="segmented-control-container bg-middark br-2 gap-1 p-1 z-1 flex flex-row">{NAV_TABS.map((tab, idx) => {const isActive = idx === activeIdx;return (<divkey={tab.path}+ data-onboarding={tab.onboarding}className={`segmented-control-button justify-center button pl-2 pr-2 gap-1 br-1 flex-inline items-center cursor-pointer${isActive ? ' bg-dark' : ''}`}onClick={() => handleClick(tab.path)}onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleClick(tab.path); } }}>- {tab.path === '/active-recording'- ? <ActiveRecordingLabel />- : <p className={`text md text-center p-1 ${isActive ? ' text-white' : ' text-gray'}`}>{tab.label}</p>- }+ <p className={`text md text-center p-1 ${isActive ? ' text-white' : ' text-gray'}`}>{tab.label}</p></div>);})}diff --git a/freemocap-ui/src/components/ui-components/SettingsModal.tsx b/freemocap-ui/src/components/ui-components/SettingsModal.tsxindex 62b00379..2a7f7dc3 100644--- a/freemocap-ui/src/components/ui-components/SettingsModal.tsx+++ b/freemocap-ui/src/components/ui-components/SettingsModal.tsx@@ -8,6 +8,7 @@ import ButtonSm from '@/components/ui-components/ButtonSm';import IconButton from '@/components/ui-components/IconButton';import Checkbox from '@/components/ui-components/Checkbox';import SubactionHeader from '@/components/ui-components/SubactionHeader';+import {useTutorial} from '@/components/tutorial';interface SettingsModalProps {open: boolean;@@ -22,6 +23,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({open, onClose}) =>const {isElectron, api} = useElectronIPC();const dispatch = useAppDispatch();const isRecording = useAppSelector(selectIsAnyRecording);+ const {startTour} = useTutorial();const [baseFolder, setBaseFolder] = useState<string>('');const [telemetryEnabled, setTelemetryEnabled] = useState<boolean>(true);@@ -117,6 +119,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({open, onClose}) =>await api.fileSystem.openFolder.mutate({path: baseFolder});}, [api, baseFolder]);+ const handleReplayTour = useCallback(() => {+ startTour('getting-started');+ onClose();+ }, [startTour, onClose]);+const handleTelemetryToggle = useCallback(async (checked: boolean) => {setTelemetryEnabled(checked);try {@@ -194,6 +201,19 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({open, onClose}) =>)}</div>+ {/* Getting started */}+ <div className="flex flex-col gap-2 bg-secondary p-2 br-1">+ <SubactionHeader text="Getting started" className="text-gray"/>+ <p className="text sm text-gray">Replay the guided tour of the basics.</p>+ <div className="flex flex-row">+ <ButtonSm+ text="Replay tutorial"+ buttonType="quaternary"+ onClick={handleReplayTour}+ />+ </div>+ </div>+{/* Bottom actions */}<div className="flex flex-row gap-2" style={{justifyContent: 'flex-end'}}><ButtonSm text="Close" buttonType="quaternary" onClick={onClose}/>diff --git a/freemocap-ui/src/components/ui-components/SettingsOverlay.tsx b/freemocap-ui/src/components/ui-components/SettingsOverlay.tsxindex c533a7bc..0cf3e70f 100644--- a/freemocap-ui/src/components/ui-components/SettingsOverlay.tsx+++ b/freemocap-ui/src/components/ui-components/SettingsOverlay.tsx@@ -128,7 +128,7 @@ export const SettingsOverlay: React.FC<SettingsOverlayProps> = ({return (<>- <div className="streaming-bar-setting-action-bar z-2 pos-abs flex flex-row gap-3 top-0 right-0">+ <div data-onboarding="realtime:pipeline" className="streaming-bar-setting-action-bar z-2 pos-abs flex flex-row gap-3 top-0 right-0"><div className="live-action-buttons-container flex flex-row gap-4">{/* GROUP 1 */}diff --git a/freemocap-ui/src/components/ui-components/WelcomeModal.tsx b/freemocap-ui/src/components/ui-components/WelcomeModal.tsxindex 64392889..1d1b24ad 100644--- a/freemocap-ui/src/components/ui-components/WelcomeModal.tsx+++ b/freemocap-ui/src/components/ui-components/WelcomeModal.tsx@@ -13,6 +13,7 @@ import ButtonSm from '@/components/ui-components/ButtonSm';import ButtonCard from '@/components/ui-components/ButtonCard';import IconButton from '@/components/ui-components/IconButton';import Checkbox from '@/components/ui-components/Checkbox';+import { useTutorial } from '@/components/tutorial';interface WelcomeModalProps {open: boolean;@@ -28,6 +29,7 @@ export const WelcomeModal: React.FC<WelcomeModalProps> = ({ open, onClose }) =>const { isElectron, api } = useElectronIPC();const { connectedCameraIds } = useServer();const cameras = useAppSelector(selectCameras);+ const { startTour } = useTutorial();const prevCountRef = useRef(connectedCameraIds.length);// Close automatically when cameras first connect@@ -93,6 +95,11 @@ export const WelcomeModal: React.FC<WelcomeModalProps> = ({ open, onClose }) =>onClose();}, [navigate, onClose]);+ const handleStartTour = useCallback(() => {+ startTour('getting-started');+ onClose();+ }, [startTour, onClose]);+if (!open) return null;return (@@ -144,6 +151,17 @@ export const WelcomeModal: React.FC<WelcomeModalProps> = ({ open, onClose }) =>/></div>+ {/* Guided tour launcher β emphasized until the user finishes it once */}+ <div className="mt-2">+ <ButtonSm+ iconClass="learn-icon"+ text={t('tour.take')}+ textColor="text-white"+ className="full-width justify-center primary accent tour-nudge-pulse"+ onClick={handleStartTour}+ />+ </div>+{/* Telemetry toggle */}{telemetryLoaded && (<div className="mt-2">diff --git a/freemocap-ui/src/components/viewport3d/scene/SkeletonFitRitualIndicator.tsx b/freemocap-ui/src/components/viewport3d/scene/SkeletonFitRitualIndicator.tsxnew file mode 100644index 00000000..3c60ee50--- /dev/null+++ b/freemocap-ui/src/components/viewport3d/scene/SkeletonFitRitualIndicator.tsx@@ -0,0 +1,182 @@+import {memo, useEffect, useRef, useState, useSyncExternalStore} from "react";+import {useAppSelector} from "@/store/hooks";+import {selectIsPipelineConnected} from "@/store/slices/realtime";+import {useServerOptional} from "@/services/server/server-context";+import type {SkeletonFitStates} from "@/services/server/server-helpers/skeleton-fit-state-store";+import type {SkeletonFitStateSnapshot} from "@/services/server/server-helpers/websocket-message-types";++const FITTED_TOAST_MS = 5000;+// Display-only heuristic: median |captured - seed| / seed above this reads as a bonked fit.+const PRIOR_DEVIATION_WARN = 0.15;++// Higher-priority state wins when several pipelines report at once.+const STATE_PRIORITY: Record<string, number> = {countdown: 3, capturing: 2, fitted: 1, idle: 0};++const EMPTY_STATES: SkeletonFitStates = {};+const NOOP_SUBSCRIBE = () => () => {};+const getEmptyStates = (): SkeletonFitStates => EMPTY_STATES;++function pickMostActive(states: SkeletonFitStates): SkeletonFitStateSnapshot | null {+ let best: SkeletonFitStateSnapshot | null = null;+ for (const state of Object.values(states)) {+ if (state && (best === null || (STATE_PRIORITY[state.state] ?? 0) > (STATE_PRIORITY[best.state] ?? 0))) {+ best = state;+ }+ }+ return best;+}++/**+ * Renders the segment-fit calibration ritual (armed by the Reset Fitter button)+ * as a top-center viewport overlay: countdown β hold-still capture with quality+ * hints β "locked" confirmation. State arrives pushed over the websocket+ * (server sends only on change); renders nothing while the fitter is idle.+ * All gating rules live server-side β this only visualizes the snapshot.+ */+export const SkeletonFitRitualIndicator = memo(function SkeletonFitRitualIndicator() {+ const isConnected = useAppSelector(selectIsPipelineConnected);+ const server = useServerOptional();+ const store = server?.getSkeletonFitStateStore();+ const states = useSyncExternalStore(+ store?.subscribe ?? NOOP_SUBSCRIBE,+ store?.getSnapshot ?? getEmptyStates,+ );+ const snap = pickMostActive(states);++ const [toastAt, setToastAt] = useState<number | null>(null);+ // null until the first state is observed, so a ritual that finished before+ // this component mounted doesn't replay its "locked" toast.+ const prevStateRef = useRef<string | null>(null);++ useEffect(() => {+ const state = snap?.state ?? "idle";+ const prev = prevStateRef.current;+ prevStateRef.current = state;+ if (prev === null) return; // baseline observation, not a transition+ if (state === "fitted" && prev !== "fitted") {+ setToastAt(Date.now());+ } else if (state === "countdown" || state === "capturing") {+ setToastAt(null); // a (re-)armed ritual clears any stale toast+ }+ }, [snap]);++ // FITTED is quiescent (no further pushes), so the toast needs its own+ // timer to disappear.+ useEffect(() => {+ if (toastAt === null) return;+ const remaining = FITTED_TOAST_MS - (Date.now() - toastAt);+ const timer = window.setTimeout(() => setToastAt(null), Math.max(0, remaining));+ return () => window.clearTimeout(timer);+ }, [toastAt]);++ if (!isConnected || !snap) return null;++ const toastVisible = snap.state === "fitted" && toastAt !== null;+ if (snap.state !== "countdown" && snap.state !== "capturing" && !toastVisible) return null;++ return (+ <div+ className="pos-abs"+ style={{+ top: 12,+ left: "50%",+ transform: "translateX(-50%)",+ zIndex: 100,+ pointerEvents: "none",+ minWidth: 260,+ textAlign: "center",+ background: "rgba(20, 20, 20, 0.85)",+ border: "1px solid #444",+ borderRadius: 6,+ padding: "10px 18px",+ color: "#ddd",+ userSelect: "none",+ }}+ >+ {snap.state === "countdown" && <CountdownBody remainingS={snap.countdown_remaining_s} />}+ {snap.state === "capturing" && <CapturingBody snap={snap} />}+ {toastVisible && <FittedBody snap={snap} />}+ </div>+ );+});++function CountdownBody({remainingS}: {remainingS: number}) {+ return (+ <>+ <div style={{fontSize: "0.75rem", letterSpacing: 2, color: "#aaa"}}>+ GET INTO POSITION+ </div>+ <div style={{fontSize: "2rem", fontWeight: "bold", lineHeight: 1.2}}>+ {Math.max(1, Math.ceil(remainingS))}+ </div>+ <div style={{fontSize: "0.7rem", color: "#888"}}>+ skeleton calibration starts at zero β hold still+ </div>+ </>+ );+}++function CapturingBody({snap}: {snap: SkeletonFitStateSnapshot}) {+ const progress = Math.min(1, snap.capture_good_streak / Math.max(1, snap.capture_required_good_frames));++ let hint: string;+ if (snap.visible_fraction < snap.capture_min_visible_fraction) {+ hint = "partial view β fitting what the cameras can see";+ } else if (snap.mean_error_px !== null && snap.mean_error_px > snap.capture_max_mean_error_px) {+ hint = "hold still β tracking is noisy";+ } else {+ hint = "capturing calibration framesβ¦";+ }++ return (+ <>+ <div style={{fontSize: "0.75rem", letterSpacing: 2, color: "#aaa"}}>HOLD STILL</div>+ <div+ style={{+ width: 220,+ height: 6,+ background: "#333",+ borderRadius: 3,+ margin: "8px auto",+ overflow: "hidden",+ }}+ >+ <div+ style={{+ width: `${progress * 100}%`,+ height: "100%",+ background: "#4da3ff",+ transition: "width 0.2s linear",+ }}+ />+ </div>+ <div style={{fontSize: "0.7rem", color: hint.endsWith("β¦") ? "#888" : "#e0a030"}}>+ {hint}+ </div>+ <div style={{fontSize: "0.65rem", color: "#666", marginTop: 4}}>+ finishes automatically in {Math.max(1, Math.ceil(snap.capture_timeout_remaining_s))}s+ </div>+ </>+ );+}++function FittedBody({snap}: {snap: SkeletonFitStateSnapshot}) {+ const deviation = snap.median_seed_deviation;+ const devPct = deviation !== null ? Math.round(deviation * 100) : null;+ const devHigh = deviation !== null && deviation > PRIOR_DEVIATION_WARN;++ return (+ <>+ <div style={{fontSize: "0.8rem", letterSpacing: 1, color: "#8fd18f"}}>+ SKELETON LOCKED β {snap.n_fitted_body_bones} bones fitted+ </div>+ {devPct !== null && (+ <div style={{fontSize: "0.7rem", color: devHigh ? "#e0a030" : "#888"}}>+ {devHigh+ ? `deviates ${devPct}% from priors β check subject height`+ : `${devPct}% from priors`}+ </div>+ )}+ </>+ );+}diff --git a/freemocap-ui/src/components/viewport3d/scene/ViewportOverlay.tsx b/freemocap-ui/src/components/viewport3d/scene/ViewportOverlay.tsxindex d7ce66f8..f347e639 100644--- a/freemocap-ui/src/components/viewport3d/scene/ViewportOverlay.tsx+++ b/freemocap-ui/src/components/viewport3d/scene/ViewportOverlay.tsx@@ -4,6 +4,7 @@ import { useViewportState } from "./ViewportStateContext";import IconButton from "@/components/ui-components/IconButton";import { useAppDispatch, useAppSelector } from "@/store/hooks";import { resetSkeletonFitter, selectIsPipelineConnected } from "@/store/slices/realtime";+import { SkeletonFitRitualIndicator } from "./SkeletonFitRitualIndicator";interface ViewportOverlayProps {onFitCamera: () => void;@@ -76,6 +77,7 @@ export function ViewportOverlay({return (<>+ {isRealtimeConnected && <SkeletonFitRitualIndicator />}<divclassName="viewport-options pos-abs top-0 left-0 p-2 br-1"style={{diff --git a/freemocap-ui/src/constants/server-urls.ts b/freemocap-ui/src/constants/server-urls.tsindex a865b9bd..c9fc382d 100644--- a/freemocap-ui/src/constants/server-urls.ts+++ b/freemocap-ui/src/constants/server-urls.ts@@ -90,6 +90,9 @@ class ServerUrls {stopPipeline: (pipelineId: string) => `${baseUrl}/freemocap/posthoc/pipeline/${encodeURIComponent(pipelineId)}`,stopAllPipelines: `${baseUrl}/freemocap/posthoc/pipeline`,+ // Telemetry+ trackTelemetry: `${baseUrl}/freemocap/telemetry/track`,+// Blender endpointsblenderDetect: `${baseUrl}/freemocap/blender/detect`,blenderExport: `${baseUrl}/freemocap/blender/export`,diff --git a/freemocap-ui/src/hooks/useHydrateDataFolder.ts b/freemocap-ui/src/hooks/useHydrateDataFolder.tsdeleted file mode 100644index 065529c7..00000000--- a/freemocap-ui/src/hooks/useHydrateDataFolder.ts+++ /dev/null@@ -1,41 +0,0 @@-import {useEffect, useRef} from 'react';-import {useElectronIPC} from '@/services/electron-ipc/electron-ipc';-import {useAppDispatch, useAppSelector} from '@/store';-import {recordingDirectoryChanged} from '@/store/slices/recording';-import {activeRecordingBaseDirectoryChanged} from '@/store/slices/active-recording';-import {recordingsDirFromBaseFolder} from '@/utils/dataFolder';--/**- * On startup, resolve the base data folder from the Electron main process and seed the recording- * directories with `<baseFolder>/recordings`. Only fills in directories the user has not already- * chosen (persisted values are left untouched). Runs once per app launch.- */-export function useHydrateDataFolder(): void {- const {isElectron, api} = useElectronIPC();- const dispatch = useAppDispatch();- const recordingDirectory = useAppSelector((s) => s.recording.recordingDirectory);- const activeBaseDirectory = useAppSelector((s) => s.activeRecording.baseDirectory);- const hasRun = useRef(false);-- useEffect(() => {- if (hasRun.current || !isElectron || !api) return;- hasRun.current = true;-- let cancelled = false;- (async () => {- try {- const baseFolder = await api.fileSystem.getBaseDataFolder.query();- if (cancelled || !baseFolder) return;- const recordingsDir = recordingsDirFromBaseFolder(baseFolder);- if (!recordingDirectory) dispatch(recordingDirectoryChanged(recordingsDir));- if (!activeBaseDirectory) dispatch(activeRecordingBaseDirectoryChanged(recordingsDir));- } catch (err) {- console.error('Failed to hydrate data folder from base folder:', err);- }- })();-- return () => {- cancelled = true;- };- }, [isElectron, api, dispatch, recordingDirectory, activeBaseDirectory]);-}diff --git a/freemocap-ui/src/hooks/useMenuActions.ts b/freemocap-ui/src/hooks/useMenuActions.tsindex c9625fa0..071724bd 100644--- a/freemocap-ui/src/hooks/useMenuActions.ts+++ b/freemocap-ui/src/hooks/useMenuActions.ts@@ -13,6 +13,7 @@ import {pipelineSnackbarShown} from '@/store/slices/pipelines';import {isElectron, useElectronIPC} from '@/services/electron-ipc/electron-ipc';import {recordingsDirFromBaseFolder} from '@/utils/dataFolder';import {SUPPORTED_LOCALES} from '@/i18n';+import {useTutorial} from '@/components/tutorial';import type {MenuAction} from '../../electron/main/services/menu-builder';// i18n keys that the menu builder needs for translated labels@@ -25,6 +26,7 @@ const MENU_LABEL_KEYS = ['menuLoadTestData','menuClearActiveRecording','menuHelp',+ 'menuTakeTour','menuDetectCameras','menuConnectCameras','menuCloseAllCameras',@@ -65,6 +67,7 @@ export function useMenuActions({ onToggleSidebar }: UseMenuActionsParams): voidconst navigate = useNavigate();const { t, i18n } = useTranslation();const { api } = useElectronIPC();+ const { startTour } = useTutorial();const isRecording = useAppSelector((state) => state.recording.isRecording);// const currentLocale = useAppSelector(selectLocale);@@ -164,6 +167,11 @@ export function useMenuActions({ onToggleSidebar }: UseMenuActionsParams): voidwindow.dispatchEvent(new CustomEvent('check-for-updates'));break;+ // Help+ case 'start-tutorial':+ startTour('getting-started');+ break;+// File actionscase 'open-recording-folder':dispatch(selectVideoLoadFolder());@@ -199,5 +207,5 @@ export function useMenuActions({ onToggleSidebar }: UseMenuActionsParams): void});return cleanup;- }, [dispatch, navigate, isRecording, onToggleSidebar, api]);+ }, [dispatch, navigate, isRecording, onToggleSidebar, api, startTour]);}diff --git a/freemocap-ui/src/i18n/locales/en-english.json b/freemocap-ui/src/i18n/locales/en-english.jsonindex fca0cbbd..3a4da0bb 100644--- a/freemocap-ui/src/i18n/locales/en-english.json+++ b/freemocap-ui/src/i18n/locales/en-english.json@@ -239,6 +239,7 @@"menuLoadTestData": "Load Test Data","menuClearActiveRecording": "Clear Active Recording","menuHelp": "Help",+ "menuTakeTour": "Take the Tour","menuDetectCameras": "Detect Cameras","menuConnectCameras": "Connect Cameras","menuCloseAllCameras": "Close All Cameras",@@ -268,5 +269,81 @@"checkForUpdates": "Check for Updates","upToDate": "You are up to date","updateError": "Update check failed",- "serverNotConnected": "Connect to server to enable controls"+ "serverNotConnected": "Connect to server to enable controls",+ "tour": {+ "take": "Take a quick tour",+ "replay": "Replay tour",+ "welcome": {+ "title": "Welcome to FreeMoCap",+ "text": "Let's walk the main path: connecting the local server, your cameras, the realtime pipeline, calibration, and your first recording. It only takes a minute.",+ "start": "Start the tour"+ },+ "tabs": {+ "title": "Streaming vs Playback",+ "text": "Last thing β these two tabs up top. Streaming (where you are now) is for live cameras and recording; your captures then show up under Playback, where you review and process them."+ },+ "server": {+ "title": "Server connection",+ "text": "FreeMoCap is a clientβserver app: this window talks to a FreeMoCap server running locally on your own computer. This panel shows that connection β it links up automatically, and you can toggle it here to reconnect."+ },+ "camera": {+ "title": "Connect your cameras",+ "text": "Once the server is connected, detect and connect your cameras here. Each camera has its own settings, and you can toggle whether it's included in the realtime pipeline."+ },+ "realtime": {+ "title": "Realtime pipeline",+ "text": "These controls run the live pipeline. Toggle 2D skeleton tracking, 3D triangulation, and filtering on or off, and choose which tracking model to use β all live as you stream."+ },+ "realtimeDeep": {+ "controls": {+ "title": "Turning it on & off",+ "text": "The lightning toggle turns the live pipeline fully on or off (it's not a pause β pausing the cameras is what pauses the pipeline, automatically). If you turn it on while your cameras are off, it connects your selected cameras first, then starts the pipeline. With it on, switch 2D skeleton tracking, 3D triangulation, and filtering on or off, and pick the tracking model β each stage adds detail (and compute), so turn off what you don't need."+ },+ "recording": {+ "title": "It never slows your recording",+ "text": "The realtime pipeline is designed so it can't interfere with recording. Even if the live preview can't keep up with your cameras' full frame rate, the videos saved to disk are captured at the full requested frame rate β so when you process a recording later, you get full-frame-rate data no matter how fast the live pipeline ran."+ }+ },+ "calibration": {+ "title": "Calibrate your cameras",+ "text": "To get 3D motion capture from multiple cameras, calibrate them first β this works out where each camera sits in space. (A single camera works without calibration.) See the guide to calibrate with a ChArUco board."+ },+ "recording": {+ "title": "Record your capture",+ "text": "When you're ready, hit Start Recording. Auto-process is on by default, so FreeMoCap runs motion capture automatically as soon as the recording finishes."+ },+ "finish": {+ "title": "You're all set!",+ "text": "That's the main path β server, cameras, pipeline, calibration, and recording. Dig into the docs for more, and replay this tour any time from the Welcome screen, Settings, or the Help menu.",+ "done": "Finish"+ },+ "serverDeep": {+ "status": {+ "title": "Connection status",+ "text": "The colored dot shows whether the local server is reachable, and the row below it shows the websocket β FreeMoCap is \"connected\" once that websocket is open."+ },+ "toggle": {+ "title": "Start, stop & reconnect",+ "text": "Open this panel to start or stop the local server and reconnect the websocket. It reconnects on its own, but this is where you take manual control if something gets stuck."+ }+ },+ "cameraDeep": {+ "detect": {+ "title": "Detect & connect",+ "text": "Detect scans for plugged-in cameras; Connect starts streaming from the ones you've selected. Each detected camera shows up as a row you can expand."+ },+ "settings": {+ "title": "Per-camera settings",+ "text": "Expand a camera to set its resolution, exposure and rotation, and use the toggles to include or exclude it from the capture group and the realtime pipeline."+ }+ },+ "controls": {+ "back": "Back",+ "next": "Next",+ "deeper": "Deeper",+ "skip": "Skip tour",+ "docs": "Read the calibration guide",+ "targetHidden": "Can't highlight this right now β it may be in a collapsed panel. Click Next to continue."+ }+ }}diff --git a/freemocap-ui/src/layout/BasePanelLayout.tsx b/freemocap-ui/src/layout/BasePanelLayout.tsxindex 248ebf37..0413a379 100644--- a/freemocap-ui/src/layout/BasePanelLayout.tsx+++ b/freemocap-ui/src/layout/BasePanelLayout.tsx@@ -17,6 +17,7 @@ import PromptTooltip from "@/components/ui-components/PromptTooltip";import { useServer } from "@/services/server/ServerContextProvider";import { useAppSelector } from "@/store";import { selectIsLoading } from "@/store/slices/cameras/cameras-selectors";+import { useTutorial } from "@/components/tutorial";export const BasePanelLayout = ({children,@@ -33,6 +34,9 @@ export const BasePanelLayout = ({const { isConnected, isFailed, connectedCameraIds } = useServer();const location = useLocation();const isCamerasLoading = useAppSelector(selectIsLoading);+ // While a guided tour runs, hide the ad-hoc onboarding tooltips so the tour's+ // own bubble is the only thing pointing at a shared target (e.g. camera:connect-camera).+ const { isTourActive } = useTutorial();useEffect(() => {bottomPanelRef.current?.collapse();@@ -73,7 +77,7 @@ export const BasePanelLayout = ({><PromptTooltipclassName={isFailed ? "" : "loading"}- show={!isConnected}+ show={!isConnected && !isTourActive}title={isFailed ? "Service Unavailable" : "Connecting..."}text={isFailed? "Make sure you have the service running"@@ -91,7 +95,8 @@ export const BasePanelLayout = ({!isFailed && // <-- optional extra safetylocation.pathname === "/streaming" &&connectedCameraIds.length === 0 &&- !isCamerasLoading+ !isCamerasLoading &&+ !isTourActive // <-- tour owns the stage while it runs}title="Connect Cameras"text="Make sure you have at least one camera plugged in, then hit Connect to start streaming."diff --git a/freemocap-ui/src/services/electron-ipc/electron-ipc-client.ts b/freemocap-ui/src/services/electron-ipc/electron-ipc-client.tsindex 250fc9fe..845ad04f 100644--- a/freemocap-ui/src/services/electron-ipc/electron-ipc-client.ts+++ b/freemocap-ui/src/services/electron-ipc/electron-ipc-client.ts@@ -5,6 +5,9 @@ import type {AppAPI} from '../../../electron/main/api';// Type for the electron API exposed via preloadinterface ElectronAPI {+ // Resolved synchronously at preload time β override-or-default, never empty.+ // See electron/main/base-folder.ts (getBaseDataFolder) and electron/preload/index.ts.+ baseDataFolder: string;invoke: (path: string, input?: any) => Promise<any>;onMenuAction: (callback: (action: string) => void) => () => void;sendMenuLabels: (params: Record<string, unknown>) => void;diff --git a/freemocap-ui/src/services/server/ServerContextProvider.tsx b/freemocap-ui/src/services/server/ServerContextProvider.tsxindex 33330ece..0764757d 100644--- a/freemocap-ui/src/services/server/ServerContextProvider.tsx+++ b/freemocap-ui/src/services/server/ServerContextProvider.tsx@@ -15,8 +15,10 @@ import {isFrontendPayload,isLogRecord,isPosthocProgress,+ isSkeletonFitState,isTrackerSchemas,} from "@/services/server/server-helpers/websocket-message-types";+import {SkeletonFitStateStore} from "@/services/server/server-helpers/skeleton-fit-state-store";import {TrackedObjectDefinition} from "@/services/server/server-helpers/tracked-object-definition";import {BLOCK_KIND,@@ -73,6 +75,7 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({childrconst canvasManagerRef = useRef<CanvasManager | null>(null);const framerateStoreRef = useRef<FramerateStore>(new FramerateStore());const logStoreRef = useRef<LogStore>(new LogStore());+ const skeletonFitStateStoreRef = useRef<SkeletonFitStateStore>(new SkeletonFitStateStore());// Latest server-side (backend) FPS stored in a ref for non-reactive accessconst serverFpsRef = useRef<number | null>(null);@@ -154,6 +157,7 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({childrpendingAckFrameNumberRef.current = null;lastCameraIdsRef.current = [];framerateStoreRef.current.clear();+ skeletonFitStateStoreRef.current.clear();keypointsRef.current = null;skeletonRef.current = null;trackerSchemasRef.current = {};@@ -456,6 +460,8 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({childr}} else if (isAppState(jsonData)) {store.dispatch(serverStateReceived(jsonData));+ } else if (isSkeletonFitState(jsonData)) {+ skeletonFitStateStoreRef.current.update(jsonData.pipelines);} else {console.warn('[WS] unhandled JSON message:', jsonData.message_type ?? '(no message_type)', jsonData);}@@ -511,6 +517,10 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({childrreturn logStoreRef.current;}, []);+ const getSkeletonFitStateStore = useCallback((): SkeletonFitStateStore => {+ return skeletonFitStateStoreRef.current;+ }, []);+const subscribeToKeypoints = useCallback((cb: KeypointsCallback): () => void => {keypointsSubscribersRef.current.add(cb);return () => { keypointsSubscribersRef.current.delete(cb); };@@ -583,6 +593,7 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({childrgetServerFps,getFramerateStore,getLogStore,+ getSkeletonFitStateStore,connectedCameraIds,updateServerConnection,subscribeToKeypoints,@@ -596,7 +607,7 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({childrtrackerSchemas,activeTrackerId,getActiveSchema,- }), [isConnected, isFailed, connectedCameraIds, trackerSchemas, activeTrackerId, connect, disconnect, sendWebsocketMessage, setCanvasForCamera, getFps, getServerFps, getFramerateStore, getLogStore, updateServerConnection, subscribeToKeypoints, subscribeToSkeleton, subscribeToCenterOfMass, subscribeToXcom, subscribeToBodyKinematics, getLatestKeypoints, getLatestSkeleton, setOverlayVisibility, getActiveSchema]);+ }), [isConnected, isFailed, connectedCameraIds, trackerSchemas, activeTrackerId, connect, disconnect, sendWebsocketMessage, setCanvasForCamera, getFps, getServerFps, getFramerateStore, getLogStore, getSkeletonFitStateStore, updateServerConnection, subscribeToKeypoints, subscribeToSkeleton, subscribeToCenterOfMass, subscribeToXcom, subscribeToBodyKinematics, getLatestKeypoints, getLatestSkeleton, setOverlayVisibility, getActiveSchema]);return (<ServerContext.Provider value={contextValue}>diff --git a/freemocap-ui/src/services/server/server-context.ts b/freemocap-ui/src/services/server/server-context.tsindex 25d0538b..70064dec 100644--- a/freemocap-ui/src/services/server/server-context.ts+++ b/freemocap-ui/src/services/server/server-context.ts@@ -1,6 +1,7 @@import { createContext, useContext } from 'react';import type { FramerateStore } from './server-helpers/framerate-store';import type { LogStore } from './server-helpers/log-store';+import type { SkeletonFitStateStore } from './server-helpers/skeleton-fit-state-store';import type { TrackedObjectDefinition } from './server-helpers/tracked-object-definition';import type { Point3d, BodyKinematics } from '@/components/viewport3d';import type { KeypointsCallback, KeypointsFrame } from '@/components/viewport3d/KeypointsSourceContext';@@ -18,6 +19,7 @@ export interface ServerContextValue {getServerFps: () => number | null;getFramerateStore: () => FramerateStore;getLogStore: () => LogStore;+ getSkeletonFitStateStore: () => SkeletonFitStateStore;connectedCameraIds: string[];updateServerConnection: (host: string, port: number) => void;subscribeToKeypoints: (cb: KeypointsCallback) => () => void;diff --git a/freemocap-ui/src/services/server/server-helpers/skeleton-fit-state-store.ts b/freemocap-ui/src/services/server/server-helpers/skeleton-fit-state-store.tsnew file mode 100644index 00000000..36c36095--- /dev/null+++ b/freemocap-ui/src/services/server/server-helpers/skeleton-fit-state-store.ts@@ -0,0 +1,35 @@+// src/services/server/server-helpers/skeleton-fit-state-store.ts+import type {SkeletonFitStateSnapshot} from "./websocket-message-types";++export type SkeletonFitStates = Record<string, SkeletonFitStateSnapshot | null>;++const EMPTY_STATES: SkeletonFitStates = {};++/**+ * Latest per-pipeline segment-fit ritual states, pushed over the websocket.+ * Lives in a ref β no Redux, no re-renders of the provider tree. Consumers+ * subscribe via useSyncExternalStore; the server only sends on change, so+ * notifications arrive exactly when the ritual does something.+ */+export class SkeletonFitStateStore {+ private states: SkeletonFitStates = EMPTY_STATES;+ private readonly listeners = new Set<() => void>();++ update(states: SkeletonFitStates): void {+ this.states = states;+ this.listeners.forEach((listener) => listener());+ }++ getSnapshot = (): SkeletonFitStates => this.states;++ subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ };++ clear(): void {+ this.update(EMPTY_STATES);+ }+}diff --git a/freemocap-ui/src/services/server/server-helpers/websocket-message-types.ts b/freemocap-ui/src/services/server/server-helpers/websocket-message-types.tsindex bff4c469..4f1f6e89 100644--- a/freemocap-ui/src/services/server/server-helpers/websocket-message-types.ts+++ b/freemocap-ui/src/services/server/server-helpers/websocket-message-types.ts@@ -89,6 +89,39 @@ export function isTrackerSchemas(data: any): data is TrackerSchemasMessage {);}+/**+ * Segment-fit calibration ritual state for one pipeline β pushed by the+ * backend whenever it changes (snake_case, straight off the dataclass).+ */+export interface SkeletonFitStateSnapshot {+ state: string; // "idle" | "countdown" | "capturing" | "fitted"+ countdown_remaining_s: number;+ capture_good_streak: number;+ capture_required_good_frames: number;+ capture_min_visible_fraction: number;+ capture_max_mean_error_px: number;+ capture_timeout_remaining_s: number;+ visible_fraction: number;+ mean_error_px: number | null;+ n_fitted_body_bones: number;+ median_seed_deviation: number | null;+}++export interface SkeletonFitStateWsMessage {+ message_type: 'skeleton_fit_state';+ pipelines: Record<string, SkeletonFitStateSnapshot | null>;+}++export function isSkeletonFitState(data: any): data is SkeletonFitStateWsMessage {+ return (+ data &&+ typeof data === 'object' &&+ data.message_type === 'skeleton_fit_state' &&+ data.pipelines &&+ typeof data.pipelines === 'object'+ );+}+export const PosthocProgressSchema = z.object({message_type: z.literal('posthoc_progress'),pipeline_id: z.string(),diff --git a/freemocap-ui/src/store/slices/active-recording/active-recording-slice.ts b/freemocap-ui/src/store/slices/active-recording/active-recording-slice.tsindex 23bafcac..b104c386 100644--- a/freemocap-ui/src/store/slices/active-recording/active-recording-slice.ts+++ b/freemocap-ui/src/store/slices/active-recording/active-recording-slice.ts@@ -4,6 +4,7 @@ import {startRecording, stopRecording} from '@/store/slices/recording/recording-import {buildRecordingStructure, RecordingStructure} from './recording-structure';import type {RecordingLayoutPresetName} from './layout-presets/layout-presets';import {loadFromStorage} from '@/store/persistence';+import {recordingsDirFromBaseFolder} from '@/utils/dataFolder';export type ActiveRecordingOrigin =| 'pending-capture'@@ -18,8 +19,18 @@ export interface ActiveRecordingState {layoutPreset: RecordingLayoutPresetName;}-// Empty until hydrated from the base data folder at startup (see useHydrateDataFolder).-const DEFAULT_BASE_DIRECTORY = '';+// The base directory must NEVER be empty β see the identical invariant (and full rationale) on+// DEFAULT_RECORDING_DIRECTORY in recording-slice.ts. Resolved synchronously from the same source.+const FALLBACK_BASE_DIRECTORY = '~/freemocap_data/recordings';++function resolveDefaultBaseDirectory(): string {+ const baseDataFolder = typeof window !== 'undefined' && window.electronAPI+ ? window.electronAPI.baseDataFolder+ : undefined;+ return baseDataFolder ? recordingsDirFromBaseFolder(baseDataFolder) : FALLBACK_BASE_DIRECTORY;+}++const DEFAULT_BASE_DIRECTORY = resolveDefaultBaseDirectory();const DEFAULT_LAYOUT_PRESET: RecordingLayoutPresetName = 'canonical';interface PersistedActiveRecording {@@ -29,9 +40,13 @@ interface PersistedActiveRecording {}const _persisted = loadFromStorage<PersistedActiveRecording | null>('activeRecording', null);+// A blank/whitespace persisted value means "not actually set" β never carry '' forward.+const _initialBaseDirectory = _persisted?.baseDirectory && _persisted.baseDirectory.trim()+ ? _persisted.baseDirectory+ : DEFAULT_BASE_DIRECTORY;const initialState: ActiveRecordingState = {- baseDirectory: _persisted?.baseDirectory ?? DEFAULT_BASE_DIRECTORY,+ baseDirectory: _initialBaseDirectory,recordingName: _persisted?.recordingName ?? null,// Normalize origin on restore β 'just-captured' and 'auto-latest' are transientorigin: _persisted?.recordingName ? 'browsed' : null,diff --git a/freemocap-ui/src/store/slices/calibration/calibration-thunks.ts b/freemocap-ui/src/store/slices/calibration/calibration-thunks.tsindex 4ea60cfa..82551a9f 100644--- a/freemocap-ui/src/store/slices/calibration/calibration-thunks.ts+++ b/freemocap-ui/src/store/slices/calibration/calibration-thunks.ts@@ -77,10 +77,10 @@ export const startCalibrationRecording = createAsyncThunk<// (that's what `calibrateRecording` does, to re-process an existing recording).// Using the active path here let new videos pile into an old recording folder,// mixing camera sets / frame counts and breaking posthoc calibration.+ //+ // recordingDirectory is guaranteed non-empty from store initialization onward+ // (see recording-slice.ts) β no need to guard it here.const recordingsRoot = state.recording.recordingDirectory;- if (!recordingsRoot) {- return rejectWithValue('Recordings directory is not set');- }const base = recordingsRoot.replace(/[\\/]+$/, '');const calibrationRecordingDirectory = `${base}/${getTimestampString()}_calibration`;diff --git a/freemocap-ui/src/store/slices/recording/recording-slice.ts b/freemocap-ui/src/store/slices/recording/recording-slice.tsindex 7975e4ee..0ab5a2d4 100644--- a/freemocap-ui/src/store/slices/recording/recording-slice.ts+++ b/freemocap-ui/src/store/slices/recording/recording-slice.ts@@ -4,6 +4,7 @@ import {ComputedRecordingPath, PendingOperation, RecordingConfig, RecordingInfo}import {startRecording, stopRecording} from './recording-thunks';import {loadFromStorage} from '@/store/persistence';import {getTimestampString} from './getTimestampString';+import {recordingsDirFromBaseFolder} from '@/utils/dataFolder';const computeRecordingPath = (recordingDirectory: string,@@ -42,8 +43,26 @@ const computeRecordingPath = (};};-// Empty until hydrated from the base data folder at startup (see useHydrateDataFolder).-const DEFAULT_RECORDING_DIRECTORY = '';+// The recording directory must NEVER be empty β it is always either the user's persisted+// override or a real path derived from the base data folder. The base data folder itself is+// resolved by Electron main (override-or-`~/freemocap_data`, see electron/main/base-folder.ts)+// and handed to the renderer *synchronously* at preload time (electron/preload/index.ts), so it+// is available before this module β and therefore this initial state β ever runs. There is no+// async hydration step and no window where this can be blank.+//+// The literal fallback below only activates when there is no Electron main process to ask at all+// (e.g. `npm run dev`'s bare Vite server opened directly in a browser tab) β a dev-only scenario+// with no real filesystem to resolve `~` against client-side.+const FALLBACK_RECORDING_DIRECTORY = '~/freemocap_data/recordings';++function resolveDefaultRecordingDirectory(): string {+ const baseDataFolder = typeof window !== 'undefined' && window.electronAPI+ ? window.electronAPI.baseDataFolder+ : undefined;+ return baseDataFolder ? recordingsDirFromBaseFolder(baseDataFolder) : FALLBACK_RECORDING_DIRECTORY;+}++const DEFAULT_RECORDING_DIRECTORY = resolveDefaultRecordingDirectory();const DEFAULT_RECORDING_CONFIG: RecordingConfig = {useDelayStart: false,@@ -61,10 +80,15 @@ const DEFAULT_RECORDING_CONFIG: RecordingConfig = {const _persistedConfig = loadFromStorage<RecordingConfig | null>('recording.config', null);const _persistedDirectory = loadFromStorage<string | null>('recording.directory', null);+// A blank/whitespace persisted value means "not actually set" (e.g. saved while this bug was+// live) β treat it the same as no persisted value at all, never carry '' forward.+const _initialRecordingDirectory = _persistedDirectory && _persistedDirectory.trim()+ ? _persistedDirectory+ : DEFAULT_RECORDING_DIRECTORY;const initialState: RecordingInfo = {isRecording: false,- recordingDirectory: _persistedDirectory ?? DEFAULT_RECORDING_DIRECTORY,+ recordingDirectory: _initialRecordingDirectory,recordingName: null,startedAt: null,duration: 0,@@ -73,7 +97,7 @@ const initialState: RecordingInfo = {computed: {recordingName: '',subfolderName: '',- fullRecordingPath: _persistedDirectory ?? DEFAULT_RECORDING_DIRECTORY,+ fullRecordingPath: _initialRecordingDirectory,},pendingOperation: null,countdown: null,diff --git a/freemocap-ui/src/styles/tutorial.css b/freemocap-ui/src/styles/tutorial.cssnew file mode 100644index 00000000..cedfad41--- /dev/null+++ b/freemocap-ui/src/styles/tutorial.css@@ -0,0 +1,104 @@+/* =========================================+ TUTORIAL / GUIDED TOUR+ Layering: app < spotlight dim (300) < pointer bubble (320) < fallback & overlay (340).+ FloatingOnboarding hard-codes z-index:99 inline on its portal, so these+ overrides use !important on the classes it forwards to that portal.+========================================= */++.prompt-tooltip-reference-container.tour-spotlight-layer {+ z-index: 300 !important;+}++.prompt-tooltip-reference-container.tour-bubble-layer {+ z-index: 320 !important;+}++/* The tour bubble carries its own nav row, so give it a little more room than+ the shared 248px tooltip width. */+.tour-bubble-layer .prompt-tooltip-container {+ min-width: 300px;+ max-width: 300px;+}++/* =========================================+ SPOTLIGHT β dim the app, ring the target+ Fills the target-sized box FloatingOnboarding positions for us. The box-shadow+ spread paints everything outside the target dark; the inner ring highlights it.+========================================= */++.tour-spotlight {+ width: 100%;+ height: 100%;+ border-radius: 8px;+ box-shadow:+ 0 0 0 3px var(--color-info, #4aa3ff),+ 0 0 0 9999px rgba(0, 0, 0, 0.55);+ transition: box-shadow 0.15s linear;+}++/* =========================================+ TOUR NAV β Back / Skip / Next, rendered on the bubble itself+========================================= */++.tour-nav {+ margin-top: 4px;+ padding-top: 8px;+ border-top: 1px solid var(--color-border, rgba(255, 255, 255, 0.12));+}++.tour-nav .tour-step-counter {+ white-space: nowrap;+}++/* Skip is a quiet, full-width affordance under the primary Back/Next row. */+.tour-nav .tour-skip-link {+ align-self: center;+ opacity: 0.75;+}++.tour-nav .tour-skip-link:hover {+ opacity: 1;+}++/* =========================================+ POINTER FALLBACK β centered card shown ONLY when the target can't be+ highlighted (collapsed panel, wrong route, not yet mounted). Carries the same+ TourNav controls so the tour can never soft-lock.+========================================= */++.tour-pointer-fallback {+ position: fixed;+ top: 96px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 340;+ width: 340px;+ max-width: 90vw;+}++.tour-control-caption {+ line-height: 1.3;+}++/* =========================================+ OVERLAY β centered modal for branch/info steps+ Sits above the spotlight/bubble layers so an intro/finish screen is unobstructed.+========================================= */++.tour-overlay {+ z-index: 340;+}++/* =========================================+ FIRST-RUN NUDGE β draw attention to the launch button until the tour is done+========================================= */++@keyframes tour-nudge-pulse {+ 0%, 100% { box-shadow: 0 0 0 0 rgba(74, 163, 255, 0.5); }+ 50% { box-shadow: 0 0 0 6px rgba(74, 163, 255, 0); }+}++.tour-nudge-pulse {+ border-radius: 6px;+ animation: tour-nudge-pulse 2.2s ease-in-out infinite;+}diff --git a/freemocap/api/http/realtime/realtime_router.py b/freemocap/api/http/realtime/realtime_router.pyindex fc7a0239..0e4ac020 100644--- a/freemocap/api/http/realtime/realtime_router.py+++ b/freemocap/api/http/realtime/realtime_router.py@@ -1,7 +1,7 @@import loggingfrom fastapi import APIRouter, Body, HTTPException, status-from pydantic import BaseModel, Field+from pydantic import BaseModel, ConfigDict, Fieldfrom skellycam.core.camera_group.camera_group import CameraConfigsfrom skellycam.core.types.type_overloads import CameraGroupIdString, CameraIdString@@ -11,6 +11,7 @@ from freemocap.core.pipeline.realtime.realtime_pipeline import RealtimePipelinefrom freemocap.pubsub.pubsub_topics import (SkeletonFitterResetMessage,SkeletonFitterResetTopic,+ SkeletonFitStateMessage,)logger = logging.getLogger(__name__)@@ -55,6 +56,37 @@ class RealtimePipelineCloseResponse(BaseModel):class RealtimePipelineUpdateRequest(BaseModel):config: RealtimePipelineConfig = Field(default_factory=RealtimePipelineConfig, examples=[RealtimePipelineConfig()])+class SkeletonFitStateResponse(BaseModel):+ model_config = ConfigDict(populate_by_name=True)++ state: str = Field(description="Ritual state: idle | countdown | capturing | fitted")+ countdown_remaining_s: float = Field(alias="countdownRemainingS")+ capture_good_streak: int = Field(alias="captureGoodStreak")+ capture_required_good_frames: int = Field(alias="captureRequiredGoodFrames")+ capture_min_visible_fraction: float = Field(alias="captureMinVisibleFraction")+ capture_max_mean_error_px: float = Field(alias="captureMaxMeanErrorPx")+ capture_timeout_remaining_s: float = Field(alias="captureTimeoutRemainingS")+ visible_fraction: float = Field(alias="visibleFraction")+ mean_error_px: float | None = Field(alias="meanErrorPx")+ n_fitted_body_bones: int = Field(alias="nFittedBodyBones")+ median_seed_deviation: float | None = Field(alias="medianSeedDeviation")++ @classmethod+ def from_message(cls, msg: SkeletonFitStateMessage) -> "SkeletonFitStateResponse":+ return cls(+ state=msg.state,+ countdown_remaining_s=msg.countdown_remaining_s,+ capture_good_streak=msg.capture_good_streak,+ capture_required_good_frames=msg.capture_required_good_frames,+ capture_min_visible_fraction=msg.capture_min_visible_fraction,+ capture_max_mean_error_px=msg.capture_max_mean_error_px,+ capture_timeout_remaining_s=msg.capture_timeout_remaining_s,+ visible_fraction=msg.visible_fraction,+ mean_error_px=msg.mean_error_px,+ n_fitted_body_bones=msg.n_fitted_body_bones,+ median_seed_deviation=msg.median_seed_deviation,+ )+@realtime_router.post("/apply",@@ -120,15 +152,16 @@ async def pipeline_close_endpoint() -> None:@realtime_router.post("/reset-skeleton-fitter",status_code=status.HTTP_204_NO_CONTENT,- summary="Reset the skeleton fitter β forget learned bone lengths and start over",+ summary="Arm the skeleton refit ritual β countdown, quality-gated capture, freeze",)async def reset_skeleton_fitter_endpoint() -> None:- """Fully reset the realtime skeleton fitter.+ """Arm the segment-fit calibration ritual on every live pipeline.- Signals every live pipeline to forget its learned per-bone lengths (the online- best-K-by-reprojection-error median estimates) and carried bone directions, so- the next frame re-seeds from anthropometric priors exactly as if the pipeline- had just started β no process restart needed. Fire-and-forget: 204 No Content.+ Each pipeline's fitter clears its learned bone lengths and enters the ritual:+ a countdown (so the subject can get into view and hold still), a quality-gated+ capture window (only consecutive good frames count), then a freeze that+ re-anchors each bone's trust region on the captured length. Poll+ `GET /realtime/skeleton-fitter-state` for progress. Fire-and-forget: 204 No Content."""logger.api("Received `realtime/reset-skeleton-fitter` POST request")try:@@ -149,3 +182,34 @@ async def reset_skeleton_fitter_endpoint() -> None:status_code=500,detail=f"Error resetting skeleton fitter: {type(e).__name__} - {e}",)+++@realtime_router.get(+ "/skeleton-fitter-state",+ summary="Current segment-fit ritual state per pipeline (idle/countdown/capturing/fitted)",+)+async def skeleton_fitter_state_endpoint() -> dict[str, SkeletonFitStateResponse | None]:+ """Latest segment-fit ritual state for every live pipeline.++ Values are None for pipelines whose fitter hasn't published a state yet+ (skeleton fitting disabled, or no frames processed since startup).+ """+ logger.api("Received `realtime/skeleton-fitter-state` GET request")+ try:+ app = get_freemocap_app()+ result: dict[str, SkeletonFitStateResponse | None] = {}+ for pipeline in app.realtime_pipeline_manager.pipelines.values():+ state = pipeline.get_latest_skeleton_fit_state()+ result[pipeline.id] = (+ SkeletonFitStateResponse.from_message(state)+ if state is not None+ else None+ )+ return result+ except Exception as e:+ logger.error(f"Error reading skeleton fitter state: {type(e).__name__} - {e}")+ logger.exception(e)+ raise HTTPException(+ status_code=500,+ detail=f"Error reading skeleton fitter state: {type(e).__name__} - {e}",+ )diff --git a/freemocap/api/http/telemetry/__init__.py b/freemocap/api/http/telemetry/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/freemocap/api/http/telemetry/telemetry_router.py b/freemocap/api/http/telemetry/telemetry_router.pynew file mode 100644index 00000000..6e921998--- /dev/null+++ b/freemocap/api/http/telemetry/telemetry_router.py@@ -0,0 +1,33 @@+import logging++from fastapi import APIRouter+from pydantic import BaseModel, Field++from freemocap.system.telemetry.telemetry import track_event++logger = logging.getLogger(__name__)+telemetry_router = APIRouter(prefix="/telemetry", tags=["Telemetry"])+++class TelemetryEventRequest(BaseModel):+ event_type: str = Field(+ alias="eventType",+ description="Event name, e.g. 'tour_started' or 'tour_step_viewed'.",+ )+ payload: dict[str, object] | None = Field(+ default=None,+ description="Optional anonymous event properties (no PII).",+ )+++@telemetry_router.post("/track", summary="Record an anonymous telemetry event")+def track_telemetry_event(request: TelemetryEventRequest) -> dict[str, bool]:+ """Forward a UI-originated event to the telemetry client.++ This is a no-op when the user has opted out of telemetry: track_event only+ forwards to the skellypings client when it was initialized, which happens+ solely when telemetry is enabled. The opt-in decision therefore lives in one+ place (telemetry_config.json) and the UI does not need to re-check it.+ """+ track_event(event_type=request.event_type, payload=request.payload)+ return {"ok": True}diff --git a/freemocap/api/routers.py b/freemocap/api/routers.pyindex a038b91c..36234109 100644--- a/freemocap/api/routers.py+++ b/freemocap/api/routers.py@@ -8,6 +8,7 @@ from freemocap.api.http.calibration.calibration_router import calibration_routerfrom freemocap.api.http.mocap.mocap_router import mocap_routerfrom freemocap.api.http.posthoc.posthoc_router import posthoc_routerfrom freemocap.api.http.realtime.realtime_router import realtime_router+from freemocap.api.http.telemetry.telemetry_router import telemetry_routerAPP_ROUTERS = [health_router,shutdown_router]@@ -21,5 +22,6 @@ FREEMOCAP_ROUTERS = [realtime_router,mocap_router,posthoc_router,blender_router,- playback_router+ playback_router,+ telemetry_router]diff --git a/freemocap/api/websocket/websocket_message_types.py b/freemocap/api/websocket/websocket_message_types.pyindex 9df4acbe..ee646e9d 100644--- a/freemocap/api/websocket/websocket_message_types.py+++ b/freemocap/api/websocket/websocket_message_types.py@@ -12,3 +12,4 @@ class WebsocketMessageType(str, enum.Enum):LOG_RECORD = "log_record"TRACKER_SCHEMAS = "tracker_schemas"APP_STATE = "app_state"+ SKELETON_FIT_STATE = "skeleton_fit_state"diff --git a/freemocap/api/websocket/websocket_server.py b/freemocap/api/websocket/websocket_server.pyindex cf315512..5b39e85c 100644--- a/freemocap/api/websocket/websocket_server.py+++ b/freemocap/api/websocket/websocket_server.py@@ -21,6 +21,7 @@ from starlette.websockets import WebSocket, WebSocketState, WebSocketDisconnectfrom freemocap.api.websocket.tracker_schema_message import TrackerSchemasMessage, collect_active_tracker_schemasfrom freemocap.api.websocket.websocket_message_types import WebsocketMessageTypefrom freemocap.app.freemocap_application import FreemocapApplication, get_freemocap_app+from freemocap.pubsub.pubsub_topics import SkeletonFitStateMessagefrom freemocap.utilities.wait_functions import await_10msfrom skellycam.core.types.type_overloads import CameraGroupIdString, FrameNumberInt@@ -158,6 +159,10 @@ class WebsocketServer:self._app_state_sender(),name="WebsocketAppStateSender",),+ asyncio.create_task(+ self._skeleton_fit_state_sender(),+ name="WebsocketSkeletonFitStateSender",+ ),]try:@@ -199,6 +204,38 @@ class WebsocketServer:self._global_kill_flag.value = Trueraise+ async def _skeleton_fit_state_sender(self):+ """Push per-pipeline segment-fit ritual state whenever it changes.++ Drives the frontend's calibration-ritual overlay (countdown β hold-+ still capture β locked) with no HTTP polling. States only change while+ a ritual runs, so an idle fitter costs zero messages.+ """+ logger.info("Starting skeleton-fit-state sender task...")+ previous: dict[str, SkeletonFitStateMessage | None] | None = None+ try:+ while self.should_continue:+ states = {+ pipeline.id: pipeline.get_latest_skeleton_fit_state()+ for pipeline in self._app.realtime_pipeline_manager.pipelines.values()+ }+ if previous is None or states != previous:+ await self._send_msgspec_json({+ "message_type": WebsocketMessageType.SKELETON_FIT_STATE,+ "pipelines": states,+ })+ await asyncio.sleep(0.25)+ previous = states+ except asyncio.CancelledError:+ pass+ except WebSocketDisconnect:+ logger.info("Client disconnected, ending skeleton-fit-state sender task...")+ except Exception as e:+ logger.exception(f"Error in skeleton-fit-state sender: {e.__class__}: {e}")+ self._websocket_should_continue = False+ self._global_kill_flag.value = True+ raise+def last_frame_acknowledged(self) -> bool:if self.last_sent_frame_number == -1:return Truediff --git a/freemocap/core/pipeline/realtime/camera_node.py b/freemocap/core/pipeline/realtime/camera_node.pyindex 3e95e1cb..362ecd44 100644--- a/freemocap/core/pipeline/realtime/camera_node.py+++ b/freemocap/core/pipeline/realtime/camera_node.py@@ -302,7 +302,7 @@ class CameraNode(SourceNode):raw_keypoints=raw_2d,)xyz = kpts.xyz- for name, coords in filtered_2d.items():+ for name, coords in filtered_2d.positions.items():try:idx = kpts.index_of(name)xyz[idx, 0] = coords[0]diff --git a/freemocap/core/pipeline/realtime/realtime_aggregator_node.py b/freemocap/core/pipeline/realtime/realtime_aggregator_node.pyindex ef575fbb..94d5b9e5 100644--- a/freemocap/core/pipeline/realtime/realtime_aggregator_node.py+++ b/freemocap/core/pipeline/realtime/realtime_aggregator_node.py@@ -14,10 +14,11 @@ the new calibration is loaded and the skeleton filter + velocity gate are reset.Rigid-body correction (``RealtimeSkeletonRigidifier``) runs on the triangulated3D points: each bone's length is estimated online (a best-K-by-reprojection-error-median, seeded from anthropometry) and enforced by a single closed-form forward-pass. The fitter is fully reset on calibration reload (and on demand via the-reset signal): both the carried directions and the learned lengths are dropped,-so it re-fits from anthropometric seeds.+median, seeded from anthropometry and bounded to a trust region around the seed)+and enforced by a single closed-form forward pass. Only real (non-extrapolated)+keypoints teach lengths. The reset signal arms a calibration ritual β countdown,+quality-gated capture, freeze β instead of re-fitting on the next frame; the+ritual state is published every frame on SkeletonFitStateTopic."""import loggingimport multiprocessing.synchronize@@ -59,6 +60,7 @@ from freemocap.core.pipeline.realtime.realtime_pipeline_config import RealtimePifrom freemocap.core.pipeline.pipeline_stage_timer import PipelineStageTimerfrom freemocap.core.pipeline.pipeline_timing_reporter import PipelineTimingReporterfrom freemocap.core.tasks.calibration.shared.calibration_state import CalibrationStateTracker+from freemocap.core.tasks.triangulation.helpers.angulation_result import AngulationResultfrom freemocap.core.tasks.mocap.realtime_filtering.realtime_point_gate import RealtimePointGate, \GateResultfrom freemocap.core.tasks.mocap.realtime_filtering.realtime_filter_config import RealtimeFilterConfig@@ -77,6 +79,8 @@ from freemocap.pubsub.pubsub_topics import (SkeletonInferenceResultMessage,SkeletonInferenceResultTopic,PipelineTimingTopic,+ SkeletonFitStateMessage,+ SkeletonFitStateTopic,)# Cap on how many pending skeleton-inference results we hold while waiting for@@ -98,15 +102,18 @@ logger = logging.getLogger(__name__)# How often (seconds) to poll the calibration file for changesCALIBRATION_POLL_INTERVAL_SECONDS: float = 1.0-def _merge_triangulated_arrays(+def _merge_angulation(*,- triangulated: dict[str, np.ndarray] | None,- into: dict[str, np.ndarray],+ angulation: AngulationResult | None,+ into_points: dict[str, np.ndarray],+ into_errors: dict[str, float],) -> None:- """Merge triangulated 3D point arrays into the output dict, skipping NaN entries."""- if triangulated is None:+ """Merge one frame's triangulated points and their reprojection errors into+ the output dicts, skipping NaN entries. Error-less results (single-camera+ planar projection) merge points only."""+ if angulation is None:return- for point_name, coords in triangulated.items():+ for point_name, coords in angulation.points.items():if not isinstance(coords, np.ndarray):raise TypeError(f"Unexpected type for triangulated point '{point_name}': "@@ -114,7 +121,9 @@ def _merge_triangulated_arrays()if np.any(np.isnan(coords)):continue- into[point_name] = coords+ into_points[point_name] = coords+ if angulation.errors_px is not None and point_name in angulation.errors_px:+ into_errors[point_name] = angulation.errors_px[point_name]@dataclass@@ -170,6 +179,9 @@ class RealtimeAggregatorNode(AggregatorNode):result_ready_event=result_ready_event,result_consumed_event=result_consumed_event,skeleton_fitter_reset_sub=skeleton_fitter_reset_sub,+ skeleton_fit_state_pub=pubsub.get_publication_queue(+ SkeletonFitStateTopic,+ ),),)return cls(@@ -196,6 +208,7 @@ class RealtimeAggregatorNode(AggregatorNode):result_ready_event: multiprocessing.synchronize.Event,result_consumed_event: multiprocessing.synchronize.Event,skeleton_fitter_reset_sub: TopicSubscriptionQueue,+ skeleton_fit_state_pub: TopicPublicationQueue,) -> None:logger.debug(f"RealtimeAggregationNode [{camera_group_id}] initializing")aggregator_config = pipeline_config.aggregator_config@@ -242,14 +255,25 @@ class RealtimeAggregatorNode(AggregatorNode):# length estimators + forward-pass tree rigidifiers). Loaded once at# init; the per-frame hot path is pure numpy.skeleton_rigidifier: RealtimeSkeletonRigidifier | None = None+ rigidifier_filter_config: RealtimeFilterConfig | None = Noneif aggregator_config.skeleton_fitting_enabled:skeleton_rigidifier = RealtimeSkeletonRigidifier.create(detector_type=detector_type,height_mm=filter_config.height_mm,buffer_capacity=filter_config.segment_length_buffer_capacity,decay_tau_s=filter_config.segment_length_decay_s,- plausibility_tol=filter_config.segment_length_plausibility_tol,+ fit_ratio=filter_config.segment_length_fit_ratio,+ min_samples=filter_config.segment_length_min_samples,+ agreement_tol=filter_config.segment_length_agreement_tol,+ max_reprojection_error=filter_config.segment_length_max_reprojection_error_px,+ countdown_s=filter_config.calibration_countdown_s,+ capture_min_visible_fraction=filter_config.calibration_capture_min_visible_fraction,+ capture_max_mean_error_px=filter_config.calibration_capture_max_mean_error_px,+ capture_consecutive_good_frames=filter_config.calibration_capture_consecutive_good_frames,+ capture_update_min_visible_fraction=filter_config.calibration_capture_update_min_visible_fraction,+ capture_timeout_s=filter_config.calibration_capture_timeout_s,)+ rigidifier_filter_config = filter_configlogger.debug(f"RealtimeAggregationNode [{camera_group_id}] skeleton rigidifier created "f"(body bones: {len(skeleton_rigidifier.body_bone_lengths)}, "@@ -356,21 +380,43 @@ class RealtimeAggregatorNode(AggregatorNode):else:biomechanics = None+ # Recreate the rigidifier when the detector naming changes or+ # any fit parameter changed β silently stale fit params are+ # worse than a one-time canonical-model reload.+ filter_config_changed = (+ rigidifier_filter_config is not None+ and filter_config != rigidifier_filter_config+ )if aggregator_config.skeleton_fitting_enabled:- if skeleton_rigidifier is None or detector_type_changed:+ if (+ skeleton_rigidifier is None+ or detector_type_changed+ or filter_config_changed+ ):skeleton_rigidifier = RealtimeSkeletonRigidifier.create(detector_type=detector_type,height_mm=filter_config.height_mm,buffer_capacity=filter_config.segment_length_buffer_capacity,decay_tau_s=filter_config.segment_length_decay_s,- plausibility_tol=filter_config.segment_length_plausibility_tol,+ fit_ratio=filter_config.segment_length_fit_ratio,+ min_samples=filter_config.segment_length_min_samples,+ agreement_tol=filter_config.segment_length_agreement_tol,+ max_reprojection_error=filter_config.segment_length_max_reprojection_error_px,+ countdown_s=filter_config.calibration_countdown_s,+ capture_min_visible_fraction=filter_config.calibration_capture_min_visible_fraction,+ capture_max_mean_error_px=filter_config.calibration_capture_max_mean_error_px,+ capture_consecutive_good_frames=filter_config.calibration_capture_consecutive_good_frames,+ capture_update_min_visible_fraction=filter_config.calibration_capture_update_min_visible_fraction,+ capture_timeout_s=filter_config.calibration_capture_timeout_s,)+ rigidifier_filter_config = filter_configlogger.info(f"RealtimeAggregationNode [{camera_group_id}] "f"(re)created skeleton rigidifier for detector_type={detector_type}")else:skeleton_rigidifier = None+ rigidifier_filter_config = None# ---- Handle skeleton fitter reset signals ----# Drain unconditionally so the queue can't grow while skeleton@@ -383,10 +429,10 @@ class RealtimeAggregatorNode(AggregatorNode):breakreset_requested = Trueif reset_requested and skeleton_rigidifier is not None:- skeleton_rigidifier.reset()+ skeleton_rigidifier.request_refit()logger.info(- f"RealtimeAggregationNode [{camera_group_id}] skeleton fitter "- f"reset β forgot learned bone lengths + directions (fresh start)"+ f"RealtimeAggregationNode [{camera_group_id}] segment-fit "+ f"ritual armed (countdown β capture β freeze)")# ---- Periodically check if calibration file changed on disk ----@@ -404,11 +450,11 @@ class RealtimeAggregatorNode(AggregatorNode):prev_com = Noneprev_com_time = Nonestreaming_kinematics.reset()- # New calibration β full reset of the fitter: the lengths- # were learned under the old calibration, so re-fit from- # scratch (anthropometric seeds) under the new one.+ # New calibration β re-arm the refit ritual: the lengths+ # were learned under the old calibration, so capture+ # fresh ones under the new one.if skeleton_rigidifier is not None:- skeleton_rigidifier.reset()+ skeleton_rigidifier.request_refit()# ---- Request new frames if ready ----if not camera_group_shm.valid:@@ -565,8 +611,11 @@ class RealtimeAggregatorNode(AggregatorNode):# All processing stays in dict[str, ndarray] until final# conversion to Point3d for the output message.raw_keypoints: dict[str, np.ndarray] = {}+ raw_errors_px: dict[str, float] = {}filtered_keypoints: dict[str, np.ndarray] = {}+ measured_keypoints: dict[str, np.ndarray] = {}skeleton_keypoints: dict[str, np.ndarray] = {}+ frame_time = time.perf_counter()com_result: CenterOfMassResult | None = Nonexcom: Point3d | None = Nonebody_kinematics = None@@ -581,14 +630,15 @@ class RealtimeAggregatorNode(AggregatorNode):}if skeleton_observations_by_camera:t0 = time.perf_counter() if timer is not None else 0.0- _merge_triangulated_arrays(- triangulated=calibration.try_angulate(+ _merge_angulation(+ angulation=calibration.try_angulate(frame_number=last_received_frame,frame_observations_by_camera=skeleton_observations_by_camera,max_reprojection_error_px=filter_config.max_reprojection_error_px,triangulation_config=aggregator_config.triangulation_config,),- into=raw_keypoints,+ into_points=raw_keypoints,+ into_errors=raw_errors_px,)if timer is not None:timer.record("skeleton_triangulation", (time.perf_counter() - t0) * 1e3)@@ -602,14 +652,15 @@ class RealtimeAggregatorNode(AggregatorNode):}if charuco_observations_by_camera:t0 = time.perf_counter() if timer is not None else 0.0- _merge_triangulated_arrays(- triangulated=calibration.try_angulate(+ _merge_angulation(+ angulation=calibration.try_angulate(frame_number=last_received_frame,frame_observations_by_camera=charuco_observations_by_camera,max_reprojection_error_px=filter_config.max_reprojection_error_px,triangulation_config=aggregator_config.triangulation_config,),- into=raw_keypoints,+ into_points=raw_keypoints,+ into_errors=raw_errors_px,)if timer is not None:timer.record("charuco_triangulation", (time.perf_counter() - t0) * 1e3)@@ -627,10 +678,18 @@ class RealtimeAggregatorNode(AggregatorNode):# One Euro filter: smooth raw keypoints and gap-fill brief occlusionsif raw_keypoints:t0 = time.perf_counter() if timer is not None else 0.0- filtered_keypoints = keypoint_filter.filter(- t=time.perf_counter(),+ filter_result = keypoint_filter.filter(+ t=frame_time,raw_keypoints=raw_keypoints,)+ filtered_keypoints = filter_result.positions+ # Real measurements only: gap-filled (extrapolated)+ # points still display, but never teach bone lengths.+ measured_keypoints = {+ name: pos+ for name, pos in filter_result.positions.items()+ if name not in filter_result.predicted_names+ }if timer is not None:timer.record("keypoint_filter", (time.perf_counter() - t0) * 1e3)@@ -639,13 +698,12 @@ class RealtimeAggregatorNode(AggregatorNode):if raw_keypoints:t0 = time.perf_counter() if timer is not None else 0.0gate_result: GateResult = point_gate.gate(- t=time.perf_counter(),+ t=frame_time,points=raw_keypoints,)- _merge_triangulated_arrays(- triangulated=gate_result.positions,- into=filtered_keypoints,- )+ for point_name, coords in gate_result.positions.items():+ if not np.any(np.isnan(coords)):+ filtered_keypoints[point_name] = coordsif timer is not None:timer.record("velocity_gate", (time.perf_counter() - t0) * 1e3)@@ -655,7 +713,17 @@ class RealtimeAggregatorNode(AggregatorNode):and filtered_keypoints):t0 = time.perf_counter() if timer is not None else 0.0- rigid_result = skeleton_rigidifier.rigidify_frame(filtered_keypoints)+ rigid_result = skeleton_rigidifier.rigidify_frame(+ filtered_keypoints,+ measured=measured_keypoints,+ t=frame_time,+ errors=raw_errors_px if raw_errors_px else None,+ )+ skeleton_fit_state_pub.put(+ SkeletonFitStateMessage.from_snapshot(+ skeleton_rigidifier.fit_state+ )+ )if timer is not None:timer.record("skeleton_fitting", (time.perf_counter() - t0) * 1e3)@@ -747,18 +815,18 @@ class RealtimeAggregatorNode(AggregatorNode):>= proportion_report.thresholds.min_assessable_segments):drift = proportion_report.human_shape_violations(check_rigidity=False)- if drift:- logger.warning(- f"RealtimeAggregationNode [{camera_group_id}] "- f"body-proportion drift: " + "; ".join(drift)- )- else:- logger.debug(- f"RealtimeAggregationNode [{camera_group_id}] body "- f"proportions OK β implied height "- f"{proportion_report.implied_height_median_mm:.0f}mm "- f"(cv {proportion_report.implied_height_cv:.2f})"- )+ # if drift:+ # logger.warning(+ # f"RealtimeAggregationNode [{camera_group_id}] "+ # f"body-proportion drift: " + "; ".join(drift)+ # )+ # else:+ # logger.debug(+ # f"RealtimeAggregationNode [{camera_group_id}] body "+ # f"proportions OK β implied height "+ # f"{proportion_report.implied_height_median_mm:.0f}mm "+ # f"(cv {proportion_report.implied_height_cv:.2f})"+ # )# ---- Publish aggregated output ----aggregation_output_pub.put(diff --git a/freemocap/core/pipeline/realtime/realtime_keypoint_filter.py b/freemocap/core/pipeline/realtime/realtime_keypoint_filter.pyindex 9871da15..b58400fe 100644--- a/freemocap/core/pipeline/realtime/realtime_keypoint_filter.py+++ b/freemocap/core/pipeline/realtime/realtime_keypoint_filter.py@@ -5,6 +5,10 @@ Applies per-keypoint One Euro smoothing to 2D or 3D positions and predicts(extrapolates) positions for keypoints that temporarily disappear, so theoutput stream doesn't blink when tracking is lost for a few frames.+Predicted positions are extrapolations, not measurements: every ``filter``+call reports which keypoints were predicted this frame so downstream consumers+(bone-length estimation) can exclude them while still using them for display.+Works on ``dict[str, ndarray(dims,)]`` β set ``dims=2`` for pixel-space(camera node) or ``dims=3`` for world-space (aggregator)."""@@ -19,6 +23,22 @@ from freemocap.core.tasks.mocap.realtime_filtering.one_euro_filter import OneEurlogger = logging.getLogger(__name__)+@dataclass(slots=True, frozen=True)+class FilteredKeypoints:+ """Smoothed keypoints for one frame, with provenance.++ positions : dict[str, ndarray(dims,)]+ Smoothed positions; includes extrapolations for recently-seen+ keypoints absent this frame.+ predicted_names : frozenset[str]+ Names whose position this frame is an extrapolation, not a+ measurement. Must not feed length estimation.+ """++ positions: dict[str, np.ndarray]+ predicted_names: frozenset[str]++@dataclassclass RealtimeKeypointFilter:"""One Euro filter applied per-keypoint with velocity-decay gap filling.@@ -49,8 +69,8 @@ class RealtimeKeypointFilter:# ------------------------------------------------------------------def filter(self, *, t: float, raw_keypoints: dict[str, np.ndarray],- ) -> dict[str, np.ndarray]:- """Return smoothed + gap-filled keypoints.+ ) -> FilteredKeypoints:+ """Return smoothed + gap-filled keypoints with predicted-name provenance.Args:t: Monotonic timestamp in seconds.@@ -59,15 +79,16 @@ class RealtimeKeypointFilter:responsible for pre-filtering.Returns:- dict mapping point name β filtered ``(dims,)`` ndarray.- Includes predictions for recently-seen keypoints absent this frame.+ ``FilteredKeypoints`` β smoothed positions including predictions+ for recently-seen keypoints absent this frame, plus the set of+ names that were predicted rather than observed."""if self._last_t is not None and t <= self._last_t:logger.warning(f"Non-monotonic timestamp: t={t} <= last_t={self._last_t}. "f"Skipping filter for this frame.")- return raw_keypoints+ return FilteredKeypoints(positions=raw_keypoints, predicted_names=frozenset())self._last_t = tresult: dict[str, np.ndarray] = {}@@ -95,6 +116,7 @@ class RealtimeKeypointFilter:])# Predict keypoints absent this frame (gap filling).+ predicted: set[str] = set()for name, filts in self._filters.items():if name in raw_keypoints:continue@@ -105,8 +127,9 @@ class RealtimeKeypointFilter:for i in range(self.dims)])self._prediction_counts[name] = count + 1+ predicted.add(name)- return result+ return FilteredKeypoints(positions=result, predicted_names=frozenset(predicted))def reset(self) -> None:"""Clear all filter state (call on calibration / coordinate change)."""diff --git a/freemocap/core/pipeline/realtime/realtime_pipeline.py b/freemocap/core/pipeline/realtime/realtime_pipeline.pyindex f3ee9d1b..51deeb10 100644--- a/freemocap/core/pipeline/realtime/realtime_pipeline.py+++ b/freemocap/core/pipeline/realtime/realtime_pipeline.py@@ -42,6 +42,8 @@ from freemocap.pubsub.pubsub_topics import (PipelineConfigUpdateMessage,PipelineConfigUpdateTopic,SkeletonFitterResetTopic,+ SkeletonFitStateMessage,+ SkeletonFitStateTopic,)logger = logging.getLogger(__name__)@@ -66,6 +68,7 @@ class RealtimePipeline:skeleton_inference_node: RealtimeSkeletonInferenceNode | Nonecharuco_recorder_node: CharucoRecorderNode | Noneaggregation_output_subscription: TopicSubscriptionQueue+ skeleton_fit_state_subscription: TopicSubscriptionQueueresult_ready_event: multiprocessing.synchronize.Eventresult_consumed_event: multiprocessing.synchronize.Eventipc: PipelineIPC@@ -75,6 +78,7 @@ class RealtimePipeline:# Config stashed while a calibration recording temporarily forces Charuco-only# mode (skeleton inference paused). None whenever not in that mode._pre_calibration_config: RealtimePipelineConfig | None = None+ _latest_fit_state: SkeletonFitStateMessage | None = None@propertydef alive(self) -> bool:@@ -193,6 +197,9 @@ class RealtimePipeline:skeleton_fitter_reset_sub = pubsub.get_subscription(SkeletonFitterResetTopic,)+ skeleton_fit_state_subscription = pubsub.get_subscription(+ SkeletonFitStateTopic,+ )aggregation_node = RealtimeAggregatorNode.create(camera_group_id=camera_group.id,@@ -220,6 +227,7 @@ class RealtimePipeline:skeleton_inference_node=skeleton_inference_node,charuco_recorder_node=charuco_recorder_node,aggregation_output_subscription=aggregation_output_subscription,+ skeleton_fit_state_subscription=skeleton_fit_state_subscription,result_ready_event=result_ready_event,result_consumed_event=result_consumed_event,ipc=ipc,@@ -426,6 +434,16 @@ class RealtimePipeline:"""return await asyncio.to_thread(self.result_ready_event.wait, timeout)+ def get_latest_skeleton_fit_state(self) -> SkeletonFitStateMessage | None:+ """Newest segment-fit ritual state (drains the subscription to latest),+ or None if the fitter hasn't published one yet."""+ while True:+ try:+ self._latest_fit_state = self.skeleton_fit_state_subscription.get_nowait()+ except Empty:+ break+ return self._latest_fit_state+def get_latest_frontend_payload(self,if_newer_than: FrameNumberInt,diff --git a/freemocap/core/tasks/calibration/shared/calibration_state.py b/freemocap/core/tasks/calibration/shared/calibration_state.pyindex a2e4a362..eea900e1 100644--- a/freemocap/core/tasks/calibration/shared/calibration_state.py+++ b/freemocap/core/tasks/calibration/shared/calibration_state.py@@ -20,6 +20,7 @@ from skellytracker.core.data_primitives.observation import Observationfrom freemocap.core.tasks.calibration.shared.calibration_result import CalibrationResultfrom freemocap.core.tasks.calibration.shared.calibration_paths import get_last_successful_calibration_toml_pathfrom freemocap.core.tasks.calibration.shared.camera_id_resolution import resolve_camera_id_or_raise+from freemocap.core.tasks.triangulation.helpers.angulation_result import AngulationResultfrom freemocap.core.tasks.triangulation.helpers.project_single_camera import project_2d_observation_to_3dfrom freemocap.core.tasks.triangulation.helpers.triangulation_config import TriangulationConfigfrom freemocap.core.tasks.triangulation.triangulator import Triangulator@@ -211,22 +212,27 @@ class CalibrationStateTracker:frame_observations_by_camera: dict[CameraIdString, Observation],max_reprojection_error_px: float,triangulation_config: TriangulationConfig | None = None,- ) -> dict[str, NDArray[np.float64]] | None:+ ) -> AngulationResult | None:"""Attempt triangulation with reprojection error gating.Uses to_keypoints() to get named 2D observations from each camera,finds points visible in β₯2 cameras, triangulates via DLT, and rejectspoints whose mean reprojection error exceeds max_reprojection_error_px.- Returns the triangulated 3D points as a dict of {point_name: xyz},- or None if no valid calibration is loaded or triangulation failed.+ Returns an ``AngulationResult`` β triangulated 3D points plus their+ per-point mean reprojection errors (None on the single-camera planar+ path, where reprojection error is undefined) β or None if no valid+ calibration is loaded or triangulation failed."""if not self.is_valid:# Single-camera: projection doesn't need calibrationif len(frame_observations_by_camera) == 1:obs = next(iter(frame_observations_by_camera.values()))self._consecutive_failure_count = 0- return project_2d_observation_to_3d(observation=obs)+ return AngulationResult(+ points=project_2d_observation_to_3d(observation=obs),+ errors_px=None,+ )return Noneif triangulation_config is None:@@ -253,12 +259,12 @@ class CalibrationStateTracker:matched_obs_by_cam[self._cam_id_name_cache[cam_id]] = obsif len(matched_obs_by_cam) == 0:- return {}+ return AngulationResult(points={}, errors_px={})if len(matched_obs_by_cam) == 1:obs = next(iter(matched_obs_by_cam.values()))result = project_2d_observation_to_3d(observation=obs)self._consecutive_failure_count = 0- return result+ return AngulationResult(points=result, errors_px=None)# Reuse a cached sub-triangulator for this camera subset; only build# a new one when we see a novel active-camera combination.@@ -303,7 +309,7 @@ class CalibrationStateTracker:f"(all {len(canonical_names)} keypoints are NaN in at least {n_cameras - 1} cameras). "f"Check that the person is visible to multiple cameras and confidence gating is not too aggressive.")- return {}+ return AngulationResult(points={}, errors_px={})if not bool(keep_mask.all()):stacked = stacked[:, keep_mask, :]point_names_seq = tuple(@@ -343,22 +349,25 @@ class CalibrationStateTracker:points_3d[bad_mask] = np.nan# self._timer.record("mean_reproj_error", (time.perf_counter() - _t0) * 1e3)- # Build result dict, excluding NaN points.- # Strip the stage prefix that to_keypoints() adds (e.g. "body.nose" β "nose")- # so downstream code sees the canonical unprefixed names.+ # Build result, excluding NaN points. Strip the stage prefix that+ # to_keypoints() adds (e.g. "body.nose" β "nose") so downstream code+ # sees the canonical unprefixed names. Each surviving point keeps+ # its mean reprojection error alongside its position._t0 = time.perf_counter()valid_pt_mask = ~np.isnan(points_3d).any(axis=1)- result: dict[str, NDArray[np.float64]] = {- _strip_stage_prefix(name): points_3d[i]- for i, name in enumerate(point_names_seq)- if valid_pt_mask[i]- }+ points: dict[str, NDArray[np.float64]] = {}+ errors_px: dict[str, float] = {}+ for i, name in enumerate(point_names_seq):+ if valid_pt_mask[i]:+ stripped = _strip_stage_prefix(name)+ points[stripped] = points_3d[i]+ errors_px[stripped] = float(mean_reproj_error[i])# self._timer.record("result_dict", (time.perf_counter() - _t0) * 1e3)# self._timer.maybe_report()# Triangulation succeeded β reset failure counterself._consecutive_failure_count = 0- return result+ return AngulationResult(points=points, errors_px=errors_px)except Exception as e:self._consecutive_failure_count += 1diff --git a/freemocap/core/tasks/mocap/realtime_filtering/realtime_filter_config.py b/freemocap/core/tasks/mocap/realtime_filtering/realtime_filter_config.pyindex 0593427f..40974084 100644--- a/freemocap/core/tasks/mocap/realtime_filtering/realtime_filter_config.py+++ b/freemocap/core/tasks/mocap/realtime_filtering/realtime_filter_config.py@@ -85,9 +85,55 @@ class RealtimeFilterConfig(BaseModel):# adapting (never permanently frozen on old data).segment_length_decay_s: float = 30.0- # Reject a measured length deviating more than this fraction from the- # running median (guards against low-error-but-wrong samples). None = off.- segment_length_plausibility_tol: float | None = 0.5+ # Trust-region half-width (fraction of the seed length). A measured length+ # outside seed Γ (1 Β± fit_ratio) β lower bound floored at 0.25 Γ seed β is+ # rejected outright, and reported estimates are clamped to the same band.+ # 0.0 = lengths locked to the seeds; 1.0 = up to double/half the seed.+ segment_length_fit_ratio: float = 0.2++ # Measurements a bone's buffer must retain before its median may replace+ # the seed. Bootstrap protection: one frame teaches nothing.+ segment_length_min_samples: int = 5++ # Max relative MAD (median absolute deviation / median) across a buffer's+ # retained samples for them to count as agreeing. A flickering or bimodal+ # measurement stream never replaces the seed.+ segment_length_agreement_tol: float = 0.05++ # Reprojection-error gate for admitting a length measurement (pixels).+ # Distinct from the triangulation survival gate below: a point may survive+ # triangulation yet be too sloppy to teach bone lengths.+ segment_length_max_reprojection_error_px: float = 15.0++ # ---- Segment-fit calibration ritual ----+ # "Reset skeleton fit" arms this ritual instead of re-fitting instantly:+ # countdown (subject gets into view) β quality-gated capture window β+ # freeze (captured lengths re-anchor the trust regions) β bounded drift.++ # Seconds between arming a refit and the capture window opening.+ calibration_countdown_s: float = 3.0++ # Fraction of measurable body keypoints that must be really observed (not+ # extrapolated) for a capture frame to count as good.+ calibration_capture_min_visible_fraction: float = 0.8++ # Max mean reprojection error across measured body keypoints for a capture+ # frame to count as good (pixels).+ calibration_capture_max_mean_error_px: float = 10.0++ # Consecutive good frames required to freeze the capture. ~1 s at 30 fps.+ calibration_capture_consecutive_good_frames: int = 30++ # Lower visibility floor for a capture frame to still teach the bones it+ # can see (per-bone buffers only sample really-observed endpoints, so a+ # partial body β seated at a desk, legs under the table β calibrates its+ # visible bones even though the full-body "good" gate never passes).+ calibration_capture_update_min_visible_fraction: float = 0.25++ # Max seconds in the capture window before a best-effort freeze: whatever+ # bones reached agreement are re-anchored; if none did, the ritual drops+ # back to normal live fitting. Bounds the ritual so it always terminates.+ calibration_capture_timeout_s: float = 15.0# ---- Subject scale ----# Subject standing height in keypoint-coordinate units (mm). The charucodiff --git a/freemocap/core/tasks/mocap/rigid_body/online_segment_lengths.py b/freemocap/core/tasks/mocap/rigid_body/online_segment_lengths.pyindex cb8ead76..7466cf24 100644--- a/freemocap/core/tasks/mocap/rigid_body/online_segment_lengths.py+++ b/freemocap/core/tasks/mocap/rigid_body/online_segment_lengths.py@@ -5,6 +5,19 @@ reprojection error with an age decay, and reports their **median** β the realtanalogue of the posthoc pipeline's per-bone median over the whole recording(skellyforge ``enforce_rigid_bones.calculate_bone_lengths_and_statistics``).+Two guards keep the estimate honest:++* **Trust region** β a measurement only enters the buffer if it lands within+ ``seed_length Γ (1 Β± fit_ratio)`` (lower bound floored at 25% of the seed),+ and the reported estimate is clamped to the same band. The anchor is the+ seed β the anthropometric prior, or a captured calibration via ``reseed`` β+ never the buffer's own contents, so no stream of garbage can drag the+ estimate out of spec or redefine what "plausible" means.+* **Bootstrap agreement** β the buffer only replaces its seed once+ ``min_samples`` retained measurements agree with each other (relative MAD+ within ``agreement_tol``). One frame β or a flickering stream β teaches+ nothing.+Why best-K-by-error instead of a recency window: a bone length is (assumed)stationary, so the best estimate comes from the highest-quality observations*ever* seen, not merely the most recent ones. The age decay (``decay_tau_s``)@@ -27,6 +40,10 @@ class _Sample:t: float+def _clamp(x: float, lo: float, hi: float) -> float:+ return min(hi, max(lo, x))++@dataclassclass BoneLengthBuffer:"""Best-K-by-reprojection-error buffer of one bone's length measurements.@@ -40,37 +57,47 @@ class BoneLengthBuffer:Age-decay time constant (seconds). A stored sample's effective error is``error * exp(age / decay_tau_s)``, so stale samples lose their slot.seed_length : float- Anthropometric prior (mm) returned until ``min_samples`` real- measurements have accumulated.+ Anthropometric prior (mm) returned until the buffer reaches agreement,+ and the anchor of the trust region. Replaced by ``reseed``.+ fit_ratio : float+ Trust-region half-width as a fraction of the seed: measurements outside+ ``seed Γ (1 Β± fit_ratio)`` (lower bound floored at ``seed Γ 0.25``) are+ rejected outright.min_samples : int- Minimum buffered measurements before the median replaces the seed.+ Minimum retained measurements before the buffer may leave its seed.+ agreement_tol : float+ Max relative MAD (median absolute deviation / median) across retained+ samples for the buffer to count as agreeing.max_error : float | NoneReprojection-error gate: measurements above this are dropped outright.- plausibility_tol : float | None- Fractional deviation from the current buffer median above which a- measurement is rejected as implausible (guards against low-error-but-- wrong samples). Inactive until the buffer holds >= 2 samples."""capacity: intdecay_tau_s: floatseed_length: float- min_samples: int = 1+ fit_ratio: float = 0.2+ min_samples: int = 5+ agreement_tol: float = 0.05max_error: float | None = None- plausibility_tol: float | None = None_samples: list[_Sample] = field(default_factory=list, init=False, repr=False)+ @property+ def trust_region(self) -> tuple[float, float]:+ """(lower, upper) acceptable length band (mm), anchored to the seed."""+ lower = max(self.seed_length * (1.0 - self.fit_ratio), self.seed_length * 0.25)+ upper = self.seed_length * (1.0 + self.fit_ratio)+ return lower, upper+def offer(self, *, length: float, error: float, t: float) -> bool:"""Offer one measurement. Returns True if it is retained in the buffer."""if not math.isfinite(length) or length <= 0.0:return Falseif self.max_error is not None and error > self.max_error:return False- if self.plausibility_tol is not None and len(self._samples) >= 2:- median = float(np.median([s.length for s in self._samples]))- if median > 0.0 and abs(length - median) / median > self.plausibility_tol:- return False+ lower, upper = self.trust_region+ if length < lower or length > upper:+ return Falsenew_sample = _Sample(length=float(length), error=float(error), t=float(t))self._samples.append(new_sample)@@ -93,12 +120,43 @@ class BoneLengthBuffer:return sample.errorreturn sample.error * math.exp(age / self.decay_tau_s)+ def agreed_median(self) -> float | None:+ """Buffer consensus length (mm), or None when there is no consensus.++ Consensus requires ``min_samples`` retained measurements whose relative+ MAD is within ``agreement_tol`` β a flickering or bimodal measurement+ stream has no opinion and the seed stands.+ """+ if len(self._samples) < self.min_samples:+ return None+ lengths = np.asarray([s.length for s in self._samples], dtype=float)+ median = float(np.median(lengths))+ mad = float(np.median(np.abs(lengths - median)))+ if mad / median > self.agreement_tol:+ return None+ return median+@propertydef estimate(self) -> float:- """Current best length estimate (mm): median of the buffer, else seed."""- if len(self._samples) < self.min_samples:+ """Current best length estimate (mm): the agreed median if the buffer+ has consensus, else the seed β never outside the trust region."""+ median = self.agreed_median()+ if median is None:return self.seed_length- return float(np.median([s.length for s in self._samples]))+ lower, upper = self.trust_region+ return _clamp(median, lower, upper)++ def reseed(self, new_seed: float) -> None:+ """Re-anchor on a captured length: replace the seed, forget measurements.++ The trust region re-centers on ``new_seed`` and the estimate falls back+ to it until fresh agreement accumulates β captured calibration with+ bounded drift.+ """+ if not math.isfinite(new_seed) or new_seed <= 0.0:+ raise ValueError(f"reseed requires a positive finite length, got {new_seed}")+ self.seed_length = float(new_seed)+ self._samples.clear()def __len__(self) -> int:return len(self._samples)@@ -113,24 +171,26 @@ class OnlineBoneLengths:"""One ``BoneLengthBuffer`` per bone, seeded from anthropometric ratios.``update`` is called once per frame with the current canonical-named 3D- positions and (optionally) per-keypoint reprojection errors; ``lengths``- returns the current best length estimate per bone for the rigidifier.+ positions of **real** (measured, not extrapolated) keypoints and+ (optionally) per-keypoint reprojection errors; ``lengths`` returns the+ current best length estimate per bone for the rigidifier.Parameters----------bone_seeds : dict[str, float]``"parent->child" -> seed length (mm)`` (ratio x height). Defines whichbones are tracked and their starting estimates.- capacity, decay_tau_s, min_samples, max_error, plausibility_tol+ capacity, decay_tau_s, fit_ratio, min_samples, agreement_tol, max_errorPer-bone buffer settings (see ``BoneLengthBuffer``)."""bone_seeds: dict[str, float]capacity: intdecay_tau_s: float- min_samples: int = 1+ fit_ratio: float = 0.2+ min_samples: int = 5+ agreement_tol: float = 0.05max_error: float | None = None- plausibility_tol: float | None = None_buffers: dict[str, BoneLengthBuffer] = field(default_factory=dict, init=False, repr=False)_endpoints: dict[str, tuple[str, str]] = field(default_factory=dict, init=False, repr=False)@@ -143,11 +203,17 @@ class OnlineBoneLengths:capacity=self.capacity,decay_tau_s=self.decay_tau_s,seed_length=float(seed),+ fit_ratio=self.fit_ratio,min_samples=self.min_samples,+ agreement_tol=self.agreement_tol,max_error=self.max_error,- plausibility_tol=self.plausibility_tol,)+ @property+ def endpoints(self) -> dict[str, tuple[str, str]]:+ """``"parent->child" -> (parent, child)`` for every tracked bone."""+ return dict(self._endpoints)+def update(self,positions: dict[str, np.ndarray],@@ -159,8 +225,8 @@ class OnlineBoneLengths:A bone is measured only when both endpoints are present. Its measurementerror is the **worse** of the two endpoints' reprojection errors (a bone- is only as trustworthy as its less-certain endpoint). When ``errors`` is- None, measurements are treated as fully confident (error 0).+ is only as trustworthy as its less-certain endpoint). When ``errors``+ is None, measurements are treated as fully confident (error 0)."""for bone_key, buf in self._buffers.items():parent, child = self._endpoints[bone_key]@@ -180,6 +246,27 @@ class OnlineBoneLengths:"""Current best length estimate (mm) per bone."""return {bone_key: buf.estimate for bone_key, buf in self._buffers.items()}+ @property+ def seeds(self) -> dict[str, float]:+ """Current seed (mm) per bone: the anthropometric prior, or the captured+ calibration for bones that have been re-anchored via ``reseed``."""+ return {bone_key: buf.seed_length for bone_key, buf in self._buffers.items()}++ def agreed_medians(self) -> dict[str, float | None]:+ """Per-bone buffer consensus (mm), or None where no agreement yet."""+ return {bone_key: buf.agreed_median() for bone_key, buf in self._buffers.items()}++ def reseed(self, lengths: dict[str, float]) -> None:+ """Re-anchor the given bones on captured lengths.++ Raises ``KeyError`` on an unknown bone key β no partial reseeds.+ """+ for bone_key in lengths:+ if bone_key not in self._buffers:+ raise KeyError(f"Unknown bone '{bone_key}' β cannot reseed.")+ for bone_key, new_seed in lengths.items():+ self._buffers[bone_key].reseed(new_seed)+def reset(self) -> None:"""Forget every bone's measurements β all estimates fall back to their seeds."""for buf in self._buffers.values():diff --git a/freemocap/core/tasks/mocap/rigid_body/segment_fit_ritual.py b/freemocap/core/tasks/mocap/rigid_body/segment_fit_ritual.pynew file mode 100644index 00000000..b8c45976--- /dev/null+++ b/freemocap/core/tasks/mocap/rigid_body/segment_fit_ritual.py@@ -0,0 +1,264 @@+"""Segment-fit calibration ritual for the realtime skeleton fitter.++State machine that turns "reset the skeleton fit" from an instant next-frame+re-fit into a gated capture: a countdown (so the subject can get into view and+hold still), a quality-gated capture window (only consecutive good frames+count), then a freeze that re-anchors each bone's trust region on the captured+length (see ``OnlineBoneLengths.reseed``). Bones that never reach agreement β+hands out of frame, a limb never visible β keep their seeds and stay live.++ IDLE β normal live fitting (the hardened buffers β trust region,+ agreement gating, error ranking β do the work).+ COUNTDOWN β armed; buffers cleared; no updates until the deadline passes.+ CAPTURING β two quality tiers. "Updatable" frames (enough real keypoints+ to teach something, low error) feed the per-bone buffers β+ partial bodies still calibrate what the cameras can see, so+ a seated subject's torso and arms fit even though the legs+ never will. "Good" frames (nearly everything visible)+ advance the consecutive-good streak toward the fast-path+ freeze. A timeout bounds the window: on expiry, whatever+ bones reached agreement are re-anchored (best effort); if+ nothing agreed, the ritual drops back to IDLE.+ FITTED β captured bones are re-anchored; updates continue, so lengths+ drift slowly inside the re-anchored trust region.+"""+from __future__ import annotations++from dataclasses import dataclass+from enum import StrEnum++import numpy as np++from freemocap.core.tasks.mocap.rigid_body.online_segment_lengths import OnlineBoneLengths+++class FitRitualState(StrEnum):+ IDLE = "idle"+ COUNTDOWN = "countdown"+ CAPTURING = "capturing"+ FITTED = "fitted"+++@dataclass(slots=True, frozen=True)+class FitStateSnapshot:+ """Point-in-time view of the ritual, for publication to the frontend."""++ state: str+ countdown_remaining_s: float+ capture_good_streak: int+ capture_required_good_frames: int+ capture_min_visible_fraction: float+ capture_max_mean_error_px: float+ capture_timeout_remaining_s: float+ visible_fraction: float+ mean_error_px: float | None+ n_fitted_body_bones: int+ median_seed_deviation: float | None+++class SegmentFitRitual:+ """Countdown β gated capture β freeze state machine over the three length managers."""++ def __init__(+ self,+ *,+ body_lengths: OnlineBoneLengths,+ rhand_lengths: OnlineBoneLengths,+ lhand_lengths: OnlineBoneLengths,+ countdown_s: float,+ capture_min_visible_fraction: float,+ capture_max_mean_error_px: float,+ capture_consecutive_good_frames: int,+ capture_update_min_visible_fraction: float,+ capture_timeout_s: float,+ ) -> None:+ self._lengths = {+ "body": body_lengths,+ "rhand": rhand_lengths,+ "lhand": lhand_lengths,+ }+ self._body_endpoints = body_lengths.endpoints+ self._countdown_s = float(countdown_s)+ self._min_visible = float(capture_min_visible_fraction)+ self._max_mean_error = float(capture_max_mean_error_px)+ self._update_min_visible = float(capture_update_min_visible_fraction)+ self._timeout_s = float(capture_timeout_s)+ # The freeze can only capture bones whose buffers reached agreement,+ # which needs min_samples consecutive samples β so the required streak+ # can never be shorter than the largest min_samples. Enforcing it here+ # keeps the invariant true regardless of config.+ self._required_good_frames = max(+ int(capture_consecutive_good_frames),+ max(m.min_samples for m in (body_lengths, rhand_lengths, lhand_lengths)),+ )++ self._state = FitRitualState.IDLE+ self._refit_pending = False+ self._deadline_t = 0.0+ self._capture_start_t = 0.0+ self._good_streak = 0+ self._last_t = 0.0+ self._n_fitted_body_bones = 0+ self._median_seed_deviation: float | None = None+ self._last_visible_fraction = 0.0+ self._last_mean_error_px: float | None = None++ def request_refit(self) -> None:+ """Arm the ritual: the next frame starts the countdown."""+ self._refit_pending = True++ @property+ def state(self) -> FitRitualState:+ return self._state++ def on_frame(+ self,+ *,+ measured_body: dict[str, np.ndarray],+ measured_rhand: dict[str, np.ndarray],+ measured_lhand: dict[str, np.ndarray],+ errors_body: dict[str, float] | None,+ errors_rhand: dict[str, float] | None,+ errors_lhand: dict[str, float] | None,+ t: float,+ ) -> None:+ """Advance the state machine by one frame and apply its update policy."""+ self._last_t = t+ self._last_visible_fraction = self._visible_fraction(measured_body)+ self._last_mean_error_px = self._mean_error(measured_body, errors_body)++ if self._refit_pending:+ self._refit_pending = False+ for lengths in self._lengths.values():+ lengths.reset()+ self._state = FitRitualState.COUNTDOWN+ self._deadline_t = t + self._countdown_s+ self._good_streak = 0+ self._n_fitted_body_bones = 0+ self._median_seed_deviation = None++ if self._state is FitRitualState.COUNTDOWN:+ if t >= self._deadline_t:+ self._state = FitRitualState.CAPTURING+ self._capture_start_t = t+ return++ if self._state is FitRitualState.CAPTURING:+ error_ok = (+ self._last_mean_error_px is None+ or self._last_mean_error_px <= self._max_mean_error+ )+ good = self._last_visible_fraction >= self._min_visible and error_ok+ updatable = self._last_visible_fraction >= self._update_min_visible and error_ok+ if updatable:+ # Partial-visibility frames still teach the bones they can+ # see β a bone's buffer only samples when both endpoints are+ # really observed, so a hidden leg pollutes nothing.+ self._update_all(+ measured_body, measured_rhand, measured_lhand,+ errors_body, errors_rhand, errors_lhand, t,+ )+ if good:+ self._good_streak += 1+ if self._good_streak >= self._required_good_frames:+ self._freeze()+ self._state = FitRitualState.FITTED+ return+ self._good_streak = 0+ if t - self._capture_start_t >= self._timeout_s:+ # Best-effort freeze: re-anchor whatever reached agreement+ # (a seated subject's torso/arms; the legs keep their seeds).+ # Nothing agreed -> normal live fitting, no fanfare.+ if self._freeze() > 0:+ self._state = FitRitualState.FITTED+ else:+ self._state = FitRitualState.IDLE+ return++ # IDLE and FITTED both update every frame; FITTED bones are re-anchored,+ # so their updates drift only inside the captured trust region.+ self._update_all(+ measured_body, measured_rhand, measured_lhand,+ errors_body, errors_rhand, errors_lhand, t,+ )++ def _visible_fraction(self, measured_body: dict[str, np.ndarray]) -> float:+ expected = {name for endpoints in self._body_endpoints.values() for name in endpoints}+ present = sum(1 for name in expected if name in measured_body)+ return present / len(expected)++ @staticmethod+ def _mean_error(+ measured_body: dict[str, np.ndarray],+ errors_body: dict[str, float] | None,+ ) -> float | None:+ if errors_body is None:+ return None+ vals = [errors_body[name] for name in measured_body if name in errors_body]+ if not vals:+ return None+ return float(np.mean(vals))++ def _update_all(+ self,+ measured_body: dict[str, np.ndarray],+ measured_rhand: dict[str, np.ndarray],+ measured_lhand: dict[str, np.ndarray],+ errors_body: dict[str, float] | None,+ errors_rhand: dict[str, float] | None,+ errors_lhand: dict[str, float] | None,+ t: float,+ ) -> None:+ self._lengths["body"].update(measured_body, t=t, errors=errors_body)+ self._lengths["rhand"].update(measured_rhand, t=t, errors=errors_rhand)+ self._lengths["lhand"].update(measured_lhand, t=t, errors=errors_lhand)++ def _freeze(self) -> int:+ """Re-anchor every bone that reached agreement on its captured length.++ Returns the number of bones re-anchored across body and both hands.+ """+ n_captured = 0+ deviations: list[float] = []+ for tree_name, lengths in self._lengths.items():+ medians = lengths.agreed_medians()+ seeds = lengths.seeds+ captured = {bone: m for bone, m in medians.items() if m is not None}+ if not captured:+ continue+ n_captured += len(captured)+ if tree_name == "body":+ self._n_fitted_body_bones = len(captured)+ deviations = [+ abs(captured[bone] - seeds[bone]) / seeds[bone]+ for bone in captured+ ]+ lengths.reseed(captured)+ if deviations:+ self._median_seed_deviation = float(np.median(deviations))+ return n_captured++ def snapshot(self) -> FitStateSnapshot:+ countdown_remaining = (+ max(0.0, self._deadline_t - self._last_t)+ if self._state is FitRitualState.COUNTDOWN+ else 0.0+ )+ timeout_remaining = (+ max(0.0, self._timeout_s - (self._last_t - self._capture_start_t))+ if self._state is FitRitualState.CAPTURING+ else 0.0+ )+ return FitStateSnapshot(+ state=str(self._state),+ countdown_remaining_s=countdown_remaining,+ capture_good_streak=self._good_streak,+ capture_required_good_frames=self._required_good_frames,+ capture_min_visible_fraction=self._min_visible,+ capture_max_mean_error_px=self._max_mean_error,+ capture_timeout_remaining_s=timeout_remaining,+ visible_fraction=self._last_visible_fraction,+ mean_error_px=self._last_mean_error_px,+ n_fitted_body_bones=self._n_fitted_body_bones,+ median_seed_deviation=self._median_seed_deviation,+ )diff --git a/freemocap/core/tasks/mocap/rigid_body/skeleton_rigidifier.py b/freemocap/core/tasks/mocap/rigid_body/skeleton_rigidifier.pyindex a8c83f73..39c48991 100644--- a/freemocap/core/tasks/mocap/rigid_body/skeleton_rigidifier.py+++ b/freemocap/core/tasks/mocap/rigid_body/skeleton_rigidifier.py@@ -17,7 +17,6 @@ collapsing onto its parent.from __future__ import annotationsimport math-import timefrom collections import dequefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -45,6 +44,10 @@ from skellytracker.core.detectors.keypoint_detectors.rtmpose.hand.rtmpose_hand_dfrom skellytracker.core.io.tracker_mapping import TrackerMappingfrom freemocap.core.tasks.mocap.rigid_body.online_segment_lengths import OnlineBoneLengths+from freemocap.core.tasks.mocap.rigid_body.segment_fit_ritual import (+ FitStateSnapshot,+ SegmentFitRitual,+)# Direction used for a bone that has never been observed (no carried direction)._FALLBACK_DIRECTION: np.ndarray = np.array([0.0, 1.0, 0.0])@@ -259,10 +262,10 @@ class RealtimeSkeletonRigidifier:Created once at aggregator init for a specific detector type (RTMPose orMediaPipe β see ``create``). Each frame: map the configured detector's raw- keypoints onto the canonical body + hand models, update each bone's online- length estimate- (a best-K-by-reprojection-error median), and run a single closed-form- forward pass that holds those lengths while following the observed pose.+ keypoints onto the canonical body + hand models, advance the segment-fit+ ritual with the **measured** (real, not extrapolated) keypoints, and run a+ single closed-form forward pass over the full keypoint set that holds the+ estimated lengths while following the observed pose.This is the streaming counterpart of the posthoc rigid-bones step(skellyforge ``enforce_rigid_bones``): same median-length + forward-pass@@ -284,6 +287,8 @@ class RealtimeSkeletonRigidifier:_hand_name_to_tracker_r: dict[str, str] = field(repr=False)_hand_name_to_tracker_l: dict[str, str] = field(repr=False)+ _ritual: SegmentFitRitual = field(repr=False)+height_mm: float = 1750.0@classmethod@@ -294,9 +299,16 @@ class RealtimeSkeletonRigidifier:height_mm: float = 1750.0,buffer_capacity: int = 64,decay_tau_s: float = 30.0,+ fit_ratio: float = 0.2,+ min_samples: int = 5,+ agreement_tol: float = 0.05,max_reprojection_error: float | None = None,- plausibility_tol: float | None = 0.5,- min_samples: int = 1,+ countdown_s: float = 3.0,+ capture_min_visible_fraction: float = 0.8,+ capture_max_mean_error_px: float = 10.0,+ capture_consecutive_good_frames: int = 30,+ capture_update_min_visible_fraction: float = 0.25,+ capture_timeout_s: float = 15.0,) -> "RealtimeSkeletonRigidifier":"""Load canonical models + tracker mappings and build the per-tree state.@@ -314,14 +326,33 @@ class RealtimeSkeletonRigidifier:Best-K buffer size per bone.decay_tau_s : floatAge-decay time constant (s) for the buffer's eviction score.- max_reprojection_error : float | None- Reprojection-error gate for admitting a measurement (None = rely on- the upstream NaN-rejection gate).- plausibility_tol : float | None- Fractional deviation from the running median above which a- measurement is rejected as implausible.+ fit_ratio : float+ Trust-region half-width (fraction of the seed) for admitting+ measurements and clamping estimates.min_samples : int- Measurements needed before the median replaces the seed.+ Measurements a bone's buffer must retain before it may leave its seed.+ agreement_tol : float+ Max relative MAD across a buffer's samples for them to count as+ agreeing (replacing the seed).+ max_reprojection_error : float | None+ Reprojection-error gate for admitting a measurement (None = no+ error gate, e.g. single-camera mode).+ countdown_s : float+ Seconds between arming a refit and the capture window opening.+ capture_min_visible_fraction : float+ Fraction of measurable body keypoints that must be really observed+ (not extrapolated) for a capture frame to count as good.+ capture_max_mean_error_px : float+ Max mean reprojection error across measured body keypoints for a+ capture frame to count as good.+ capture_consecutive_good_frames : int+ Consecutive good frames required to freeze the capture.+ capture_update_min_visible_fraction : float+ Lower visibility floor for a capture frame to still teach the+ bones it can see (partial bodies calibrate their visible bones).+ capture_timeout_s : float+ Max seconds in the capture window before a best-effort freeze of+ whatever bones reached agreement (none -> back to live fitting)."""body_anatomy = AnatomicalStructure.from_model_info(CanonicalBodyModelInfo(), "body")hand_anatomy = AnatomicalStructure.from_model_info(CanonicalHandModelInfo(), "hand")@@ -352,11 +383,27 @@ class RealtimeSkeletonRigidifier:bone_seeds=seeds,capacity=buffer_capacity,decay_tau_s=decay_tau_s,+ fit_ratio=fit_ratio,min_samples=min_samples,+ agreement_tol=agreement_tol,max_error=max_reprojection_error,- plausibility_tol=plausibility_tol,)+ body_lengths = make_lengths(body_seeds)+ rhand_lengths = make_lengths(hand_seeds)+ lhand_lengths = make_lengths(hand_seeds)+ ritual = SegmentFitRitual(+ body_lengths=body_lengths,+ rhand_lengths=rhand_lengths,+ lhand_lengths=lhand_lengths,+ countdown_s=countdown_s,+ capture_min_visible_fraction=capture_min_visible_fraction,+ capture_max_mean_error_px=capture_max_mean_error_px,+ capture_consecutive_good_frames=capture_consecutive_good_frames,+ capture_update_min_visible_fraction=capture_update_min_visible_fraction,+ capture_timeout_s=capture_timeout_s,+ )+return cls(_body_mapping=body_mapping,_hand_mapping_r=hand_mapping_r,@@ -364,11 +411,12 @@ class RealtimeSkeletonRigidifier:_body_tree=TreeRigidifier(joint_hierarchy=body_anatomy.joint_hierarchy),_hand_tree_r=TreeRigidifier(joint_hierarchy=hand_anatomy.joint_hierarchy),_hand_tree_l=TreeRigidifier(joint_hierarchy=hand_anatomy.joint_hierarchy),- _body_lengths=make_lengths(body_seeds),- _rhand_lengths=make_lengths(hand_seeds),- _lhand_lengths=make_lengths(hand_seeds),+ _body_lengths=body_lengths,+ _rhand_lengths=rhand_lengths,+ _lhand_lengths=lhand_lengths,_hand_name_to_tracker_r=name_to_tracker_r,_hand_name_to_tracker_l=name_to_tracker_l,+ _ritual=ritual,height_mm=height_mm,)@@ -376,32 +424,51 @@ class RealtimeSkeletonRigidifier:self,tracker_positions: dict[str, np.ndarray],*,- t: float | None = None,- errors: dict[str, float] | None = None,+ measured: dict[str, np.ndarray],+ t: float,+ errors: dict[str, float] | None,) -> RigidifyResult:"""Rigidify one frame of the configured detector's raw keypoints.- ``errors`` (optional) maps **tracker** keypoint name -> reprojection- error (px); the bone-length estimator uses it to rank/gate samples so- high-error frames don't corrupt the lengths. Most body limb landmarks- share names with the canonical model directly (both RTMPose and- MediaPipe use core COCO limb names); hand errors are remapped from the- side-prefixed tracker names. When absent, samples are treated as- equally confident.+ Parameters+ ----------+ tracker_positions : dict[str, (3,) ndarray]+ This frame's keypoints (tracker names), including any gap-filled+ extrapolations β drives the rigidified output only.+ measured : dict[str, (3,) ndarray]+ The real-only subset of ``tracker_positions`` (extrapolated points+ removed) β the only positions allowed to teach bone lengths.+ Synthesized canonical centers degrade to a partial mean of their+ real sources when some sources are extrapolated; the trust region+ and agreement gate bound that bias.+ t : float+ Frame timestamp (s); drives the buffers' age decay and the ritual+ countdown. The caller owns the clock.+ errors : dict[str, float] | None+ Per-tracker-keypoint reprojection error (px); the bone-length+ estimator uses it to rank/gate samples so high-error frames don't+ corrupt the lengths. Most body limb landmarks share names with the+ canonical model directly (both RTMPose and MediaPipe use core COCO+ limb names); hand errors are remapped from the side-prefixed+ tracker names. None (single-camera mode) = all samples treated as+ equally confident."""- if t is None:- t = time.perf_counter()-canonical_body = self._body_mapping.apply(tracker_positions)canonical_rhand = self._hand_mapping_r.apply(tracker_positions)canonical_lhand = self._hand_mapping_l.apply(tracker_positions)- self._body_lengths.update(canonical_body, t=t, errors=errors)- self._rhand_lengths.update(- canonical_rhand, t=t, errors=_hand_errors(errors, self._hand_name_to_tracker_r),- )- self._lhand_lengths.update(- canonical_lhand, t=t, errors=_hand_errors(errors, self._hand_name_to_tracker_l),+ measured_body = self._body_mapping.apply(measured)+ measured_rhand = self._hand_mapping_r.apply(measured)+ measured_lhand = self._hand_mapping_l.apply(measured)++ self._ritual.on_frame(+ measured_body=measured_body,+ measured_rhand=measured_rhand,+ measured_lhand=measured_lhand,+ errors_body=errors,+ errors_rhand=_hand_errors(errors, self._hand_name_to_tracker_r),+ errors_lhand=_hand_errors(errors, self._hand_name_to_tracker_l),+ t=t,)body_out = self._body_tree.rigidify(canonical_body, self._body_lengths.lengths)@@ -425,20 +492,21 @@ class RealtimeSkeletonRigidifier:right_hand_positions=rhand_tracker,)- def reset(self) -> None:- """Restore the fitter to its just-created state.+ def request_refit(self) -> None:+ """Arm the refit ritual: countdown β quality-gated capture β freeze.- Forgets the learned bone lengths (every online estimate falls back to its- anthropometric seed) and clears the carried gap-fill directions on all- trees. The next frame re-fits from scratch, exactly as if the pipeline had- just started.+ Clears the carried gap-fill directions on all trees immediately; the+ length buffers clear when the countdown begins on the next frame."""self._body_tree.reset()self._hand_tree_r.reset()self._hand_tree_l.reset()- self._body_lengths.reset()- self._rhand_lengths.reset()- self._lhand_lengths.reset()+ self._ritual.request_refit()++ @property+ def fit_state(self) -> FitStateSnapshot:+ """Current ritual state, for publication to the frontend."""+ return self._ritual.snapshot()@propertydef body_bone_lengths(self) -> dict[str, float]:diff --git a/freemocap/core/tasks/triangulation/helpers/angulation_result.py b/freemocap/core/tasks/triangulation/helpers/angulation_result.pynew file mode 100644index 00000000..6749dfb2--- /dev/null+++ b/freemocap/core/tasks/triangulation/helpers/angulation_result.py@@ -0,0 +1,26 @@+from dataclasses import dataclass++import numpy as np+from numpy.typing import NDArray+++@dataclass(slots=True, frozen=True)+class AngulationResult:+ """Output of `CalibrationStateTracker.try_angulate(...)` for one frame.++ points : dict[str, (3,) ndarray]+ Triangulated 3D point positions (mm), keyed by canonical point name.+ NaN-free β points that failed triangulation or the reprojection gate+ are absent, never NaN.+ errors_px : dict[str, float] | None+ Per-point mean reprojection error across cameras (px), keyed by the+ same names as ``points``. None when no error information exists β+ the single-camera planar-projection path, where reprojection error+ is undefined by construction.++ Hot path - slots removes per-instance __dict__ overhead, frozen makes it+ immutable so it can be shared across threads/queues without copying.+ """++ points: dict[str, NDArray[np.float64]]+ errors_px: dict[str, float] | Nonediff --git a/freemocap/core/tasks/triangulation/helpers/project_single_camera.py b/freemocap/core/tasks/triangulation/helpers/project_single_camera.pyindex 1af394a5..13f73d24 100644--- a/freemocap/core/tasks/triangulation/helpers/project_single_camera.py+++ b/freemocap/core/tasks/triangulation/helpers/project_single_camera.py@@ -20,8 +20,8 @@ def project_2d_observation_to_3d() -> dict[str, NDArray[np.float64]]:"""Project a single camera's per-frame observation to 3D on the Y=0 plane.- Returns {point_name: ndarray(3,)} β the same shape try_angulate() returns- for multi-camera triangulation.+ Returns {point_name: ndarray(3,)} β the same shape as the ``points`` dict+ try_angulate() produces for multi-camera triangulation."""kpts = observation.to_keypoints()xy = kpts.xyz[:, :2] # (n_points, 2)diff --git a/freemocap/pubsub/pubsub_topics.py b/freemocap/pubsub/pubsub_topics.pyindex 88f505c5..a929bea4 100644--- a/freemocap/pubsub/pubsub_topics.py+++ b/freemocap/pubsub/pubsub_topics.py@@ -17,6 +17,7 @@ from skellytracker.core.data_primitives.observation import Observationfrom freemocap.core.kinematics.body_kinematics_state import BodyKinematicsStatefrom freemocap.core.pipeline.realtime.realtime_pipeline_config import RealtimePipelineConfigfrom freemocap.core.tasks.mocap.center_of_mass import CenterOfMassResult+from freemocap.core.tasks.mocap.rigid_body.segment_fit_ritual import FitStateSnapshotfrom freemocap.core.types.type_overloads import (FrameNumberInt,PipelineIdString,@@ -206,15 +207,53 @@ class CalibrationRecordingStateMessage(TopicMessageABC):@dataclassclass SkeletonFitterResetMessage(TopicMessageABC):- """Trigger the aggregator to fully reset the skeleton fitter.+ """Arm the segment-fit calibration ritual on every live pipeline.Presence of this message in the subscription queue signals the aggregator to- call ``RealtimeSkeletonRigidifier.reset()`` β forgetting the learned bone- lengths (re-seeding from anthropometry) and clearing the carried bone- directions, so the fit starts over as if the pipeline had just launched.+ call ``RealtimeSkeletonRigidifier.request_refit()`` β starting the countdown+ β quality-gated capture β freeze ritual instead of an instant next-frame+ re-fit."""+@dataclass+class SkeletonFitStateMessage(TopicMessageABC):+ """Per-frame snapshot of the segment-fit calibration ritual.++ Published by the aggregator every frame the rigidifier runs, so the+ frontend can render the ritual ("hold still β capturing in 3β¦2β¦1 β+ locked") and spot a bonked fit (high ``median_seed_deviation``).+ """++ state: str = "idle"+ countdown_remaining_s: float = 0.0+ capture_good_streak: int = 0+ capture_required_good_frames: int = 0+ capture_min_visible_fraction: float = 0.0+ capture_max_mean_error_px: float = 0.0+ capture_timeout_remaining_s: float = 0.0+ visible_fraction: float = 0.0+ mean_error_px: float | None = None+ n_fitted_body_bones: int = 0+ median_seed_deviation: float | None = None++ @classmethod+ def from_snapshot(cls, snapshot: FitStateSnapshot) -> "SkeletonFitStateMessage":+ return cls(+ state=snapshot.state,+ countdown_remaining_s=snapshot.countdown_remaining_s,+ capture_good_streak=snapshot.capture_good_streak,+ capture_required_good_frames=snapshot.capture_required_good_frames,+ capture_min_visible_fraction=snapshot.capture_min_visible_fraction,+ capture_max_mean_error_px=snapshot.capture_max_mean_error_px,+ capture_timeout_remaining_s=snapshot.capture_timeout_remaining_s,+ visible_fraction=snapshot.visible_fraction,+ mean_error_px=snapshot.mean_error_px,+ n_fitted_body_bones=snapshot.n_fitted_body_bones,+ median_seed_deviation=snapshot.median_seed_deviation,+ )++# ---------------------------------------------------------------------------# Topic instantiation@@ -229,5 +268,6 @@ AggregationNodeOutputTopic = create_topic(AggregationNodeOutputMessage)PipelineTimingTopic = create_topic(PipelineTimingMessage)CalibrationRecordingStateTopic = create_topic(CalibrationRecordingStateMessage)SkeletonFitterResetTopic = create_topic(SkeletonFitterResetMessage)+SkeletonFitStateTopic = create_topic(SkeletonFitStateMessage)diff --git a/freemocap/tests/pipelines/test_realtime_keypoint_filter.py b/freemocap/tests/pipelines/test_realtime_keypoint_filter.pynew file mode 100644index 00000000..87a1b5eb--- /dev/null+++ b/freemocap/tests/pipelines/test_realtime_keypoint_filter.py@@ -0,0 +1,46 @@+"""Unit tests for the realtime One Euro keypoint filter's prediction provenance."""+import numpy as np++from freemocap.core.pipeline.realtime.realtime_keypoint_filter import RealtimeKeypointFilter+++def test_observed_points_are_not_predicted():+ f = RealtimeKeypointFilter(dims=3)+ out = f.filter(t=0.0, raw_keypoints={"nose": np.array([1.0, 2.0, 3.0])})+ np.testing.assert_allclose(out.positions["nose"], [1.0, 2.0, 3.0])+ assert out.predicted_names == frozenset()+++def test_missing_point_is_gap_filled_and_flagged():+ f = RealtimeKeypointFilter(dims=3)+ f.filter(t=0.0, raw_keypoints={"nose": np.array([1.0, 2.0, 3.0])})+ out = f.filter(t=0.1, raw_keypoints={})+ assert "nose" in out.positions # gap-filled so display doesn't blink+ assert out.predicted_names == frozenset({"nose"})+++def test_prediction_stops_after_max_frames():+ f = RealtimeKeypointFilter(dims=3, max_prediction_frames=2)+ f.filter(t=0.0, raw_keypoints={"nose": np.zeros(3)})+ f.filter(t=0.1, raw_keypoints={})+ f.filter(t=0.2, raw_keypoints={})+ out = f.filter(t=0.3, raw_keypoints={})+ assert "nose" not in out.positions+ assert out.predicted_names == frozenset()+++def test_returning_point_is_real_again():+ f = RealtimeKeypointFilter(dims=3)+ f.filter(t=0.0, raw_keypoints={"nose": np.zeros(3)})+ f.filter(t=0.1, raw_keypoints={})+ out = f.filter(t=0.2, raw_keypoints={"nose": np.ones(3)})+ assert out.predicted_names == frozenset()+++def test_reset_clears_state():+ f = RealtimeKeypointFilter(dims=3)+ f.filter(t=0.0, raw_keypoints={"nose": np.zeros(3)})+ f.reset()+ out = f.filter(t=0.1, raw_keypoints={})+ assert out.positions == {}+ assert out.predicted_names == frozenset()diff --git a/freemocap/tests/rigid_body/test_bone_length_buffer.py b/freemocap/tests/rigid_body/test_bone_length_buffer.pyindex 20ec763c..80ebb316 100644--- a/freemocap/tests/rigid_body/test_bone_length_buffer.py+++ b/freemocap/tests/rigid_body/test_bone_length_buffer.py@@ -1,7 +1,8 @@"""Unit tests for the streaming best-K bone-length buffer.The buffer keeps the best-K bone-length measurements seen so far, ranked by-reprojection error with an age decay, and reports their median. It is the+reprojection error with an age decay, and reports their median once enough+samples agree β always inside a trust region anchored to the seed. It is therealtime analogue of the posthoc pipeline's per-bone median over all frames."""import pytest@@ -9,57 +10,125 @@ import pytestfrom freemocap.core.tasks.mocap.rigid_body.online_segment_lengths import BoneLengthBuffer+def _buf(**overrides) -> BoneLengthBuffer:+ kwargs = dict(capacity=8, decay_tau_s=1e12, seed_length=100.0)+ kwargs.update(overrides)+ return BoneLengthBuffer(**kwargs)++def test_estimate_is_seed_when_empty():- buf = BoneLengthBuffer(capacity=4, decay_tau_s=10.0, seed_length=100.0)+ buf = _buf()assert buf.estimate == 100.0assert len(buf) == 0-def test_estimate_is_median_of_accepted_samples():- buf = BoneLengthBuffer(capacity=8, decay_tau_s=1e12, seed_length=100.0)- for i, length in enumerate([90.0, 110.0, 100.0]):- assert buf.offer(length=length, error=1.0, t=float(i)) is True- assert buf.estimate == 100.0 # median of {90, 100, 110}+def test_single_offer_does_not_replace_seed():+ # Bootstrap protection: min_samples=5 by default β one frame teaches nothing.+ buf = _buf()+ assert buf.offer(length=110.0, error=1.0, t=0.0) is True+ assert buf.estimate == 100.0+++def test_agreeing_samples_replace_seed_with_median():+ buf = _buf()+ for i in range(5):+ assert buf.offer(length=110.0 + i * 0.1, error=1.0, t=float(i)) is True+ assert buf.estimate == pytest.approx(110.2)+++def test_bimodal_samples_never_replace_seed():+ # Alternating 90 / 110: relative MAD is 10% > agreement_tol (5%) β no consensus.+ buf = _buf()+ for i in range(10):+ buf.offer(length=90.0 if i % 2 == 0 else 110.0, error=1.0, t=float(i))+ assert buf.estimate == 100.0+++def test_trust_region_rejects_out_of_spec_lengths():+ # seed 100, fit_ratio 0.2 -> [80, 120].+ buf = _buf(fit_ratio=0.2)+ assert buf.offer(length=79.9, error=1.0, t=0.0) is False+ assert buf.offer(length=120.1, error=1.0, t=1.0) is False+ assert buf.offer(length=80.0, error=1.0, t=2.0) is True+ assert buf.offer(length=120.0, error=1.0, t=3.0) is True+++def test_trust_region_floor_is_25_percent_of_seed():+ # ratio 1.0 would allow [0, 200] β the floor clamps the lower bound to 25.+ buf = _buf(fit_ratio=1.0)+ assert buf.offer(length=24.9, error=1.0, t=0.0) is False+ assert buf.offer(length=25.0, error=1.0, t=1.0) is True+ assert buf.offer(length=200.0, error=1.0, t=2.0) is True+ assert buf.offer(length=200.1, error=1.0, t=3.0) is False+++def test_garbage_stream_can_never_establish_a_new_anchor():+ # A sustained stream of out-of-region garbage is rejected forever, so the+ # estimate can never get stuck on it β and good data is still accepted after.+ buf = _buf(fit_ratio=0.2)+ for i in range(20):+ assert buf.offer(length=300.0, error=0.0, t=float(i)) is False+ assert buf.estimate == 100.0+ for i in range(5):+ assert buf.offer(length=110.0, error=1.0, t=100.0 + i) is True+ assert buf.estimate == pytest.approx(110.0)def test_reproj_gate_drops_high_error_samples():- buf = BoneLengthBuffer(capacity=8, decay_tau_s=1e12, seed_length=100.0, max_error=5.0)- assert buf.offer(length=400.0, error=50.0, t=0.0) is False # error above gate+ buf = _buf(max_error=5.0)+ assert buf.offer(length=110.0, error=50.0, t=0.0) is Falseassert len(buf) == 0- assert buf.estimate == 100.0 # untouched -> still the seed+ assert buf.estimate == 100.0def test_keeps_best_k_by_error_when_over_capacity():# capacity 2, effectively no decay: the worst-error sample must not survive.- buf = BoneLengthBuffer(capacity=2, decay_tau_s=1e12, seed_length=100.0)- buf.offer(length=200.0, error=1.0, t=0.0)- buf.offer(length=201.0, error=2.0, t=1.0)- buf.offer(length=999.0, error=9.0, t=2.0) # worst error -> evicted+ buf = _buf(capacity=2, min_samples=1)+ buf.offer(length=110.0, error=1.0, t=0.0)+ buf.offer(length=111.0, error=2.0, t=1.0)+ buf.offer(length=112.0, error=9.0, t=2.0) # worst error -> evictedassert len(buf) == 2- assert buf.estimate == 200.5 # median of {200, 201}+ assert buf.estimate == 110.5 # median of {110, 111}def test_decay_lets_fresh_sample_replace_stale_better_one():# With a short decay, a stale low-error sample is evicted for a fresh,# higher-error one (age inflates the stale sample's effective error).- buf = BoneLengthBuffer(capacity=1, decay_tau_s=1.0, seed_length=100.0)- buf.offer(length=200.0, error=0.1, t=0.0)- assert buf.estimate == 200.0- buf.offer(length=250.0, error=1.0, t=100.0) # much later- assert buf.estimate == 250.0+ buf = _buf(capacity=1, decay_tau_s=1.0, min_samples=1)+ buf.offer(length=110.0, error=0.1, t=0.0)+ assert buf.estimate == 110.0+ buf.offer(length=115.0, error=1.0, t=100.0) # much later+ assert buf.estimate == 115.0def test_no_decay_keeps_lower_error_sample():# With negligible decay, the lower-error sample wins regardless of age.- buf = BoneLengthBuffer(capacity=1, decay_tau_s=1e12, seed_length=100.0)- buf.offer(length=200.0, error=0.1, t=0.0)- assert buf.offer(length=250.0, error=1.0, t=100.0) is False # higher error -> rejected- assert buf.estimate == 200.0+ buf = _buf(capacity=1, min_samples=1)+ buf.offer(length=110.0, error=0.1, t=0.0)+ assert buf.offer(length=115.0, error=1.0, t=100.0) is False # higher error -> rejected+ assert buf.estimate == 110.0-def test_plausibility_gate_drops_wild_lengths():- buf = BoneLengthBuffer(capacity=8, decay_tau_s=1e12, seed_length=100.0, plausibility_tol=0.2)+def test_reseed_reanchors_and_clears():+ buf = _buf(fit_ratio=0.2)for i in range(5):- buf.offer(length=300.0, error=1.0, t=float(i)) # establish a 300 mm median- assert buf.offer(length=600.0, error=1.0, t=5.0) is False # 2x median -> implausible+ buf.offer(length=110.0, error=1.0, t=float(i))+ assert buf.estimate == pytest.approx(110.0)++ buf.reseed(300.0)+assert buf.estimate == 300.0+ assert len(buf) == 0+ # The trust region re-centered: 110 is now out of spec, 330 is in.+ assert buf.offer(length=110.0, error=1.0, t=10.0) is False+ for i in range(5):+ assert buf.offer(length=330.0, error=1.0, t=20.0 + i) is True+ assert buf.estimate == pytest.approx(330.0)+++def test_reseed_rejects_invalid_length():+ buf = _buf()+ with pytest.raises(ValueError):+ buf.reseed(0.0)+ with pytest.raises(ValueError):+ buf.reseed(float("nan"))diff --git a/freemocap/tests/rigid_body/test_online_bone_lengths.py b/freemocap/tests/rigid_body/test_online_bone_lengths.pyindex a0c69ba4..8ff27d9b 100644--- a/freemocap/tests/rigid_body/test_online_bone_lengths.py+++ b/freemocap/tests/rigid_body/test_online_bone_lengths.py@@ -1,5 +1,6 @@"""Unit tests for the multi-bone online length manager."""import numpy as np+import pytestfrom freemocap.core.tasks.mocap.rigid_body.online_segment_lengths import OnlineBoneLengths@@ -9,6 +10,8 @@ def _make(**overrides) -> OnlineBoneLengths:bone_seeds={"a->b": 100.0, "b->c": 80.0},capacity=8,decay_tau_s=1e12,+ min_samples=1,+ fit_ratio=1.0,)kwargs.update(overrides)return OnlineBoneLengths(**kwargs)@@ -58,6 +61,39 @@ def test_update_without_errors_still_measures():assert online.lengths["a->b"] == 150.0+def test_trust_region_rejects_out_of_spec_measurement():+ online = _make(fit_ratio=0.2) # region for seed 100: [80, 120]+ positions = {"a": np.zeros(3), "b": np.array([0.0, 150.0, 0.0])}+ online.update(positions, errors={"a": 1.0, "b": 1.0}, t=0.0)+ assert online.lengths["a->b"] == 100.0 # 150 is out of region -> seed stands+++def test_agreement_required_before_leaving_seed():+ online = _make(min_samples=5, fit_ratio=0.5) # region for seed 100: [50, 150]+ positions = {"a": np.zeros(3), "b": np.array([0.0, 130.0, 0.0])}+ for i in range(4):+ online.update(positions, errors={"a": 1.0, "b": 1.0}, t=float(i))+ assert online.lengths["a->b"] == 100.0 # 4 < min_samples+ assert online.agreed_medians()["a->b"] is None+ online.update(positions, errors={"a": 1.0, "b": 1.0}, t=4.0)+ assert online.lengths["a->b"] == pytest.approx(130.0)+ assert online.agreed_medians()["a->b"] == pytest.approx(130.0)+++def test_reseed_reanchors_bones():+ online = _make()+ online.reseed({"a->b": 300.0})+ assert online.lengths["a->b"] == 300.0+ assert online.seeds["a->b"] == 300.0+ assert online.lengths["b->c"] == 80.0 # untouched+++def test_reseed_unknown_bone_raises():+ online = _make()+ with pytest.raises(KeyError):+ online.reseed({"x->y": 100.0})++def test_reset_restores_seeds():online = _make()online.update(diff --git a/freemocap/tests/rigid_body/test_realtime_skeleton_rigidifier.py b/freemocap/tests/rigid_body/test_realtime_skeleton_rigidifier.pyindex a44fdb23..a1819bca 100644--- a/freemocap/tests/rigid_body/test_realtime_skeleton_rigidifier.py+++ b/freemocap/tests/rigid_body/test_realtime_skeleton_rigidifier.py@@ -29,6 +29,10 @@ def _upright_rtmpose_pose() -> dict[str, np.ndarray]:}+def _frame(rig: RealtimeSkeletonRigidifier, pose: dict[str, np.ndarray], t: float):+ return rig.rigidify_frame(pose, measured=pose, t=t, errors=None)++def test_create_seeds_all_bones():rig = RealtimeSkeletonRigidifier.create(height_mm=1750.0)assert len(rig.body_bone_lengths) == 26@@ -38,7 +42,7 @@ def test_create_seeds_all_bones():def test_body_includes_canonical_centers():rig = RealtimeSkeletonRigidifier.create(height_mm=1750.0)- out = rig.rigidify_frame(_upright_rtmpose_pose())+ out = _frame(rig, _upright_rtmpose_pose(), t=0.0)assert "hips_center" in out.body_positionsassert "left_elbow" in out.body_positions@@ -47,7 +51,7 @@ def test_output_segment_length_equals_estimate():# The rigid guarantee: an output bone's length is exactly the current# estimate, not whatever this frame's noisy observation happened to be.rig = RealtimeSkeletonRigidifier.create(height_mm=1750.0)- out = rig.rigidify_frame(_upright_rtmpose_pose())+ out = _frame(rig, _upright_rtmpose_pose(), t=0.0)est = rig.body_bone_lengths["left_shoulder->left_elbow"]body = out.body_positionsmeasured = float(np.linalg.norm(body["left_elbow"] - body["left_shoulder"]))@@ -57,11 +61,11 @@ def test_output_segment_length_equals_estimate():def test_segment_length_is_rigid_to_pose_change():rig = RealtimeSkeletonRigidifier.create(height_mm=1750.0)pose1 = _upright_rtmpose_pose()- rig.rigidify_frame(pose1)+ _frame(rig, pose1, t=0.0)# Bend the elbow drastically (very different observed upper-arm length).pose2 = dict(pose1)pose2["left_elbow"] = pose1["left_shoulder"] + np.array([0.0, -100.0, 0.0])- out2 = rig.rigidify_frame(pose2)+ out2 = _frame(rig, pose2, t=0.1)est = rig.body_bone_lengths["left_shoulder->left_elbow"]body = out2.body_positionsmeasured = float(np.linalg.norm(body["left_elbow"] - body["left_shoulder"]))@@ -70,20 +74,48 @@ def test_segment_length_is_rigid_to_pose_change():def test_body_only_input_returns_empty_hands():rig = RealtimeSkeletonRigidifier.create(height_mm=1750.0)- out = rig.rigidify_frame(_upright_rtmpose_pose()) # no hand keypoints+ out = _frame(rig, _upright_rtmpose_pose(), t=0.0) # no hand keypointsassert out.left_hand_positions == {}assert out.right_hand_positions == {}-def test_reset_forgets_learned_lengths():- # Reset must drop learned bone lengths back to the anthropometric seeds, so- # the next frame re-fits from scratch as if the pipeline had just started.+def test_predicted_points_never_teach_lengths():+ # Gap-filled (extrapolated) keypoints are excluded from `measured`: the+ # rigidified output still uses them, but they cannot move the estimates.rig = RealtimeSkeletonRigidifier.create(height_mm=1750.0)+ pose = _upright_rtmpose_pose()seed = rig.body_bone_lengths["left_shoulder->left_elbow"]- rig.rigidify_frame(_upright_rtmpose_pose())- learned = rig.body_bone_lengths["left_shoulder->left_elbow"]- assert abs(learned - seed) > 1.0 # a real measurement replaced the seed+ measured = dict(pose)+ del measured["left_elbow"] # simulated: elbow extrapolated this frame+ for i in range(6):+ rig.rigidify_frame(pose, measured=measured, t=float(i), errors=None)+ assert rig.body_bone_lengths["left_shoulder->left_elbow"] == pytest.approx(seed)- rig.reset()+def test_request_refit_reruns_capture_before_learning_again():+ rig = RealtimeSkeletonRigidifier.create(+ height_mm=1750.0,+ countdown_s=0.5,+ capture_min_visible_fraction=0.1,+ capture_consecutive_good_frames=3,+ )+ pose = _upright_rtmpose_pose()+ seed = rig.body_bone_lengths["left_shoulder->left_elbow"]+ for i in range(6):+ _frame(rig, pose, t=float(i))+ learned = rig.body_bone_lengths["left_shoulder->left_elbow"]+ assert abs(learned - seed) > 1.0 # consistent measurements replaced the seed++ rig.request_refit()+ _frame(rig, pose, t=10.0) # countdown begins; buffers clearedassert rig.body_bone_lengths["left_shoulder->left_elbow"] == pytest.approx(seed)+ assert rig.fit_state.state == "countdown"++ _frame(rig, pose, t=10.6) # deadline passed -> capture window opens+ # The required streak is max(3 configured, min_samples=5) = 5 consecutive+ # good frames β the freeze only captures bones that reached agreement.+ for i in range(6):+ _frame(rig, pose, t=10.7 + i * 0.1)+ assert rig.fit_state.state == "fitted"+ refit = rig.body_bone_lengths["left_shoulder->left_elbow"]+ assert refit == pytest.approx(learned, rel=0.05)diff --git a/freemocap/tests/rigid_body/test_segment_fit_ritual.py b/freemocap/tests/rigid_body/test_segment_fit_ritual.pynew file mode 100644index 00000000..ebc9c512--- /dev/null+++ b/freemocap/tests/rigid_body/test_segment_fit_ritual.py@@ -0,0 +1,227 @@+"""Unit tests for the segment-fit calibration ritual state machine."""+import numpy as np+import pytest++from freemocap.core.tasks.mocap.rigid_body.online_segment_lengths import OnlineBoneLengths+from freemocap.core.tasks.mocap.rigid_body.segment_fit_ritual import (+ FitRitualState,+ SegmentFitRitual,+)++# Measured bone lengths in the synthetic frames: 440 / 330 (seeds 400 / 300,+# both inside the fit_ratio=0.5 trust region).+HIPS = np.array([0.0, 0.0, 0.0])+SPINE = np.array([0.0, 440.0, 0.0])+CHEST = np.array([0.0, 770.0, 0.0])+NECK = np.array([0.0, 580.0, 0.0]) # |neck - spine| = 140, region [50, 150]++GOOD_FRAME = {"hips": HIPS, "spine": SPINE, "chest": CHEST}+++def _lengths(seeds: dict[str, float] | None = None, **overrides) -> OnlineBoneLengths:+ kwargs = dict(+ bone_seeds=seeds or {"hips->spine": 400.0, "spine->chest": 300.0},+ capacity=16,+ decay_tau_s=1e12,+ fit_ratio=0.5,+ min_samples=3,+ agreement_tol=0.05,+ )+ kwargs.update(overrides)+ return OnlineBoneLengths(**kwargs)+++def _ritual(body: OnlineBoneLengths, **overrides) -> SegmentFitRitual:+ kwargs = dict(+ body_lengths=body,+ rhand_lengths=_lengths({"ra->rb": 10.0}),+ lhand_lengths=_lengths({"la->lb": 10.0}),+ countdown_s=1.0,+ capture_min_visible_fraction=0.5,+ capture_max_mean_error_px=5.0,+ capture_consecutive_good_frames=3,+ capture_update_min_visible_fraction=0.25,+ capture_timeout_s=15.0,+ )+ kwargs.update(overrides)+ return SegmentFitRitual(**kwargs)+++def _frame(ritual: SegmentFitRitual, t: float, body_frame=None, errors_body=None) -> None:+ ritual.on_frame(+ measured_body=GOOD_FRAME if body_frame is None else body_frame,+ measured_rhand={},+ measured_lhand={},+ errors_body=errors_body,+ errors_rhand=None,+ errors_lhand=None,+ t=t,+ )+++def test_idle_updates_normally():+ body = _lengths()+ ritual = _ritual(body)+ for i in range(3):+ _frame(ritual, t=float(i))+ assert ritual.state == FitRitualState.IDLE+ assert body.lengths["hips->spine"] == pytest.approx(440.0)+ assert body.lengths["spine->chest"] == pytest.approx(330.0)+++def test_refit_countdown_blocks_updates_and_restores_seeds():+ body = _lengths()+ ritual = _ritual(body)+ for i in range(3):+ _frame(ritual, t=float(i))+ assert body.lengths["hips->spine"] == pytest.approx(440.0) # learned++ ritual.request_refit()+ _frame(ritual, t=10.0) # countdown begins; buffers cleared++ assert ritual.state == FitRitualState.COUNTDOWN+ assert body.lengths["hips->spine"] == 400.0 # back to the seed++ _frame(ritual, t=10.5) # deadline is 11.0 β still counting down+ assert body.lengths["hips->spine"] == 400.0 # no updates during countdown++ snap = ritual.snapshot()+ assert snap.state == "countdown"+ assert snap.countdown_remaining_s == pytest.approx(0.5)+ assert snap.visible_fraction == 1.0+++def test_capture_freezes_after_consecutive_good_frames():+ body = _lengths()+ ritual = _ritual(body)+ ritual.request_refit()+ _frame(ritual, t=10.0) # armed+ _frame(ritual, t=11.0) # deadline reached -> CAPTURING++ _frame(ritual, t=11.1) # good frame 1+ _frame(ritual, t=11.2) # good frame 2+ assert ritual.state == FitRitualState.CAPTURING+ assert body.lengths["hips->spine"] == 400.0 # not frozen yet++ _frame(ritual, t=11.3) # good frame 3 -> freeze+ assert ritual.state == FitRitualState.FITTED+ assert body.lengths["hips->spine"] == pytest.approx(440.0) # captured re-anchor+ assert body.lengths["spine->chest"] == pytest.approx(330.0)++ snap = ritual.snapshot()+ assert snap.n_fitted_body_bones == 2+ # Both captured lengths deviate 10% from their seeds.+ assert snap.median_seed_deviation == pytest.approx(0.1)+++def test_bad_frame_resets_good_streak():+ body = _lengths()+ ritual = _ritual(body)+ ritual.request_refit()+ _frame(ritual, t=10.0)+ _frame(ritual, t=11.0) # capturing++ _frame(ritual, t=11.1) # streak 1+ _frame(ritual, t=11.2) # streak 2+ _frame(ritual, t=11.3, body_frame={"hips": HIPS}) # low visibility -> streak 0+ _frame(ritual, t=11.4, errors_body={"hips": 50.0, "spine": 50.0, "chest": 50.0}) # high error -> 0+ assert ritual.state == FitRitualState.CAPTURING+ assert ritual.snapshot().capture_good_streak == 0++ _frame(ritual, t=11.5)+ _frame(ritual, t=11.6)+ assert ritual.state == FitRitualState.CAPTURING+ _frame(ritual, t=11.7)+ assert ritual.state == FitRitualState.FITTED+++def test_unfitted_bones_keep_seeds_and_stay_live():+ body = _lengths({"hips->spine": 400.0, "spine->chest": 300.0, "spine->neck": 100.0})+ ritual = _ritual(body)+ ritual.request_refit()+ _frame(ritual, t=10.0)+ _frame(ritual, t=11.0)+ for i in range(3):+ _frame(ritual, t=11.1 + i * 0.1) # neck never visible -> never agrees++ assert ritual.state == FitRitualState.FITTED+ assert body.lengths["spine->neck"] == 100.0 # seed kept (not captured)+ assert ritual.snapshot().n_fitted_body_bones == 2++ # FITTED keeps updating: the never-fitted bone can still learn, bounded+ # by its own (still anthropometric) trust region.+ full = dict(GOOD_FRAME, neck=NECK)+ for i in range(3):+ _frame(ritual, t=12.0 + i * 0.1, body_frame=full)+ assert body.lengths["spine->neck"] == pytest.approx(140.0)+++def test_fitted_drift_is_bounded_by_captured_anchor():+ body = _lengths()+ ritual = _ritual(body)+ ritual.request_refit()+ _frame(ritual, t=10.0)+ _frame(ritual, t=11.0)+ for i in range(3):+ _frame(ritual, t=11.1 + i * 0.1)+ assert ritual.state == FitRitualState.FITTED++ # A wild measurement after the freeze is rejected by the re-anchored+ # trust region (440 x (1 +/- 0.5) = [220, 660]).+ wild = dict(GOOD_FRAME, spine=np.array([0.0, 900.0, 0.0]))+ _frame(ritual, t=12.0, body_frame=wild)+ assert body.lengths["hips->spine"] == pytest.approx(440.0)+++def test_timeout_best_effort_freeze_fits_visible_bones():+ # The desk scenario: the "good" gate (min_visible=0.9) never passes+ # because a third of the body is always hidden, but updatable frames+ # (floor=0.5) still teach the visible bones β and the timeout ends the+ # ritual instead of capturing forever.+ body = _lengths()+ ritual = _ritual(+ body,+ capture_min_visible_fraction=0.9,+ capture_update_min_visible_fraction=0.5,+ capture_timeout_s=5.0,+ )+ ritual.request_refit()+ _frame(ritual, t=10.0)+ _frame(ritual, t=11.0) # capturing++ partial = {"hips": HIPS, "spine": SPINE} # 2/3 visible: updatable, never good+ for i in range(6):+ _frame(ritual, t=11.1 + i * 0.1, body_frame=partial)+ assert ritual.state == FitRitualState.CAPTURING+ assert ritual.snapshot().capture_good_streak == 0++ snap = ritual.snapshot()+ assert snap.capture_timeout_remaining_s == pytest.approx(5.0 - 0.6)++ _frame(ritual, t=16.1, body_frame=partial) # past the 5 s timeout+ assert ritual.state == FitRitualState.FITTED+ assert body.lengths["hips->spine"] == pytest.approx(440.0) # visible bone fitted+ assert body.lengths["spine->chest"] == 300.0 # hidden bone keeps its seed+ assert ritual.snapshot().n_fitted_body_bones == 1+++def test_timeout_without_any_agreement_returns_to_idle():+ # Every frame fails the error gate: nothing is updatable, nothing agrees,+ # so the timeout drops the ritual back to normal live fitting β seeds+ # untouched, no FITTED fanfare.+ body = _lengths()+ ritual = _ritual(body, capture_timeout_s=5.0)+ ritual.request_refit()+ _frame(ritual, t=10.0)+ _frame(ritual, t=11.0) # capturing++ noisy = {"hips": 50.0, "spine": 50.0, "chest": 50.0}+ _frame(ritual, t=11.5, errors_body=noisy)+ _frame(ritual, t=16.2, errors_body=noisy) # past the timeout+ assert ritual.state == FitRitualState.IDLE+ assert body.lengths["hips->spine"] == 400.0++ # IDLE resumes ungated live fitting.+ for i in range(3):+ _frame(ritual, t=17.0 + i * 0.1)+ assert body.lengths["hips->spine"] == pytest.approx(440.0)diff --git a/uv.lock b/uv.lockindex 7cdf91a1..63b86a12 100644--- a/uv.lock+++ b/uv.lock@@ -371,7 +371,7 @@ wheels = [[[package]]name = "freemocap"-version = "2.0.0a8"+version = "2.0.0a11"source = { editable = "." }dependencies = [{ name = "beartype", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32') or sys_platform == 'darwin'" },