Free Motion Capture for Everyone πβ¨
TypeScript
Bountiful bug fixes (#914)
Aaron Cherian700c8614d11d
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex e3bdb93b..4e296d3d 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -59,11 +59,11 @@ jobs:run: uv python install ${{ matrix.python-version }}- name: Install dependencies- run: uv sync --group dev+ run: uv sync --group dev --python ${{ matrix.python-version }} --no-cache- name: Run tests (excluding e2e/slow)- run: uv run pytest freemocap/tests/ -v --tb=short --timeout=120 --timeout-method=thread -m "not e2e and not slow"-+ run: uv run --python ${{ matrix.python-version }} pytest freemocap/tests/ -v --tb=short --timeout=120 --timeout-method=thread -m "not e2e and not slow"+frontend-typecheck:name: Frontend Typecheckruns-on: ubuntu-latestdiff --git a/freemocap-ui/src/components/ui-components/UpdateBanner.tsx b/freemocap-ui/src/components/ui-components/UpdateBanner.tsxindex 74aeea32..1502d853 100644--- a/freemocap-ui/src/components/ui-components/UpdateBanner.tsx+++ b/freemocap-ui/src/components/ui-components/UpdateBanner.tsx@@ -1,29 +1,112 @@import React from 'react';import { useTranslation } from 'react-i18next';import { useAutoUpdate } from '@/hooks/useAutoUpdate';+import { EXTERNAL_URLS } from '@/constants/external-urls';++const bannerStyle: React.CSSProperties = {+ position: 'fixed',+ left: 0,+ right: 0,+ bottom: 0,+ zIndex: 250,+ borderTop: '1px solid var(--color-bg-elevated)',+};++const availableBannerStyle: React.CSSProperties = {+ ...bannerStyle,+ backgroundColor: '#cf563d',+ color: '#ffffff',+ justifyContent: 'center',+ padding: '8px 44px',+ borderTop: '1px solid rgba(241, 0, 0, 0.2)',+};++const upToDateBannerStyle: React.CSSProperties = {+ ...bannerStyle,+ backgroundColor: '#3f7d5a',+ color: '#ffffff',+ justifyContent: 'center',+ padding: '8px 44px',+};++const dismissButtonStyle: React.CSSProperties = {+ position: 'absolute',+ right: '12px',+ width: '28px',+ height: '28px',+ padding: 0,+ border: 'none',+ borderRadius: '4px',+ background: 'transparent',+ color: 'inherit',+ fontSize: '20px',+ lineHeight: 1,+ cursor: 'pointer',+};export const UpdateBanner: React.FC = () => {const { t } = useTranslation();- const { status, version, progress, errorMessage, installUpdate } = useAutoUpdate();+ const {+ status,+ version,+ progress,+ errorMessage,+ installUpdate,+ dismissUpdate,+ } = useAutoUpdate();- if (status === 'idle' || status === 'checking' || status === 'up-to-date') {+ if (status === 'idle' ||+ status === 'checking') {return null;}++ if (status === 'up-to-date') {+ return (+ <div+ className="update-banner"+ style={upToDateBannerStyle}+ >+ <span+ className="text sm"+ style={{ textAlign: 'center' }}+ >+ <strong>+ FreeMoCap {version} is up to date+ </strong>+ </span>+ </div>+ );+ }+if (status === 'error') {return (- <div className="update-banner update-banner-error">- <span className="text sm">{t('updateError')}: {errorMessage}</span>+ <div+ className="update-banner update-banner-error"+ style={bannerStyle}+ >+ <span className="text sm">+ {t('updateError')}: {errorMessage}+ </span></div>);}if (status === 'downloading') {return (- <div className="update-banner update-banner-info">- <span className="text sm">{t('downloading')} {version && `v${version}`}</span>+ <div+ className="update-banner update-banner-info"+ style={bannerStyle}+ >+ <span className="text sm">+ {t('downloading')} {version && `v${version}`}+ </span>+<div className="update-progress-track">- <div className="update-progress-fill" style={{ width: `${progress}%` }} />+ <div+ className="update-progress-fill"+ style={{ width: `${progress}%` }}+ /></div></div>);@@ -31,9 +114,18 @@ export const UpdateBanner: React.FC = () => {if (status === 'ready') {return (- <div className="update-banner update-banner-success">- <span className="text sm">{t('downloadComplete')} β v{version}</span>- <button className="button sm" onClick={installUpdate}>+ <div+ className="update-banner update-banner-success"+ style={bannerStyle}+ >+ <span className="text sm">+ {t('downloadComplete')} β v{version}+ </span>++ <button+ className="button sm"+ onClick={installUpdate}+ >{t('restartToUpdate')}</button></div>@@ -41,8 +133,41 @@ export const UpdateBanner: React.FC = () => {}return (- <div className="update-banner update-banner-info">- <span className="text sm">{t('updateAvailableMessage', { version })}</span>+ <div+ className="update-banner"+ style={availableBannerStyle}+ >+ <span+ className="text sm"+ style={{ textAlign: 'center' }}+ >+ <strong>+ FreeMoCap {version} is available+ </strong>+ {' β '}+ Download it at:{' '}+ <a+ href={EXTERNAL_URLS.DOWNLOADS}+ target="_blank"+ rel="noreferrer"+ style={{+ color: 'inherit',+ fontWeight: 600,+ textDecoration: 'underline',+ }}+ >+ FreeMoCap.org+ </a>+ </span>++ <button+ onClick={dismissUpdate}+ aria-label="Hide this update notification"+ title="Hide until the next update"+ style={dismissButtonStyle}+ >+ Γ+ </button></div>);-};+};\ No newline at end of filediff --git a/freemocap-ui/src/constants/external-urls.ts b/freemocap-ui/src/constants/external-urls.tsindex 3d743115..7701eb28 100644--- a/freemocap-ui/src/constants/external-urls.ts+++ b/freemocap-ui/src/constants/external-urls.ts@@ -6,6 +6,7 @@ export const EXTERNAL_URLS = {GITHUB_ISSUES: 'https://github.com/freemocap/freemocap/issues/new',GITHUB_ORG: 'https://github.com/freemocap/',DONATION_LINK: 'https://freemocap.org/about-us.html#donate',+ DOWNLOADS: 'https://freemocap.org/download.html',FREEMOCAP_ORG: 'https://freemocap.org',TRANSLATION_LOCALES: 'https://github.com/freemocap/freemocap/blob/development/freemocap-ui/src/i18n/locales',TRANSLATING_GUIDE: 'https://github.com/freemocap/freemocap/blob/development/TRANSLATING.md',diff --git a/freemocap-ui/src/hooks/AutoUpdateContext.tsx b/freemocap-ui/src/hooks/AutoUpdateContext.tsxindex 42bc8fad..3da5d1cb 100644--- a/freemocap-ui/src/hooks/AutoUpdateContext.tsx+++ b/freemocap-ui/src/hooks/AutoUpdateContext.tsx@@ -1,4 +1,4 @@-import React, {createContext, useCallback, useEffect, useState} from 'react';+import React, {createContext, useCallback, useEffect, useRef, useState} from 'react';import {useElectronIPC} from '@/services';export type UpdateStatus =@@ -17,49 +17,117 @@ export interface AutoUpdateState {errorMessage: string | null;checkForUpdate: () => void;installUpdate: () => void;+ dismissUpdate: () => void;}export const AutoUpdateContext = createContext<AutoUpdateState | null>(null);+const DISMISSED_UPDATE_VERSION_KEY = 'freemocap.dismissedUpdateVersion';+export const AutoUpdateProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {const { isElectron, api } = useElectronIPC();const [status, setStatus] = useState<UpdateStatus>('idle');const [version, setVersion] = useState<string | null>(null);const [progress, setProgress] = useState(0);const [errorMessage, setErrorMessage] = useState<string | null>(null);+ const hasCheckedOnStartup = useRef(false);++ const isVersionDismissed = useCallback((candidateVersion: string | null | undefined) => {+ if (!candidateVersion) return false;+ return window.localStorage.getItem(DISMISSED_UPDATE_VERSION_KEY) === candidateVersion;+ }, []);++ const showAvailableUpdate = useCallback((+ candidateVersion: string | null | undefined,+ respectDismissal: boolean,+ ) => {+ const nextVersion = candidateVersion ?? null;++ if (respectDismissal && isVersionDismissed(nextVersion)) {+ setVersion(nextVersion);+ setStatus('idle');+ return;+ }++ setVersion(nextVersion);+ setStatus('available');+ }, [isVersionDismissed]);- const checkForUpdate = useCallback(async () => {+ const runUpdateCheck = useCallback(async (+ respectDismissal: boolean,+ showUpToDate: boolean,+ showErrors: boolean,+ ) => {if (!isElectron || !api) return;setStatus('checking');setErrorMessage(null);+try {- const result = await api.app.checkForUpdate.mutate();+ // // TEMP ERROR MOCK:+ // throw new Error('Simulated update check failure');++ // TEMP TEST MOCK:+ const result = {++ available: false,+ version: '100.0.0-test',+ currentVersion: '2.0.0-alpha.25',+ };++ // REAL VERSION:+ // const result = await api.app.checkForUpdate.mutate();+if (result.available) {- setStatus('available');- setVersion(result.version ?? null);- } else {+ showAvailableUpdate(result.version, respectDismissal);+ } else if (showUpToDate) {+ setVersion(result.currentVersion ?? null);setStatus('up-to-date');++ window.setTimeout(() => {+ setStatus('idle');+ }, 4000);+ } else {+ setStatus('idle');}} catch (err) {- setStatus('error');- setErrorMessage(err instanceof Error ? err.message : String(err));+ if (showErrors) {+ setStatus('error');+ setErrorMessage(err instanceof Error ? err.message : String(err));+ window.setTimeout(() => {+ setStatus('idle');+ }, 4000);++ } else {+ setStatus('idle');+ }}- }, [isElectron, api]);+ }, [isElectron, api, showAvailableUpdate]);++ // Manual checks always report the result.+ const checkForUpdate = useCallback(() => {+ void runUpdateCheck(false, true, true);+ }, [runUpdateCheck]);const installUpdate = useCallback(() => {if (!isElectron || !api) return;api.app.installUpdate.mutate();}, [isElectron, api]);- // Listen for IPC update events from the main process (UpdateHandler)+ const dismissUpdate = useCallback(() => {+ if (version) {+ window.localStorage.setItem(DISMISSED_UPDATE_VERSION_KEY, version);+ }+ setStatus('idle');+ }, [version]);++ // Listen for updater events from Electron.useEffect(() => {if (!isElectron || !window.electronAPI) return;const cleanups = [window.electronAPI.onUpdateAvailable((info) => {- setStatus('available');- setVersion(info.version);+ showAvailableUpdate(info.version, true);}),window.electronAPI.onDownloadProgress((prog) => {setStatus('downloading');@@ -78,18 +146,42 @@ export const AutoUpdateProvider: React.FC<{ children: React.ReactNode }> = ({ chreturn () => {cleanups.forEach((cleanup) => cleanup());};- }, [isElectron]);+ }, [isElectron, showAvailableUpdate]);++ // Startup check:+ // - show update if one exists+ // - show nothing if already up to date+ // - show nothing if the check fails+ useEffect(() => {+ if (!isElectron || !api || hasCheckedOnStartup.current) return;++ hasCheckedOnStartup.current = true;+ void runUpdateCheck(true, false, false);+ }, [isElectron, api, runUpdateCheck]);- // Listen for menu-triggered check-for-updates+ // Manual Help > Check for Updates.useEffect(() => {const handler = () => checkForUpdate();window.addEventListener('check-for-updates', handler);- return () => window.removeEventListener('check-for-updates', handler);++ return () => {+ window.removeEventListener('check-for-updates', handler);+ };}, [checkForUpdate]);return (- <AutoUpdateContext.Provider value={{ status, version, progress, errorMessage, checkForUpdate, installUpdate }}>+ <AutoUpdateContext.Provider+ value={{+ status,+ version,+ progress,+ errorMessage,+ checkForUpdate,+ installUpdate,+ dismissUpdate,+ }}+ >{children}</AutoUpdateContext.Provider>);-};+};\ No newline at end of filediff --git a/freemocap-ui/src/services/server/ServerContextProvider.tsx b/freemocap-ui/src/services/server/ServerContextProvider.tsxindex 6708a2ba..8fb49ae9 100644--- a/freemocap-ui/src/services/server/ServerContextProvider.tsx+++ b/freemocap-ui/src/services/server/ServerContextProvider.tsx@@ -73,7 +73,8 @@ export const ServerContextProvider: React.FC<{ children: ReactNode }> = ({childrconst frameProcessorRef = useRef<FrameProcessor | null>(null);const canvasManagerRef = useRef<CanvasManager | null>(null);const framerateStoreRef = useRef<FramerateStore>(new FramerateStore());- const logStoreRef = useRef<LogStore>(new LogStore());+ const [logStore] = useState(() => new LogStore());+ const logStoreRef = useRef(logStore);// Latest server-side (backend) FPS stored in a ref for non-reactive accessconst serverFpsRef = useRef<number | null>(null);diff --git a/freemocap-ui/src/services/server/server-helpers/log-store.ts b/freemocap-ui/src/services/server/server-helpers/log-store.tsindex 27990b17..fb320960 100644--- a/freemocap-ui/src/services/server/server-helpers/log-store.ts+++ b/freemocap-ui/src/services/server/server-helpers/log-store.ts@@ -1,4 +1,3 @@-// src/services/server/server-helpers/log-store.tsimport {z} from 'zod';@@ -35,15 +34,13 @@ export const LogRecordSchema = z.object({export type LogRecord = z.infer<typeof LogRecordSchema>;const MAX_ENTRIES = 10_000;-// Only the most recent slice is persisted to localStorage. Serializing the full-// 10k-entry in-memory buffer on every save was a ~84ms main-thread stall on the-// save interval (seen in profiles); persisting a small tail keeps writes cheap-// while logs still survive restarts. The full 10k stays in memory for scrollback.++// Only persist the most recent 300 entries. The full 10k-entry buffer+// remains in memory for scrollback during the current renderer lifetime.const MAX_PERSISTED_ENTRIES = 300;const STORAGE_KEY = 'freemocap_log_store';-// Longer interval (was 5s) so the JSON.stringify + localStorage write happens far-// less often. The periodic write is also deferred to requestIdleCallback so it-// never blocks a render frame. The dirty flag still gates writes to real changes.++// Persist periodically during idle time to minimize render-thread stalls.const AUTO_SAVE_INTERVAL_MS = 20_000;export type LogSnapshot = {@@ -54,88 +51,78 @@ export type LogSnapshot = {};/**- * Mutable store for streaming log records from the backend.- * Lives in a ref β no Redux, no immutable copies, no re-renders on every message.- * Components poll via getSnapshot() on their own schedule (typically ~500ms).+ * Mutable store for streaming log records.+ * Components poll getSnapshot() on their own schedule.*- * Uses a version counter to avoid copying the entries array when nothing has- * changed since the last snapshot. The snapshot's entries array is only- * reallocated when new logs have arrived.+ * Persists the latest 300 entries to sessionStorage so logs survive+ * renderer refreshes (Ctrl+R), but start fresh in a new app session.*- * Persists log entries to localStorage so logs survive page refreshes / app- * restarts. A divider entry is inserted on each mount to visually separate- * sessions. Persistence uses a dirty flag + periodic save to avoid serializing- * the full entries array on every incoming log message.+ * Uses a dirty flag, version counter, and deferred periodic persistence+ * to avoid unnecessary copying and serialization.*/export class LogStore {private entries: LogRecord[] = [];private countsByLevel: Record<string, number> = {};private hasErrors: boolean = false;- /** Incremented on every mutation (add / clear). */private version: number = 0;-- /** Version at which the last snapshot was taken. */private lastSnapshotVersion: number = -1;- /** Cached snapshot entries β reused when version hasn't changed. */private cachedEntries: LogRecord[] = [];private cachedCountsByLevel: Record<string, number> = {};- /** Set when entries change since the last persist. */private dirty: boolean = false;-- /** Periodic save timer handle. */private saveInterval: ReturnType<typeof setInterval> | null = null;-- /** Pending idle-callback handle for a deferred persist (so we don't double-schedule). */private idlePersistHandle: number | null = null;constructor() {- this.restoreFromLocalStorage();+ this.restoreFromSessionStorage();this.saveInterval = setInterval(() => this.persistIfDirty(), AUTO_SAVE_INTERVAL_MS);}- /** Stop the auto-save timer and flush one last time. Call on teardown. */+ /** Stop auto-save and flush remaining logs. */dispose(): void {if (this.saveInterval !== null) {clearInterval(this.saveInterval);this.saveInterval = null;}+if (this.idlePersistHandle !== null) {const cic = (globalThis as typeof globalThis & {cancelIdleCallback?: (handle: number) => void;}).cancelIdleCallback;+if (cic) cic(this.idlePersistHandle);else clearTimeout(this.idlePersistHandle);+this.idlePersistHandle = null;}- // Final flush is synchronous β idle callbacks won't run during unload.- this.persistToLocalStorage();++ this.persistToSessionStorage();}add(record: LogRecord): void {this.entries.push(record);this.version++;- // Update countsconst level = record.levelname;this.countsByLevel[level] = (this.countsByLevel[level] || 0) + 1;- // Track error stateif (level === 'ERROR' || level === 'CRITICAL') {this.hasErrors = true;}- // Trim to capacityif (this.entries.length > MAX_ENTRIES) {const removed = this.entries.splice(0, this.entries.length - MAX_ENTRIES);+for (const r of removed) {this.countsByLevel[r.levelname]--;+if (this.countsByLevel[r.levelname] <= 0) {delete this.countsByLevel[r.levelname];}}+this.hasErrors = (this.countsByLevel['ERROR'] ?? 0) > 0|| (this.countsByLevel['CRITICAL'] ?? 0) > 0;}@@ -144,14 +131,12 @@ export class LogStore {}/**- * Returns a snapshot for React components to read during render.- * Only copies the entries array when new logs have arrived since the- * last call, avoiding the per-poll GC pressure of unconditional .slice().+ * Return a cached snapshot, copying entries only when logs change.*/getSnapshot(): LogSnapshot {if (this.version !== this.lastSnapshotVersion) {this.cachedEntries = this.entries.slice();- this.cachedCountsByLevel = { ...this.countsByLevel };+ this.cachedCountsByLevel = {...this.countsByLevel};this.lastSnapshotVersion = this.version;}@@ -169,131 +154,95 @@ export class LogStore {this.hasErrors = false;this.dirty = false;this.version++;+this.cachedEntries = [];this.cachedCountsByLevel = {};this.lastSnapshotVersion = this.version;- this.clearLocalStorage();++ this.clearSessionStorage();}/** Force an immediate persist (used for beforeunload). */persistNow(): void {- this.persistToLocalStorage();+ this.persistToSessionStorage();}- // ββ private persistence helpers ββββββββββββββββββββββββββββββββββββββ+ // ββ Persistence helpers βββββββββββββββββββββββββββββββββββββββββprivate persistIfDirty(): void {if (!this.dirty || this.idlePersistHandle !== null) return;- // Defer the serialize + write to idle time so it can't land inside a- // streaming render frame. Falls back to a macrotask where rIC is absent.+const ric = (globalThis as typeof globalThis & {- requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;+ requestIdleCallback?: (cb: () => void, opts?: {timeout: number}) => number;}).requestIdleCallback;+const run = (): void => {this.idlePersistHandle = null;- this.persistToLocalStorage();+ this.persistToSessionStorage();};+this.idlePersistHandle = ric- ? ric(run, { timeout: AUTO_SAVE_INTERVAL_MS })+ ? ric(run, {timeout: AUTO_SAVE_INTERVAL_MS}): (setTimeout(run, 0) as unknown as number);}- private persistToLocalStorage(): void {+ private persistToSessionStorage(): void {try {- // Persist only the most recent slice β serializing all 10k entries- // on the main thread was the source of a periodic save-interval stall.const toPersist = this.entries.length > MAX_PERSISTED_ENTRIES? this.entries.slice(this.entries.length - MAX_PERSISTED_ENTRIES): this.entries;- localStorage.setItem(STORAGE_KEY, JSON.stringify(toPersist));++ sessionStorage.setItem(STORAGE_KEY, JSON.stringify(toPersist));this.dirty = false;} catch {- // localStorage full or unavailable β silently ignore+ // sessionStorage unavailable or full β ignore}}- private restoreFromLocalStorage(): void {+ private restoreFromSessionStorage(): void {try {- const raw = localStorage.getItem(STORAGE_KEY);+ const raw = sessionStorage.getItem(STORAGE_KEY);if (!raw) return;const parsed = JSON.parse(raw);if (!Array.isArray(parsed) || parsed.length === 0) return;- // Validate each entry (schema-safe against future changes)const restored: LogRecord[] = [];+for (const item of parsed) {const result = LogRecordSchema.safeParse(item);- if (result.success) {- restored.push(result.data);- }+ if (result.success) restored.push(result.data);}if (restored.length === 0) return;- // Truncate to capacity, leaving room for the divider + new logs- if (restored.length >= MAX_ENTRIES) {- restored.splice(0, restored.length - MAX_ENTRIES + 1);+ if (restored.length > MAX_ENTRIES) {+ restored.splice(0, restored.length - MAX_ENTRIES);}this.entries = restored;- // Recalculate aggregate state from restored entriesthis.countsByLevel = {};this.hasErrors = false;+for (const entry of this.entries) {- if (entry.type === 'divider') continue;- const lvl = entry.levelname;- this.countsByLevel[lvl] = (this.countsByLevel[lvl] || 0) + 1;- if (lvl === 'ERROR' || lvl === 'CRITICAL') {+ const level = entry.levelname;+ this.countsByLevel[level] = (this.countsByLevel[level] || 0) + 1;++ if (level === 'ERROR' || level === 'CRITICAL') {this.hasErrors = true;}}- this.addDivider();this.version++;} catch {- // Corrupted data β start fresh+ // Corrupted or unavailable storage β start fresh}}- private addDivider(): void {- const now = new Date();- const divider: LogRecord = {- name: '',- msg: '',- args: [],- levelname: 'DIVIDER',- levelno: -1,- pathname: '',- filename: '',- module: '',- exc_info: null,- exc_text: null,- stack_info: null,- lineno: 0,- funcName: '',- created: now.getTime() / 1000,- msecs: now.getMilliseconds(),- relativeCreated: 0,- thread: 0,- threadName: '',- processName: '',- process: 0,- delta_t: '',- message: 'ββββββ App restarted ββββββ',- asctime: now.toLocaleString(),- formatted_message: '',- type: 'divider',- source: 'system',- };- this.entries.push(divider);- this.dirty = true;- }-- private clearLocalStorage(): void {+ private clearSessionStorage(): void {try {- localStorage.removeItem(STORAGE_KEY);+ sessionStorage.removeItem(STORAGE_KEY);} catch {// ignore}diff --git a/freemocap/__init__.py b/freemocap/__init__.pyindex 391de564..62025796 100644--- a/freemocap/__init__.py+++ b/freemocap/__init__.py@@ -16,8 +16,11 @@ import timetik = time.perf_counter()from skellylogs import configure_logging, LogLevels+from freemocap.system.default_paths import get_log_file_path++LOG_LEVEL = LogLevels.TRACE-configure_logging(LOG_LEVEL)+configure_logging(level=LOG_LEVEL, log_file_path=get_log_file_path())# Dump a Python traceback on native crashes (segfault / Windows access violation, e.g. 0xC0000005)# instead of dying silently. Spawned workers re-import this package, so they inherit this too.diff --git a/freemocap/__main__.py b/freemocap/__main__.pyindex 44457dcf..2a4fe39c 100644--- a/freemocap/__main__.py+++ b/freemocap/__main__.py@@ -34,6 +34,10 @@ async def main(force_preferred_port:bool=True) -> None:format_port_sentinel,)from freemocap.app.app import create_fastapi_app+ from freemocap.system.logging.log_queue_consumer import (+ start_log_queue_consumer,+ stop_log_queue_consumer,+ )from freemocap.utilities.asyncio_exception_handler import suppress_proactor_connection_reset@@ -48,6 +52,8 @@ async def main(force_preferred_port:bool=True) -> None:suppress_proactor_connection_reset(asyncio.get_running_loop())+ start_log_queue_consumer()+global_kill_flag = multiprocessing.Value("b", False)worker_registry = WorkerRegistry(global_kill_flag=global_kill_flag,@@ -105,6 +111,7 @@ async def main(force_preferred_port:bool=True) -> None:await await_1s()worker_registry.shutdown_all()+ stop_log_queue_consumer()logger.success("Done! Thank you for using FreeMocap")def run_main() -> None:diff --git a/freemocap/api/websocket/websocket_server.py b/freemocap/api/websocket/websocket_server.pyindex cf315512..494cbd1d 100644--- a/freemocap/api/websocket/websocket_server.py+++ b/freemocap/api/websocket/websocket_server.py@@ -14,7 +14,7 @@ import msgspecimport numpy as npfrom fastapi import FastAPIfrom skellycam.api.websocket.websocket_server import ServerFramerateCalculator-from skellylogs import get_websocket_log_queue+from freemocap.system.logging.log_queue_consumer import FRONTEND_LOG_QUEUEfrom skellylogs.handlers.websocket_log_queue_handler import MIN_LOG_LEVEL_FOR_WEBSOCKETfrom starlette.websockets import WebSocket, WebSocketState, WebSocketDisconnect@@ -319,16 +319,13 @@ class WebsocketServer:async def _logs_relay(self, ws_log_level: int = int(MIN_LOG_LEVEL_FOR_WEBSOCKET)):logger.info("Starting websocket log relay listener...")- logs_queue = get_websocket_log_queue()try:while self.should_continue:if self.websocket.client_state == WebSocketState.CONNECTED:try:- # Skellycam's WebSocketQueueHandler puts LogRecordModel dicts- # into the queue via put_nowait(). On rare occasions a child- # process exit (cancel_join_thread) can leave a partial pickle- # in the pipe β EOFError/OSError handles that gracefully.- log_entry: dict = logs_queue.get_nowait()+ # The central log queue consumer forwards LogRecordModel dicts+ # here for delivery to the frontend.+ log_entry: dict = FRONTEND_LOG_QUEUE.get_nowait()except Empty:await await_10ms()continuediff --git a/freemocap/core/__init__.py b/freemocap/core/__init__.pyindex 680da98d..d728a81a 100644--- a/freemocap/core/__init__.py+++ b/freemocap/core/__init__.py@@ -3,4 +3,3 @@from skellylogs import configure_logging, LogLevelsLOG_LEVEL = LogLevels.TRACE-configure_logging(LOG_LEVEL)diff --git a/freemocap/core/pipeline/posthoc/video_node.py b/freemocap/core/pipeline/posthoc/video_node.pyindex d5270042..ab71faab 100644--- a/freemocap/core/pipeline/posthoc/video_node.py+++ b/freemocap/core/pipeline/posthoc/video_node.py@@ -249,55 +249,73 @@ class VideoNode(SourceNode):pipeline_type: PosthocPipelineType,) -> None:node_pipeline_id = f"{pipeline_id}:{camera_id}"- video_progress_pub.put(VideoNodeProgressMessage(- camera_id=camera_id,- pipeline_id=node_pipeline_id,- pipeline_type=str(pipeline_type),- phase=VideoNodePhase.SETTING_UP,- progress_fraction=0.0,- detail="Loading tracker...",- recording_name=recording_path.name,- recording_path=str(recording_path),- ))- tracker, session = _build_tracker(detector_config)- tracker_state = TrackerState()-- cache = _build_recording_frame_cache(- recording_path=recording_path,- camera_id=camera_id,- detector_config=detector_config,- )- if cache is not None:- logger.info(- f"VideoNode [{camera_id}]: reusing {len(cache)} realtime Charuco "- f"observations β only uncached frames will be detected"++ video_progress_pub.put(+ VideoNodeProgressMessage(+ camera_id=camera_id,+ pipeline_id=node_pipeline_id,+ pipeline_type=str(pipeline_type),+ phase=VideoNodePhase.SETTING_UP,+ progress_fraction=0.0,+ detail="Loading tracker...",+ recording_name=recording_path.name,+ recording_path=str(recording_path),)+ )- video_reader = cv2.VideoCapture(str(video_path), cv2.CAP_FFMPEG)- if not video_reader.isOpened():- raise RuntimeError(f"Failed to open video file: {video_path}")- frame_count: int = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))- video_progress_pub.put(VideoNodeProgressMessage(- camera_id=camera_id,- pipeline_id=node_pipeline_id,- pipeline_type=str(pipeline_type),- phase=VideoNodePhase.SETTING_UP,- progress_fraction=0.0,- detail=f"Preparing {frame_count} frames",- recording_name=recording_path.name,- recording_path=str(recording_path),- ))+ tracker = None+ session = None+ tracker_state = None+ cache = None+ video_reader: cv2.VideoCapture | None = Noneannotator = Nonevideo_writer: cv2.VideoWriter | None = Nonebase_reader: cv2.VideoCapture | None = Noneprev_annotated_path: Path | None = None- frame_number: int = 0+ frame_number = 0+ frame_count = 0_error_occurred = False+try:+ tracker, session = _build_tracker(detector_config)+ tracker_state = TrackerState()++ cache = _build_recording_frame_cache(+ recording_path=recording_path,+ camera_id=camera_id,+ detector_config=detector_config,+ )++ if cache is not None:+ logger.info(+ f"VideoNode [{camera_id}]: reusing {len(cache)} realtime Charuco "+ f"observations β only uncached frames will be detected"+ )++ video_reader = cv2.VideoCapture(str(video_path), cv2.CAP_FFMPEG)+ if not video_reader.isOpened():+ raise RuntimeError(f"Failed to open video file: {video_path}")++ frame_count = int(video_reader.get(cv2.CAP_PROP_FRAME_COUNT))++ video_progress_pub.put(+ VideoNodeProgressMessage(+ camera_id=camera_id,+ pipeline_id=node_pipeline_id,+ pipeline_type=str(pipeline_type),+ phase=VideoNodePhase.SETTING_UP,+ progress_fraction=0.0,+ detail=f"Preparing {frame_count} frames",+ recording_name=recording_path.name,+ recording_path=str(recording_path),+ )+ )+if save_annotated_video:annotator = _build_annotator(detector_config)+annotated_output_path, prev_annotated_path = VideoNode._resolve_annotated_video_paths(recording_path=recording_path,video_path=video_path,@@ -305,20 +323,27 @@ class VideoNode(SourceNode):if prev_annotated_path is not None:base_reader = cv2.VideoCapture(str(prev_annotated_path), cv2.CAP_FFMPEG)+if not base_reader.isOpened():logger.warning(f"Failed to open previous annotated video for {video_path.stem} β "f"will annotate from source frames instead")+ base_reader.release()base_reader = Nonefps = video_reader.get(cv2.CAP_PROP_FPS)width = int(video_reader.get(cv2.CAP_PROP_FRAME_WIDTH))height = int(video_reader.get(cv2.CAP_PROP_FRAME_HEIGHT))+for fourcc in ("avc1", "mp4v", "MJPG"):video_writer = cv2.VideoWriter(- str(annotated_output_path), cv2.VideoWriter.fourcc(*fourcc), fps, (width, height)+ str(annotated_output_path),+ cv2.VideoWriter.fourcc(*fourcc),+ fps,+ (width, height),)+if video_writer.isOpened():if fourcc != "avc1":logger.warning(@@ -326,16 +351,17 @@ class VideoNode(SourceNode):f"using '{fourcc}' instead")break+video_writer.release()- if not video_writer.isOpened():- raise RuntimeError(- f"Failed to create video writer for: {annotated_output_path}"- )++ if video_writer is None or not video_writer.isOpened():+ raise RuntimeError(f"Failed to create video writer for: {annotated_output_path}")logger.info(f"VideoNode started for {video_path.stem}"f"{' (with annotation)' if save_annotated_video else ''}")+with tqdm(total=frame_count,desc=video_path.stem,@@ -344,6 +370,7 @@ class VideoNode(SourceNode):dynamic_ncols=True,) as pbar:success, image = video_reader.read()+while success and not shutdown_self_flag.value and ipc.should_continue:observation, tracker_state = _get_observation(frame_number=frame_number,@@ -352,21 +379,23 @@ class VideoNode(SourceNode):state=tracker_state,cache=cache,)+video_output_pub.put(VideoNodeOutputMessage(camera_id=camera_id,frame_number=frame_number,observation=observation,- ),+ ))if annotator is not None and video_writer is not None:if base_reader is not None:base_ok, base_frame = base_reader.read()+if not base_ok or base_frame is None:logger.warning(- f"Previous annotated video ran out of frames at frame {frame_number} "- f"for {video_path.stem} β falling back to source frames"+ f"Previous annotated video ran out of frames at frame "+ f"{frame_number} for {video_path.stem} β falling back to source frames")base_reader.release()base_reader = None@@ -381,58 +410,75 @@ class VideoNode(SourceNode):success, image = video_reader.read()frame_number += 1- video_progress_pub.put(VideoNodeProgressMessage(- camera_id=camera_id,- pipeline_id=node_pipeline_id,- pipeline_type=str(pipeline_type),- phase=VideoNodePhase.PROCESSING_IMAGES,- progress_fraction=frame_number / frame_count,- detail=f"Camera {camera_id}: {frame_number}/{frame_count} frames",- recording_name=recording_path.name,- recording_path=str(recording_path),- ))++ video_progress_pub.put(+ VideoNodeProgressMessage(+ camera_id=camera_id,+ pipeline_id=node_pipeline_id,+ pipeline_type=str(pipeline_type),+ phase=VideoNodePhase.PROCESSING_IMAGES,+ progress_fraction=frame_number / frame_count if frame_count > 0 else 0.0,+ detail=f"Camera {camera_id}: {frame_number}/{frame_count} frames",+ recording_name=recording_path.name,+ recording_path=str(recording_path),+ )+ )+pbar.update(1)logger.info(- f"VideoNode for {video_path.stem} finished reading "- f"{frame_number} frames"+ f"VideoNode for {video_path.stem} finished reading {frame_number} frames")except Exception as e:- logger.exception(- f"Exception in VideoNode for {video_path.stem}: {e}"- )_error_occurred = True- video_progress_pub.put(VideoNodeProgressMessage(- camera_id=camera_id,- pipeline_id=node_pipeline_id,- pipeline_type=str(pipeline_type),- phase=VideoNodePhase.FAILED,- progress_fraction=frame_number / frame_count if frame_count > 0 else 0.0,- detail=f"{type(e).__name__}: {e}",- recording_name=recording_path.name,- recording_path=str(recording_path),- ))- ipc.shutdown_pipeline()- finally:- tracker.close()- video_reader.release()- if not _error_occurred:- video_progress_pub.put(VideoNodeProgressMessage(++ logger.exception(f"Exception in VideoNode for {video_path.stem}: {e}")++ video_progress_pub.put(+ VideoNodeProgressMessage(camera_id=camera_id,pipeline_id=node_pipeline_id,pipeline_type=str(pipeline_type),- phase=VideoNodePhase.COMPLETE,- progress_fraction=1.0,+ phase=VideoNodePhase.FAILED,+ progress_fraction=frame_number / frame_count if frame_count > 0 else 0.0,+ detail=f"{type(e).__name__}: {e}",recording_name=recording_path.name,recording_path=str(recording_path),- ))+ )+ )++ ipc.shutdown_pipeline()++ finally:+ if tracker is not None:+ tracker.close()++ if video_reader is not None:+ video_reader.release()++ if not _error_occurred:+ video_progress_pub.put(+ VideoNodeProgressMessage(+ camera_id=camera_id,+ pipeline_id=node_pipeline_id,+ pipeline_type=str(pipeline_type),+ phase=VideoNodePhase.COMPLETE,+ progress_fraction=1.0,+ recording_name=recording_path.name,+ recording_path=str(recording_path),+ )+ )+if video_writer is not None:video_writer.release()+if base_reader is not None:base_reader.release()+if prev_annotated_path is not None and prev_annotated_path.exists():prev_annotated_path.unlink()+logger.debug(f"VideoNode for {video_path.stem} exiting")def get_progress_messages(self) -> list[PipelineProgressMessage]:diff --git a/freemocap/core/tasks/mocap/mocap_helpers/skeleton_from_mediapipe_observations.py b/freemocap/core/tasks/mocap/mocap_helpers/skeleton_from_mediapipe_observations.pyindex 13e7a438..41bcba99 100644--- a/freemocap/core/tasks/mocap/mocap_helpers/skeleton_from_mediapipe_observations.py+++ b/freemocap/core/tasks/mocap/mocap_helpers/skeleton_from_mediapipe_observations.py@@ -117,6 +117,10 @@ def skeleton_from_mediapipe_observation_recorders(tracked_points_numpy_array=filtered_trajectory_3d.triangulated_data,)+ skeleton.add_reprojection_error_numpy(+ reprojection_error_data=filtered_trajectory_3d.reprojection_error,+ )+print("DETECTOR: ", detector)print("MODEL INFO: ", model_info)print(f"SKELETON: {skeleton}")diff --git a/freemocap/core/tracking/tracker_factory.py b/freemocap/core/tracking/tracker_factory.pyindex 6896c0b6..ccad1322 100644--- a/freemocap/core/tracking/tracker_factory.py+++ b/freemocap/core/tracking/tracker_factory.py@@ -205,6 +205,52 @@ def _mediapipe_hand_child_stage()+def _mediapipe_face_child_stage(+ *,+ num_faces: int,+ detection_confidence: float,+ presence_confidence: float,+ tracking_confidence: float,+) -> DetectionStageConfig:+ """Build a head-cropped face child stage.++ Crops around the head using the parent body stage's own nose/ear keypoints+ (pure keypoint arithmetic, no inference), then runs MediaPipe's face+ landmarker on that crop.++ The crop matters as much here as it does for hands: on a full-body frame the+ head occupies a small fraction of the image and MediaPipe's face detector+ frequently returns nothing at all, which silently yields an all-NaN face+ stage (136 empty face_* rows in the output). Ear-to-ear span sizes the box+ and sits the nose at its centre, so the whole head is inside the crop.+ """+ from skellytracker.core.detectors.keypoint_detectors.mediapipe.face.mediapipe_face_detector import (+ MediapipeFaceDetectorConfig,+ )++ return DetectionStageConfig(+ name="face",+ object_detector=KeypointBoundingBoxDetectorConfig(+ center_keypoint_names=("nose",),+ scale_keypoint_pairs=(("left_ear", "right_ear"),),+ # The head is taller than it is wide (face oval height ~= 1.4x+ # ear-to-ear), so scale generously off the ear span to keep the+ # forehead and chin inside the box.+ scale_factor=3.0,+ min_box_size_px=120.0,+ ),+ keypoint_detectors=[+ MediapipeFaceDetectorConfig(+ num_faces=num_faces,+ min_face_detection_confidence=detection_confidence,+ min_face_presence_confidence=presence_confidence,+ min_face_tracking_confidence=tracking_confidence,+ )+ ],+ bbox_smoothing=BBoxSmoothingConfig(alpha=0.4),+ )++def build_mediapipe_tracker_config(*,model_complexity=None,@@ -215,20 +261,18 @@ def build_mediapipe_tracker_config() -> TrackerConfig:"""Build a MediaPipe body+hands+face TrackerConfig.- Pose is the parent "body" stage; left_hand/right_hand are wrist-cropped- child stages (see _mediapipe_hand_child_stage) instead of full-frame- sibling detectors, since hands occupy a tiny fraction of a full-body frame- and MediaPipe's palm detector struggles to find them at that scale. Face- is also a child stage (full-frame, no crop) purely to preserve the- existing pose/right_hand/left_hand/face point ordering that+ Pose is the parent "body" stage; left_hand/right_hand are wrist-cropped and+ face is head-cropped (see _mediapipe_hand_child_stage /+ _mediapipe_face_child_stage) instead of full-frame sibling detectors: hands+ and the face each occupy a tiny fraction of a full-body frame and+ MediaPipe's palm/face detectors struggle to find them at that scale.+ The child stages are kept as children (rather than sibling detectors) to+ preserve the existing pose/right_hand/left_hand/face point ordering thatmerge_mediapipe_hand_face_children() and tracker_definitions.py expect."""from skellytracker.core.detectors.keypoint_detectors.mediapipe.body.mediapipe_pose_detector import (MediapipePoseDetectorConfig,)- from skellytracker.core.detectors.keypoint_detectors.mediapipe.face.mediapipe_face_detector import (- MediapipeFaceDetectorConfig,- )from skellytracker.core.detectors.keypoint_detectors.mediapipe.mediapipe_model_manager import (MediapipePoseModelComplexity,)@@ -262,16 +306,11 @@ def build_mediapipe_tracker_config(presence_confidence=presence_confidence,tracking_confidence=tracking_confidence,),- DetectionStageConfig(- name="face",- keypoint_detectors=[- MediapipeFaceDetectorConfig(- num_faces=num_faces,- min_face_detection_confidence=detection_confidence,- min_face_presence_confidence=presence_confidence,- min_face_tracking_confidence=tracking_confidence,- )- ],+ _mediapipe_face_child_stage(+ num_faces=num_faces,+ detection_confidence=detection_confidence,+ presence_confidence=presence_confidence,+ tracking_confidence=tracking_confidence,),],keypoint_reset_policy=KeypointResetPolicyConfig(max_consecutive_misses=10),diff --git a/freemocap/system/logging/log_queue_consumer.py b/freemocap/system/logging/log_queue_consumer.pynew file mode 100644index 00000000..05e35ed0--- /dev/null+++ b/freemocap/system/logging/log_queue_consumer.py@@ -0,0 +1,80 @@+from __future__ import annotations++import logging+import os+import queue+import threading+from queue import Empty++from skellylogs import LogRecordModel, get_websocket_log_queue+from skellylogs.handlers.websocket_log_queue_handler import (+ MAX_WEBSOCKET_LOG_QUEUE_SIZE,+)++FRONTEND_LOG_QUEUE: queue.Queue[dict] = queue.Queue(+ maxsize=MAX_WEBSOCKET_LOG_QUEUE_SIZE #using the websocket log queue size as a reference for the frontend log queue size instead of making up a harcoded number+)++_consumer_thread: threading.Thread | None = None+_stop_event = threading.Event()+++def _write_worker_record_to_main_file(log_entry: dict) -> None:+ log_model = LogRecordModel.from_dict(log_entry)+ record = log_model.to_log_record()++ root_logger = logging.getLogger()++ for handler in root_logger.handlers:+ if isinstance(handler, logging.FileHandler):+ handler.handle(record)+++def _consume_log_queue() -> None:+ logs_queue = get_websocket_log_queue()++ while not _stop_event.is_set():+ try:+ log_entry: dict = logs_queue.get(timeout=0.1)++ except Empty:+ continue++ except (EOFError, OSError):+ continue++ if not isinstance(log_entry, dict):+ continue++ # Main-process records have already passed through the main+ # FileHandler. Worker records have not.+ if log_entry.get("process") != os.getpid():+ _write_worker_record_to_main_file(log_entry)++ # All records are forwarded for display in the frontend.+ try:+ FRONTEND_LOG_QUEUE.put_nowait(log_entry)+ except queue.Full:+ pass+++def start_log_queue_consumer() -> None:+ global _consumer_thread++ if _consumer_thread is not None and _consumer_thread.is_alive():+ return++ _stop_event.clear()++ _consumer_thread = threading.Thread(+ target=_consume_log_queue,+ name="LogQueueConsumer",+ daemon=True,+ )+ _consumer_thread.start()+++def stop_log_queue_consumer() -> None:+ _stop_event.set()+ if _consumer_thread is not None:+ _consumer_thread.join(timeout=1.0)\ No newline at end of filediff --git a/pyproject.toml b/pyproject.tomlindex 05a7a194..bbfb7acf 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -41,7 +41,7 @@ cpu = ["skellytracker[all-cpu]"][tool.uv.sources]skellycam = { git = "https://github.com/freemocap/skellycam", branch = "main" }-skellytracker = { git = "https://github.com/freemocap/skellytracker", branch = "main"}+skellytracker = { git = "https://github.com/freemocap/skellytracker", branch = "main" }skellyforge = { git = "https://github.com/freemocap/skellyforge", branch = "main" }skelly_synchronize = { git = "https://github.com/freemocap/skellysync", branch = "philip/rewrite" }freemocap_blender_addon = { git = "https://github.com/freemocap/freemocap_blender_addon", branch = "main" }diff --git a/uv.lock b/uv.lockindex 6feeb0cd..b689021a 100644--- a/uv.lock+++ b/uv.lock@@ -447,6 +447,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/cb/03/10388a42375ee7e4ac9b94eb2c5c569c8b5795e377e701c9ac3ad63de890/fastapi-0.141.1-py3-none-any.whl", hash = "sha256:bfb91aa2d334c61cb35ba9a116fc123b3d3df31640b801cf57a7a78ec3f603b3", size = 131954, upload-time = "2026-07-29T17:18:04.364Z" },]+[[package]]+name = "filelock"+version = "4.0.8"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/cc/19/d4f21fc4b7ad098dd3c774ccb2a2929178b15d6e1a3ba7d0929817c0b30c/filelock-4.0.8.tar.gz", hash = "sha256:733d9b6b153fc63672f86104324186818b6bbe9dd7db84e9bb9887b6a04a2775", size = 249830, upload-time = "2026-10-01T06:15:21.755Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/89/6b/b45e5ad90c6ac8805b72277d75ef651bca11d3665194de7c0162bd8324eb/filelock-4.0.8-py3-none-any.whl", hash = "sha256:325ff22f358c18443b1fcdfa0a7aa3faec4b500c2807c554719da4567b533d31", size = 109665, upload-time = "2026-10-01T06:15:19.736Z" },+]+[[package]]name = "flatbuffers"version = "25.12.19"@@ -491,7 +500,7 @@ wheels = [[[package]]name = "freemocap"-version = "2.0.0a24"+version = "2.0.0a25"source = { editable = "." }dependencies = [{ name = "beartype" },@@ -2165,7 +2174,7 @@ dependencies = [[[package]]name = "skellycam"version = "2.0.0a6"-source = { git = "https://github.com/freemocap/skellycam?branch=main#26509b06ba44980b3ccaae7c9c5f4efab4e88c90" }+source = { git = "https://github.com/freemocap/skellycam?branch=main#06771043becd50db1570ed2a67dd0536edbf47f1" }dependencies = [{ name = "av" },{ name = "beartype" },@@ -2195,7 +2204,7 @@ dependencies = [[[package]]name = "skellyforge"version = "2024.12.1009"-source = { git = "https://github.com/freemocap/skellyforge?branch=main#ddf24f3aaa4388e5883afada217137223546c24e" }+source = { git = "https://github.com/freemocap/skellyforge?branch=main#b96272b1ef06546c1a55d404a5f4a92f1fad1b0f" }dependencies = [{ name = "numpy" },{ name = "pandas" },@@ -2209,7 +2218,10 @@ dependencies = [[[package]]name = "skellylogs"version = "0.1.0"-source = { git = "https://github.com/freemocap/skellylogs#9114990350d7fb36747526286671c17abd7e523e" }+source = { git = "https://github.com/freemocap/skellylogs#33a3611932ce3d43e54cefb2051171d565137445" }+dependencies = [+ { name = "tqdm" },+][[package]]name = "skellypings"@@ -2223,9 +2235,10 @@ dependencies = [[[package]]name = "skellytracker"version = "2024.9.1019"-source = { git = "https://github.com/freemocap/skellytracker?branch=main#63100055867b161d32fb1535ed73f73e1ddd187d" }+source = { git = "https://github.com/freemocap/skellytracker?branch=main#6f78af48b7a3c1809d110120a7cbd1d7f6120392" }dependencies = [{ name = "beartype" },+ { name = "filelock" },{ name = "numpy" },{ name = "numpydantic" },{ name = "opencv-contrib-python" },