Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: comprehensive health dashboard with config-driven metric cards
Adam Eivy5bfe7324c0a4
diff --git a/.changelog/v1.15.x.md b/.changelog/v1.15.x.mdnew file mode 100644index 0000000000..452872b42c--- /dev/null+++ b/.changelog/v1.15.x.md@@ -0,0 +1,21 @@+# Release v1.15.x - Changelog++Released: YYYY-MM-DD++## Overview++Comprehensive health dashboard with config-driven metric cards, collapsible categories, and lazy loading.++## Features++- **Config-driven health dashboard** — replaced hardcoded StepsCard/HeartRateCard/HrvCard with a generic MetricCard component and a registry of 50+ metrics across 8 categories (Core Vitals, Activity, Sleep, Body, Walking, Cycling, Running, Audio)+- **Collapsible category sections** — each metric category is a collapsible section with lazy data loading on expand; Core Vitals expanded by default+- **Available metrics discovery** — new server endpoint `GET /health/metrics/available` samples day files across the full history to discover which metrics have data, correctly finding sparse metrics like Withings body composition+- **Deep-linkable health dashboard** — `useSearchParams` for `range` and `section` URL params (e.g. `?range=30d§ion=walking`)+- **Alcohol/HRV correlation moved to Alcohol tab** — AlcoholHrvCorrelation chart now lives alongside the consumption chart with synced view range++## Improvements++- **Smart aggregation for sum metrics** — refactored `getDailyAggregates` to use a `SUM_METRICS` set instead of hardcoded `metricName === 'step_count'`; covers active energy, basal energy, flights climbed, exercise time, stand time, walking/cycling distance, and time in daylight+- **Correct units from Apple Health** — metric display uses actual stored units (lb, mi, mi/hr, in, etc.) instead of assumed metric units+- **PM2 memory limits** — increased max memory restart to 2G for server and CoS processesdiff --git a/client/src/components/meatspace/AlcoholChart.jsx b/client/src/components/meatspace/AlcoholChart.jsxindex 7da9a4fa21..0c6b87a8aa 100644--- a/client/src/components/meatspace/AlcoholChart.jsx+++ b/client/src/components/meatspace/AlcoholChart.jsx@@ -13,7 +13,7 @@ const VIEWS = [const GRAMS_PER_STD_DRINK = 14;-export default function AlcoholChart({ sex = 'male', onRefreshKey }) {+export default function AlcoholChart({ sex = 'male', onRefreshKey, onViewChange }) {const [data, setData] = useState([]);const [loading, setLoading] = useState(true);const [view, setView] = useState('30d');@@ -105,7 +105,7 @@ export default function AlcoholChart({ sex = 'male', onRefreshKey }) {{VIEWS.map(v => (<buttonkey={v.id}- onClick={() => setView(v.id)}+ onClick={() => { setView(v.id); onViewChange?.(v.id); }}className={`px-2 py-1 text-xs rounded transition-colors ${view === v.id? 'bg-port-accent/10 text-port-accent'diff --git a/client/src/components/meatspace/HealthCategorySection.jsx b/client/src/components/meatspace/HealthCategorySection.jsxnew file mode 100644index 0000000000..54e1afb303--- /dev/null+++ b/client/src/components/meatspace/HealthCategorySection.jsx@@ -0,0 +1,69 @@+import { useState, useEffect, useRef } from 'react';+import { ChevronDown, ChevronRight } from 'lucide-react';+import * as api from '../../services/api';+import MetricCard from './MetricCard';+import SleepCard from './SleepCard';++export default function HealthCategorySection({ category, from, to, expanded, onToggle, availableMetrics }) {+ const [metricData, setMetricData] = useState({});+ const [loading, setLoading] = useState(false);+ const lastRangeRef = useRef(null);++ // Filter to only metrics that have data+ const activeMetrics = category.metrics.filter(m => availableMetrics.has(m.key));+ if (activeMetrics.length === 0) return null;++ const rangeKey = `${from}|${to}`;++ useEffect(() => {+ if (!expanded || !from || !to) return;+ if (lastRangeRef.current === rangeKey && Object.keys(metricData).length > 0) return;++ let cancelled = false;+ setLoading(true);++ Promise.all(+ activeMetrics.map(m =>+ api.getAppleHealthMetrics(m.key, from, to)+ .then(data => ({ key: m.key, data: Array.isArray(data) ? data : [] }))+ .catch(() => ({ key: m.key, data: [] }))+ )+ ).then(results => {+ if (cancelled) return;+ const dataMap = {};+ for (const r of results) dataMap[r.key] = r.data;+ setMetricData(dataMap);+ lastRangeRef.current = rangeKey;+ setLoading(false);+ });++ return () => { cancelled = true; };+ }, [expanded, rangeKey]);++ return (+ <div className="border border-port-border rounded-xl overflow-hidden">+ <button+ onClick={onToggle}+ className="w-full flex items-center justify-between px-6 py-4 bg-port-card hover:bg-port-border/30 transition-colors"+ >+ <div className="flex items-center gap-3">+ {expanded ? <ChevronDown size={16} className="text-gray-400" /> : <ChevronRight size={16} className="text-gray-400" />}+ <h2 className="text-sm font-semibold text-white uppercase tracking-wider">{category.label}</h2>+ <span className="text-xs text-gray-500">{activeMetrics.length} metrics</span>+ </div>+ </button>++ {expanded && (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 p-6 bg-port-bg">+ {activeMetrics.map(metric =>+ metric.key === 'sleep_analysis' ? (+ <SleepCard key={metric.key} data={metricData[metric.key] ?? []} loading={loading} />+ ) : (+ <MetricCard key={metric.key} data={metricData[metric.key] ?? []} loading={loading} config={metric} />+ )+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/HeartRateCard.jsx b/client/src/components/meatspace/HeartRateCard.jsxdeleted file mode 100644index df497d6dfa..0000000000--- a/client/src/components/meatspace/HeartRateCard.jsx+++ /dev/null@@ -1,51 +0,0 @@-import {- LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer-} from 'recharts';--const CustomTooltip = ({ active, payload, label }) => {- if (!active || !payload?.length) return null;- return (- <div style={{ background: '#1a1a1a', border: '1px solid #2a2a2a', color: '#fff', padding: '8px', borderRadius: '6px', fontSize: '12px' }}>- <p style={{ color: '#9ca3af', marginBottom: 2 }}>{label}</p>- <p style={{ color: '#ef4444', fontWeight: 600 }}>{Math.round(payload[0].value)} bpm</p>- </div>- );-};--export default function HeartRateCard({ data = [], loading = false }) {- const avg = data.length > 0- ? Math.round(data.reduce((sum, d) => sum + (d.value ?? 0), 0) / data.length)- : null;-- const chartData = data.map(d => ({- date: d.date?.slice(5) ?? d.date,- value: d.value ?? 0- }));-- return (- <div className="bg-port-card border border-port-border rounded-xl p-6">- <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">Heart Rate</h3>- {loading ? (- <div className="flex items-center justify-center h-40 text-gray-600 text-sm">Loading...</div>- ) : avg == null ? (- <div className="flex items-center justify-center h-40 text-gray-600 text-sm">No heart rate data available</div>- ) : (- <>- <div className="mb-4">- <span className="text-3xl font-bold text-white font-mono">{avg}</span>- <span className="text-sm text-gray-500 ml-2">bpm</span>- </div>- <ResponsiveContainer width="100%" height={150}>- <LineChart data={chartData} margin={{ top: 2, right: 8, bottom: 2, left: 0 }}>- <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />- <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} interval="preserveStartEnd" />- <YAxis tick={{ fill: '#9ca3af', fontSize: 11 }} width={40} domain={['auto', 'auto']} />- <Tooltip content={<CustomTooltip />} />- <Line type="monotone" dataKey="value" stroke="#ef4444" strokeWidth={2} dot={false} />- </LineChart>- </ResponsiveContainer>- </>- )}- </div>- );-}diff --git a/client/src/components/meatspace/HrvCard.jsx b/client/src/components/meatspace/HrvCard.jsxdeleted file mode 100644index 212fdf3c74..0000000000--- a/client/src/components/meatspace/HrvCard.jsx+++ /dev/null@@ -1,51 +0,0 @@-import {- LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer-} from 'recharts';--const CustomTooltip = ({ active, payload, label }) => {- if (!active || !payload?.length) return null;- return (- <div style={{ background: '#1a1a1a', border: '1px solid #2a2a2a', color: '#fff', padding: '8px', borderRadius: '6px', fontSize: '12px' }}>- <p style={{ color: '#9ca3af', marginBottom: 2 }}>{label}</p>- <p style={{ color: '#22c55e', fontWeight: 600 }}>{Math.round(payload[0].value)} ms</p>- </div>- );-};--export default function HrvCard({ data = [], loading = false }) {- const avg = data.length > 0- ? Math.round(data.reduce((sum, d) => sum + (d.value ?? 0), 0) / data.length)- : null;-- const chartData = data.map(d => ({- date: d.date?.slice(5) ?? d.date,- value: d.value ?? 0- }));-- return (- <div className="bg-port-card border border-port-border rounded-xl p-6">- <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">HRV</h3>- {loading ? (- <div className="flex items-center justify-center h-40 text-gray-600 text-sm">Loading...</div>- ) : avg == null ? (- <div className="flex items-center justify-center h-40 text-gray-600 text-sm">No HRV data available</div>- ) : (- <>- <div className="mb-4">- <span className="text-3xl font-bold text-white font-mono">{avg}</span>- <span className="text-sm text-gray-500 ml-2">ms</span>- </div>- <ResponsiveContainer width="100%" height={150}>- <LineChart data={chartData} margin={{ top: 2, right: 8, bottom: 2, left: 0 }}>- <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />- <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} interval="preserveStartEnd" />- <YAxis tick={{ fill: '#9ca3af', fontSize: 11 }} width={40} domain={['auto', 'auto']} />- <Tooltip content={<CustomTooltip />} />- <Line type="monotone" dataKey="value" stroke="#22c55e" strokeWidth={2} dot={false} />- </LineChart>- </ResponsiveContainer>- </>- )}- </div>- );-}diff --git a/client/src/components/meatspace/MetricCard.jsx b/client/src/components/meatspace/MetricCard.jsxnew file mode 100644index 0000000000..7da60dfb90--- /dev/null+++ b/client/src/components/meatspace/MetricCard.jsx@@ -0,0 +1,63 @@+import {+ LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer+} from 'recharts';++export default function MetricCard({ data = [], loading = false, config }) {+ const { label, unit, color, aggregation, formatValue } = config;+ const isSumMetric = aggregation === 'sum';++ const summary = data.length > 0+ ? (isSumMetric+ ? Math.round(data.reduce((sum, d) => sum + (d.value ?? 0), 0) / data.length)+ : Math.round(data.reduce((sum, d) => sum + (d.value ?? 0), 0) / data.length * 100) / 100)+ : null;++ const displayValue = summary != null+ ? (formatValue ? formatValue(summary) : (Number.isInteger(summary) ? summary.toLocaleString() : summary))+ : null;++ const chartData = data.map(d => ({+ date: d.date?.slice(5) ?? d.date,+ value: d.value ?? 0+ }));++ const summaryLabel = isSumMetric ? `avg daily ${unit}` : unit;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-6">+ <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">{label}</h3>+ {loading ? (+ <div className="flex items-center justify-center h-40 text-gray-600 text-sm">Loading...</div>+ ) : displayValue == null ? (+ <div className="flex items-center justify-center h-40 text-gray-600 text-sm">No {label.toLowerCase()} data available</div>+ ) : (+ <>+ <div className="mb-4">+ <span className="text-3xl font-bold text-white font-mono">{displayValue}</span>+ <span className="text-sm text-gray-500 ml-2">{summaryLabel}</span>+ </div>+ <ResponsiveContainer width="100%" height={150}>+ <LineChart data={chartData} margin={{ top: 2, right: 8, bottom: 2, left: 0 }}>+ <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />+ <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} interval="preserveStartEnd" />+ <YAxis tick={{ fill: '#9ca3af', fontSize: 11 }} width={55} domain={['auto', 'auto']}+ tickFormatter={v => typeof v === 'number' && v >= 1000 ? v.toLocaleString() : v} />+ <Tooltip content={({ active, payload, label: tipLabel }) => {+ if (!active || !payload?.length) return null;+ const val = payload[0].value;+ const formatted = formatValue ? formatValue(val) : (typeof val === 'number' && val >= 1000 ? val.toLocaleString() : Math.round(val * 100) / 100);+ return (+ <div style={{ background: '#1a1a1a', border: '1px solid #2a2a2a', color: '#fff', padding: '8px', borderRadius: '6px', fontSize: '12px' }}>+ <p style={{ color: '#9ca3af', marginBottom: 2 }}>{tipLabel}</p>+ <p style={{ color, fontWeight: 600 }}>{formatted} {unit}</p>+ </div>+ );+ }} />+ <Line type="monotone" dataKey="value" stroke={color} strokeWidth={2} dot={false} />+ </LineChart>+ </ResponsiveContainer>+ </>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/StepsCard.jsx b/client/src/components/meatspace/StepsCard.jsxdeleted file mode 100644index 5726238edd..0000000000--- a/client/src/components/meatspace/StepsCard.jsx+++ /dev/null@@ -1,51 +0,0 @@-import {- LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer-} from 'recharts';--const CustomTooltip = ({ active, payload, label }) => {- if (!active || !payload?.length) return null;- return (- <div style={{ background: '#1a1a1a', border: '1px solid #2a2a2a', color: '#fff', padding: '8px', borderRadius: '6px', fontSize: '12px' }}>- <p style={{ color: '#9ca3af', marginBottom: 2 }}>{label}</p>- <p style={{ color: '#3b82f6', fontWeight: 600 }}>{Number(payload[0].value).toLocaleString()} steps</p>- </div>- );-};--export default function StepsCard({ data = [], loading = false }) {- const avg = data.length > 0- ? Math.round(data.reduce((sum, d) => sum + (d.value ?? 0), 0) / data.length)- : null;-- const chartData = data.map(d => ({- date: d.date?.slice(5) ?? d.date,- value: d.value ?? 0- }));-- return (- <div className="bg-port-card border border-port-border rounded-xl p-6">- <h3 className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-3">Steps</h3>- {loading ? (- <div className="flex items-center justify-center h-40 text-gray-600 text-sm">Loading...</div>- ) : avg == null ? (- <div className="flex items-center justify-center h-40 text-gray-600 text-sm">No step data available</div>- ) : (- <>- <div className="mb-4">- <span className="text-3xl font-bold text-white font-mono">{avg.toLocaleString()}</span>- <span className="text-sm text-gray-500 ml-2">avg daily steps</span>- </div>- <ResponsiveContainer width="100%" height={150}>- <LineChart data={chartData} margin={{ top: 2, right: 8, bottom: 2, left: 0 }}>- <CartesianGrid strokeDasharray="3 3" stroke="#2a2a2a" />- <XAxis dataKey="date" tick={{ fill: '#9ca3af', fontSize: 11 }} interval="preserveStartEnd" />- <YAxis tick={{ fill: '#9ca3af', fontSize: 11 }} width={55} tickFormatter={v => v.toLocaleString()} />- <Tooltip content={<CustomTooltip />} />- <Line type="monotone" dataKey="value" stroke="#3b82f6" strokeWidth={2} dot={false} />- </LineChart>- </ResponsiveContainer>- </>- )}- </div>- );-}diff --git a/client/src/components/meatspace/healthMetrics.js b/client/src/components/meatspace/healthMetrics.jsnew file mode 100644index 0000000000..a8aea0f13f--- /dev/null+++ b/client/src/components/meatspace/healthMetrics.js@@ -0,0 +1,107 @@+/**+ * Health Metrics Registry+ *+ * Single source of truth for all Apple Health metric display configuration.+ * Units match what Apple Health actually stores (imperial/native units).+ * Each category contains metrics with their label, unit, color, and aggregation type.+ */++export const SUM_METRICS = new Set([+ 'step_count', 'active_energy', 'basal_energy_burned', 'flights_climbed',+ 'apple_exercise_time', 'apple_stand_time', 'walking_running_distance',+ 'distance_cycling', 'time_in_daylight'+]);++export const METRIC_CATEGORIES = [+ {+ id: 'core-vitals',+ label: 'Core Vitals',+ defaultExpanded: true,+ metrics: [+ { key: 'heart_rate', label: 'Heart Rate', unit: 'bpm', color: '#ef4444', aggregation: 'avg' },+ { key: 'resting_heart_rate', label: 'Resting Heart Rate', unit: 'bpm', color: '#f87171', aggregation: 'avg' },+ { key: 'heart_rate_variability_sdnn', label: 'HRV', unit: 'ms', color: '#22c55e', aggregation: 'avg' },+ { key: 'blood_oxygen_saturation', label: 'Blood Oxygen', unit: '%', color: '#3b82f6', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'respiratory_rate', label: 'Respiratory Rate', unit: 'breaths/min', color: '#06b6d4', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'vo2_max', label: 'VO2 Max', unit: 'mL/min/kg', color: '#8b5cf6', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ ]+ },+ {+ id: 'activity',+ label: 'Activity',+ metrics: [+ { key: 'step_count', label: 'Steps', unit: 'steps', color: '#3b82f6', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'active_energy', label: 'Active Energy', unit: 'Cal', color: '#f59e0b', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'basal_energy_burned', label: 'Basal Energy', unit: 'Cal', color: '#d97706', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'walking_running_distance', label: 'Walk/Run Distance', unit: 'mi', color: '#10b981', aggregation: 'sum', formatValue: v => v.toFixed(2) },+ { key: 'apple_exercise_time', label: 'Exercise Time', unit: 'min', color: '#22c55e', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'flights_climbed', label: 'Flights Climbed', unit: 'flights', color: '#6366f1', aggregation: 'sum' },+ { key: 'physical_effort', label: 'Physical Effort', unit: 'kJ/hr/kg', color: '#ec4899', aggregation: 'avg' },+ { key: 'time_in_daylight', label: 'Time in Daylight', unit: 'min', color: '#fbbf24', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'apple_stand_time', label: 'Stand Time', unit: 'min', color: '#14b8a6', aggregation: 'sum', formatValue: v => Math.round(v).toLocaleString() },+ ]+ },+ {+ id: 'sleep',+ label: 'Sleep',+ metrics: [+ { key: 'sleep_analysis', label: 'Sleep', unit: 'hrs', color: '#8b5cf6', aggregation: 'special' },+ { key: 'breathing_disturbances', label: 'Breathing Disturbances', unit: 'events/hr', color: '#f43f5e', aggregation: 'avg' },+ ]+ },+ {+ id: 'body',+ label: 'Body',+ metrics: [+ { key: 'body_mass', label: 'Weight', unit: 'lb', color: '#6366f1', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'body_mass_index', label: 'BMI', unit: '', color: '#8b5cf6', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'body_fat_percentage', label: 'Body Fat', unit: '%', color: '#f59e0b', aggregation: 'avg', formatValue: v => (v * 100).toFixed(1) },+ { key: 'lean_body_mass', label: 'Lean Body Mass', unit: 'lb', color: '#10b981', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ ]+ },+ {+ id: 'walking',+ label: 'Walking',+ metrics: [+ { key: 'walking_speed', label: 'Walking Speed', unit: 'mi/hr', color: '#3b82f6', aggregation: 'avg', formatValue: v => v.toFixed(2) },+ { key: 'walking_step_length', label: 'Step Length', unit: 'in', color: '#06b6d4', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'walking_double_support_percentage', label: 'Double Support', unit: '%', color: '#f59e0b', aggregation: 'avg', formatValue: v => (v * 100).toFixed(1) },+ { key: 'walking_asymmetry_percentage', label: 'Asymmetry', unit: '%', color: '#ef4444', aggregation: 'avg', formatValue: v => (v * 100).toFixed(1) },+ { key: 'walking_steadiness', label: 'Steadiness', unit: '%', color: '#22c55e', aggregation: 'avg', formatValue: v => (v * 100).toFixed(0) },+ { key: 'stair_speed_up', label: 'Stair Speed (Up)', unit: 'ft/s', color: '#8b5cf6', aggregation: 'avg', formatValue: v => v.toFixed(2) },+ { key: 'stair_speed_down', label: 'Stair Speed (Down)', unit: 'ft/s', color: '#6366f1', aggregation: 'avg', formatValue: v => v.toFixed(2) },+ { key: 'six_minute_walk_test', label: '6-Min Walk Test', unit: 'm', color: '#10b981', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'walking_heart_rate_average', label: 'Walking Heart Rate', unit: 'bpm', color: '#ef4444', aggregation: 'avg' },+ ]+ },+ {+ id: 'cycling',+ label: 'Cycling',+ metrics: [+ { key: 'distance_cycling', label: 'Cycling Distance', unit: 'mi', color: '#3b82f6', aggregation: 'sum', formatValue: v => v.toFixed(2) },+ { key: 'cycling_speed', label: 'Cycling Speed', unit: 'mi/hr', color: '#06b6d4', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'cycling_cadence', label: 'Cadence', unit: 'rpm', color: '#f59e0b', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'cycling_power', label: 'Power', unit: 'W', color: '#ef4444', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'cycling_ftp', label: 'FTP', unit: 'W', color: '#8b5cf6', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },+ ]+ },+ {+ id: 'running',+ label: 'Running',+ metrics: [+ { key: 'running_speed', label: 'Running Speed', unit: 'mi/hr', color: '#3b82f6', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'running_power', label: 'Running Power', unit: 'W', color: '#ef4444', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },+ { key: 'running_stride_length', label: 'Stride Length', unit: 'm', color: '#06b6d4', aggregation: 'avg', formatValue: v => v.toFixed(2) },+ { key: 'running_vertical_oscillation', label: 'Vertical Oscillation', unit: 'cm', color: '#f59e0b', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'running_ground_contact_time', label: 'Ground Contact', unit: 'ms', color: '#8b5cf6', aggregation: 'avg', formatValue: v => Math.round(v).toLocaleString() },+ ]+ },+ {+ id: 'audio',+ label: 'Audio',+ metrics: [+ { key: 'environmental_audio_exposure', label: 'Environmental Audio', unit: 'dB', color: '#f59e0b', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ { key: 'headphone_audio_exposure', label: 'Headphone Audio', unit: 'dB', color: '#ef4444', aggregation: 'avg', formatValue: v => v.toFixed(1) },+ ]+ }+];diff --git a/client/src/components/meatspace/tabs/AlcoholTab.jsx b/client/src/components/meatspace/tabs/AlcoholTab.jsxindex 5a24a64505..e867f5b223 100644--- a/client/src/components/meatspace/tabs/AlcoholTab.jsx+++ b/client/src/components/meatspace/tabs/AlcoholTab.jsx@@ -3,6 +3,7 @@ import { Beer, Plus, Trash2, AlertTriangle, TrendingDown, TrendingUp, Pencil, Chimport * as api from '../../../services/api';import BrailleSpinner from '../../BrailleSpinner';import AlcoholChart from '../AlcoholChart';+import AlcoholHrvCorrelation from '../AlcoholHrvCorrelation';import StandardDrinkCalculator from '../StandardDrinkCalculator';const COMMON_DRINKS = [@@ -56,6 +57,10 @@ export default function AlcoholTab() {const [editingKey, setEditingKey] = useState(null); // "date:index"const [editForm, setEditForm] = useState({ name: '', oz: '', abv: '', count: 1 });+ // Correlation chart state+ const [chartView, setChartView] = useState('30d');+ const [correlationData, setCorrelationData] = useState(null);+const fetchData = useCallback(async () => {const [summaryData, entries] = await Promise.all([api.getAlcoholSummary().catch(() => null),@@ -70,6 +75,17 @@ export default function AlcoholTab() {fetchData();}, [fetchData, refreshKey]);+ // Fetch correlation data for HRV chart+ const chartDays = { '7d': 7, '30d': 30, '90d': 90 }[chartView] || 30;+ const correlationFrom = (() => { const d = new Date(); d.setDate(d.getDate() - chartDays); return d.toISOString().split('T')[0]; })();+ const correlationTo = new Date().toISOString().split('T')[0];++ useEffect(() => {+ api.getAppleHealthCorrelation(correlationFrom, correlationTo)+ .then(setCorrelationData)+ .catch(() => setCorrelationData(null));+ }, [correlationFrom, correlationTo]);+const handleQuickAdd = async (drink) => {setLogging(true);await api.logAlcoholDrink({@@ -208,8 +224,11 @@ export default function AlcoholTab() {</div>)}- {/* Consumption Chart */}- <AlcoholChart sex={summary?.sex} onRefreshKey={refreshKey} />+ {/* Consumption + HRV Correlation Charts */}+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">+ <AlcoholChart sex={summary?.sex} onRefreshKey={refreshKey} onViewChange={setChartView} />+ {correlationData && <AlcoholHrvCorrelation data={correlationData} range={chartView} />}+ </div>{/* Log a Drink */}<div className="bg-port-card border border-port-border rounded-xl p-6">diff --git a/client/src/components/meatspace/tabs/HealthTab.jsx b/client/src/components/meatspace/tabs/HealthTab.jsxindex 7dafe0decc..114f36db6e 100644--- a/client/src/components/meatspace/tabs/HealthTab.jsx+++ b/client/src/components/meatspace/tabs/HealthTab.jsx@@ -1,10 +1,8 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useRef } from 'react';+import { useSearchParams } from 'react-router-dom';import * as api from '../../../services/api';-import StepsCard from '../StepsCard';-import HeartRateCard from '../HeartRateCard';-import SleepCard from '../SleepCard';-import HrvCard from '../HrvCard';-import AlcoholHrvCorrelation from '../AlcoholHrvCorrelation';+import { METRIC_CATEGORIES } from '../healthMetrics';+import HealthCategorySection from '../HealthCategorySection';import ActivityBloodCorrelation from '../ActivityBloodCorrelation';const RANGES = [@@ -21,42 +19,76 @@ function getFromDate(days) {}export default function HealthTab() {- const [range, setRange] = useState('7d');- const [stepsData, setStepsData] = useState([]);- const [hrData, setHrData] = useState([]);- const [sleepData, setSleepData] = useState([]);- const [hrvData, setHrvData] = useState([]);+ const [searchParams, setSearchParams] = useSearchParams();+ const range = searchParams.get('range') || '7d';+ const sectionParam = searchParams.get('section');++ const [availableMetrics, setAvailableMetrics] = useState(new Set());+ const [expandedSections, setExpandedSections] = useState(new Set());const [correlationData, setCorrelationData] = useState(null);- const [loading, setLoading] = useState(true);+ const [initialized, setInitialized] = useState(false);+ const sectionRefs = useRef({});- const fetchData = useCallback(async () => {- setLoading(true);- const days = RANGES.find(r => r.id === range)?.days ?? 7;- const from = getFromDate(days);- const to = new Date().toISOString().split('T')[0];+ // Fetch which metrics have data+ useEffect(() => {+ api.getAvailableHealthMetrics()+ .then(metrics => {+ setAvailableMetrics(new Set(metrics.map(m => m.name)));+ // Set initial expanded sections after we know what's available+ const initial = new Set();+ for (const cat of METRIC_CATEGORIES) {+ if (cat.defaultExpanded) initial.add(cat.id);+ }+ if (sectionParam) initial.add(sectionParam);+ setExpandedSections(initial);+ setInitialized(true);+ })+ .catch(() => setInitialized(true));+ }, []);- const [steps, hr, sleep, hrv, correlation] = await Promise.all([- api.getAppleHealthMetrics('step_count', from, to).catch(() => []),- api.getAppleHealthMetrics('heart_rate', from, to).catch(() => []),- api.getAppleHealthMetrics('sleep_analysis', from, to).catch(() => []),- api.getAppleHealthMetrics('heart_rate_variability_sdnn', from, to).catch(() => []),- api.getAppleHealthCorrelation(from, to).catch(() => null)- ]);+ // Scroll to section if specified in URL+ useEffect(() => {+ if (sectionParam && initialized) {+ const el = sectionRefs.current[sectionParam];+ if (el) setTimeout(() => el.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100);+ }+ }, [sectionParam, initialized]);- setStepsData(Array.isArray(steps) ? steps : []);- setHrData(Array.isArray(hr) ? hr : []);- setSleepData(Array.isArray(sleep) ? sleep : []);- setHrvData(Array.isArray(hrv) ? hrv : []);- setCorrelationData(correlation);- setLoading(false);- }, [range]);+ // Fetch correlation data+ const days = RANGES.find(r => r.id === range)?.days ?? 7;+ const from = getFromDate(days);+ const to = new Date().toISOString().split('T')[0];useEffect(() => {- fetchData();- }, [fetchData]);+ api.getAppleHealthCorrelation(from, to)+ .then(setCorrelationData)+ .catch(() => setCorrelationData(null));+ }, [from, to]);++ const setRange = useCallback((newRange) => {+ const params = new URLSearchParams(searchParams);+ params.set('range', newRange);+ setSearchParams(params, { replace: true });+ }, [searchParams, setSearchParams]);++ const toggleSection = useCallback((sectionId) => {+ setExpandedSections(prev => {+ const next = new Set(prev);+ if (next.has(sectionId)) {+ next.delete(sectionId);+ } else {+ next.add(sectionId);+ }+ return next;+ });+ }, []);++ if (!initialized) {+ return <div className="text-gray-600 text-sm py-12 text-center">Loading health data...</div>;+ }return (- <div className="space-y-6">+ <div className="space-y-4">{/* Range selector */}<div className="flex items-center gap-1">{RANGES.map(r => (@@ -74,20 +106,25 @@ export default function HealthTab() {))}</div>- {/* Metric cards — 2-column grid */}- <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">- <StepsCard data={stepsData} loading={loading} />- <HeartRateCard data={hrData} loading={loading} />- <SleepCard data={sleepData} loading={loading} />- <HrvCard data={hrvData} loading={loading} />- </div>+ {/* Category sections */}+ {METRIC_CATEGORIES.map(category => (+ <div key={category.id} ref={el => sectionRefs.current[category.id] = el}>+ <HealthCategorySection+ category={category}+ from={from}+ to={to}+ expanded={expandedSections.has(category.id)}+ onToggle={() => toggleSection(category.id)}+ availableMetrics={availableMetrics}+ />+ </div>+ ))}{/* Correlation charts */}{correlationData && (- <>- <AlcoholHrvCorrelation data={correlationData} range={range} />+ <div className="space-y-6 pt-2"><ActivityBloodCorrelation data={correlationData} range={range} />- </>+ </div>)}</div>);diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 671516eb33..137c3728ba 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -60,6 +60,7 @@ export const getAppleHealthSummary = (metricName, from, to) => {if (to) params.set('to', to);return request(`/health/metrics/${metricName}?${params}`);};+export const getAvailableHealthMetrics = () => request('/health/metrics/available');export const getAppleHealthRange = () => request('/health/range');export const getAppleHealthCorrelation = (from, to) => {const params = new URLSearchParams();diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex 41f9180eb1..ae1d8281eb 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -39,7 +39,7 @@ module.exports = {},watch: ['server'],ignore_watch: ['node_modules', '**/*.test.js'],- max_memory_restart: '500M'+ max_memory_restart: '2G'},{name: 'portos-cos',@@ -61,7 +61,7 @@ module.exports = {max_restarts: 5,min_uptime: '30s',restart_delay: 10000,- max_memory_restart: '1G',+ max_memory_restart: '2G',// Important: This process manages long-running agent processes// Keep kill_timeout high to allow graceful shutdown of agentskill_timeout: 30000diff --git a/package-lock.json b/package-lock.jsonindex cb37a07e13..0703f60a5e 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "portos",- "version": "1.15.0",+ "version": "1.15.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos",- "version": "1.15.0",+ "version": "1.15.1","license": "MIT","dependencies": {"express": "^4.21.2",diff --git a/package.json b/package.jsonindex de246d10a6..91c7f0a4f1 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "1.15.0",+ "version": "1.15.1","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.jsindex 3d574c20f0..8d98afad48 100644--- a/server/routes/appleHealth.js+++ b/server/routes/appleHealth.js@@ -13,7 +13,8 @@ import {getMetricSummary,getDailyAggregates,getAvailableDateRange,- getCorrelationData+ getCorrelationData,+ getAvailableMetrics} from '../services/appleHealthQuery.js';const isZip = (file) =>@@ -54,6 +55,13 @@ router.post('/ingest', asyncHandler(async (req, res) => {res.json(result);}));+// GET /api/health/metrics/available+// Returns list of metrics that have data in recent day files+router.get('/metrics/available', asyncHandler(async (req, res) => {+ const metrics = await getAvailableMetrics();+ res.json(metrics);+}));+// GET /api/health/metrics/:metricName// Returns summary stats for a metric over a date rangerouter.get('/metrics/:metricName', asyncHandler(async (req, res) => {diff --git a/server/services/appleHealthQuery.js b/server/services/appleHealthQuery.jsindex 72265c7ce8..9207639c3e 100644--- a/server/services/appleHealthQuery.js+++ b/server/services/appleHealthQuery.js@@ -16,6 +16,13 @@ const METRIC_ALIASES = {'heart_rate_variability_sdnn': 'heart_rate_variability',};+// Metrics that should be summed per day rather than averaged+const SUM_METRICS = new Set([+ 'step_count', 'active_energy', 'basal_energy_burned', 'flights_climbed',+ 'apple_exercise_time', 'apple_stand_time', 'walking_running_distance',+ 'distance_cycling', 'time_in_daylight'+]);+// === Directory Listing ===/**@@ -136,7 +143,22 @@ export async function getDailyAggregates(metricName, from, to) {if (points.length === 0) continue;let value;- if (metricName === 'step_count') {+ if (metricName === 'sleep_analysis') {+ // Sum all aggregated sleep entries (batch flushing may produce multiple per day)+ const sleepPoints = points.filter(p => p.totalSleep !== undefined);+ if (sleepPoints.length > 0) {+ const deep = sleepPoints.reduce((s, p) => s + (p.deep ?? 0), 0);+ const rem = sleepPoints.reduce((s, p) => s + (p.rem ?? 0), 0);+ const core = sleepPoints.reduce((s, p) => s + (p.core ?? 0), 0);+ const awake = sleepPoints.reduce((s, p) => s + (p.awake ?? 0), 0);+ results.push({+ date: dateStr,+ value: Math.round((deep + rem + core) * 100) / 100,+ deep, rem, core, awake+ });+ }+ continue;+ } else if (SUM_METRICS.has(metricName)) {// Sum qty per dayvalue = points.reduce((sum, p) => sum + (p.qty ?? 0), 0);} else if (metricName === 'heart_rate') {@@ -150,28 +172,8 @@ export async function getDailyAggregates(metricName, from, to) {} else {value = null;}- } else if (metricName === 'heart_rate_variability_sdnn') {- // Average qty per day- const qtyPoints = points.filter(p => p.qty !== undefined);- value = qtyPoints.length > 0- ? qtyPoints.reduce((sum, p) => sum + p.qty, 0) / qtyPoints.length- : null;- } else if (metricName === 'sleep_analysis') {- // Return full sleep summary with stage breakdown from most recent aggregated point- const sleepPoint = [...points].reverse().find(p => p.totalSleep !== undefined);- if (sleepPoint) {- results.push({- date: dateStr,- value: Math.round((sleepPoint.totalSleep ?? 0) * 100) / 100,- deep: sleepPoint.deep ?? 0,- rem: sleepPoint.rem ?? 0,- core: sleepPoint.core ?? 0,- awake: sleepPoint.awake ?? 0- });- }- continue;} else {- // Default: average qty+ // Default: average qty (works for HRV, SpO2, walking metrics, etc.)const qtyPoints = points.filter(p => p.qty !== undefined);value = qtyPoints.length > 0? qtyPoints.reduce((sum, p) => sum + p.qty, 0) / qtyPoints.length@@ -186,6 +188,48 @@ export async function getDailyAggregates(metricName, from, to) {return results;}+// === Available Metrics Discovery ===++/**+ * Scan day files to discover which metrics have data.+ * Samples every 30th file plus the last 30 to catch both sparse metrics+ * (e.g. Withings body weight every few weeks) and recent daily metrics.+ *+ * @returns {Promise<Array<{name: string, dayCount: number}>>}+ */+export async function getAvailableMetrics() {+ const dates = await listDayFiles();+ // Sample evenly across full history + dense recent window+ const sample = new Set();+ for (let i = 0; i < dates.length; i += 30) sample.add(dates[i]);+ for (const d of dates.slice(-30)) sample.add(d);++ const metricCounts = new Map();+ for (const dateStr of sample) {+ const dayData = await readDayFile(dateStr);+ const metrics = dayData.metrics ?? {};+ for (const name of Object.keys(metrics)) {+ if (metrics[name]?.length > 0) {+ metricCounts.set(name, (metricCounts.get(name) ?? 0) + 1);+ }+ }+ }++ // Also check aliases (e.g. heart_rate_variability → heart_rate_variability_sdnn)+ const reverseAliases = Object.fromEntries(+ Object.entries(METRIC_ALIASES).map(([alias, original]) => [original, alias])+ );+ for (const [original, alias] of Object.entries(reverseAliases)) {+ if (metricCounts.has(original) && !metricCounts.has(alias)) {+ metricCounts.set(alias, metricCounts.get(original));+ }+ }++ return Array.from(metricCounts.entries())+ .map(([name, dayCount]) => ({ name, dayCount }))+ .sort((a, b) => a.name.localeCompare(b.name));+}+// === Correlation Data ===/**diff --git a/server/services/appleHealthXml.js b/server/services/appleHealthXml.jsindex db17834ef3..a7b1b198fe 100644--- a/server/services/appleHealthXml.js+++ b/server/services/appleHealthXml.js@@ -14,10 +14,72 @@ import { extractDateStr, readDayFile, writeDayFile } from './appleHealthIngest.j// === Mapping Tables ===const XML_TO_METRIC_NAME = {- 'hkquantitytypeidentifierstepcount': 'step_count',+ // Core vitals'hkquantitytypeidentifierheartrate': 'heart_rate','hkquantitytypeidentifierheartratevariancessdnn': 'heart_rate_variability_sdnn',+ 'hkquantitytypeidentifierrestingheartrate': 'resting_heart_rate',+ 'hkquantitytypeidentifierwalkingheartrateaverage': 'walking_heart_rate_average',+ 'hkquantitytypeidentifierheartraterecoveryoneminute': 'heart_rate_recovery',+ 'hkquantitytypeidentifieroxygensaturation': 'blood_oxygen_saturation',+ 'hkquantitytypeidentifierrespiratoryrate': 'respiratory_rate',+ 'hkquantitytypeidentifierbodytemperature': 'body_temperature',+ 'hkquantitytypeidentifiervo2max': 'vo2_max',++ // Activity+ 'hkquantitytypeidentifierstepcount': 'step_count',+ 'hkquantitytypeidentifieractiveenergyburned': 'active_energy',+ 'hkquantitytypeidentifierbasalenergyburned': 'basal_energy_burned',+ 'hkquantitytypeidentifierdistancewalkingrunning': 'walking_running_distance',+ 'hkquantitytypeidentifierflightsclimbed': 'flights_climbed',+ 'hkquantitytypeidentifierappleexercisetime': 'apple_exercise_time',+ 'hkquantitytypeidentifierapplestandtime': 'apple_stand_time',+ 'hkcategorytypeidentifierapplestandhour': 'apple_stand_hour',+ 'hkquantitytypeidentifierphysicaleffort': 'physical_effort',+ 'hkquantitytypeidentifiertimeindaylight': 'time_in_daylight',++ // Walking metrics+ 'hkquantitytypeidentifierwalkingspeed': 'walking_speed',+ 'hkquantitytypeidentifierwalkingsteplength': 'walking_step_length',+ 'hkquantitytypeidentifierwalkingdoublesupportpercentage': 'walking_double_support_percentage',+ 'hkquantitytypeidentifierwalkingasymmetrypercentage': 'walking_asymmetry_percentage',+ 'hkquantitytypeidentifierstairdescentspeed': 'stair_speed_down',+ 'hkquantitytypeidentifierstairascentspeed': 'stair_speed_up',+ 'hkquantitytypeidentifierapplewalkingsteadiness': 'walking_steadiness',+ 'hkquantitytypeidentifiersixminutewalktestdistance': 'six_minute_walk_test',++ // Running+ 'hkquantitytypeidentifierrunningspeed': 'running_speed',+ 'hkquantitytypeidentifierrunningpower': 'running_power',+ 'hkquantitytypeidentifierrunningverticaloscillation': 'running_vertical_oscillation',+ 'hkquantitytypeidentifierrunninggroundcontacttime': 'running_ground_contact_time',+ 'hkquantitytypeidentifierrunningstridelength': 'running_stride_length',++ // Cycling+ 'hkquantitytypeidentifierdistancecycling': 'distance_cycling',+ 'hkquantitytypeidentifiercyclingspeed': 'cycling_speed',+ 'hkquantitytypeidentifiercyclingcadence': 'cycling_cadence',+ 'hkquantitytypeidentifiercyclingpower': 'cycling_power',+ 'hkquantitytypeidentifiercyclingfunctionalthresholdpower': 'cycling_ftp',++ // Body measurements+ 'hkquantitytypeidentifierbodymass': 'body_mass',+ 'hkquantitytypeidentifierbodymassindex': 'body_mass_index',+ 'hkquantitytypeidentifierbodyfatpercentage': 'body_fat_percentage',+ 'hkquantitytypeidentifierleanbodymass': 'lean_body_mass',+ 'hkquantitytypeidentifierheight': 'height',++ // Sleep'hkcategorytypeidentifiersleepanalysis': 'sleep_analysis',+ 'hkquantitytypeidentifierapplesleepingbreathingdisturbances': 'breathing_disturbances',++ // Audio exposure+ 'hkquantitytypeidentifierenvironmentalaudioexposure': 'environmental_audio_exposure',+ 'hkquantitytypeidentifierheadphoneaudioexposure': 'headphone_audio_exposure',+ 'hkquantitytypeidentifierenvironmentalsoundreduction': 'environmental_sound_reduction',++ // Other categories+ 'hkcategorytypeidentifierhandwashingevent': 'handwashing',+ 'hkcategorytypeidentifiermindfulsession': 'mindful_session',};// HKQuantityTypeIdentifierHeartRateVariabilitySDNN mapped by direct lowercase below@@ -137,9 +199,53 @@ function aggregateSleepAnalysis(points) {// === Main Export ===+const FLUSH_INTERVAL = 200000; // Flush to disk every 200K records to stay under memory limits++/**+ * Flush accumulated day buckets to disk: aggregate, merge with existing, write, clear.+ *+ * @param {Object} dayBuckets - { [dateStr]: { [metricName]: [...dataPoints] } }+ * @returns {Promise<Set<string>>} Set of date strings that were flushed+ */+async function flushDayBuckets(dayBuckets) {+ const flushedDates = new Set();+ const allDates = Object.keys(dayBuckets);++ for (const dateStr of allDates) {+ const metrics = dayBuckets[dateStr];++ // Aggregate step_count: sum all qty values into single daily total+ if (metrics.step_count) {+ metrics.step_count = aggregateStepCount(metrics.step_count);+ }++ // Aggregate sleep_analysis: sum stage durations into daily summary+ if (metrics.sleep_analysis) {+ metrics.sleep_analysis = aggregateSleepAnalysis(metrics.sleep_analysis);+ }++ const dayData = await readDayFile(dateStr);++ for (const [metricName, newPoints] of Object.entries(metrics)) {+ const existing = dayData.metrics[metricName] || [];+ const existingDates = new Set(existing.map(p => p.date));+ const uniquePoints = newPoints.filter(p => !existingDates.has(p.date));+ if (uniquePoints.length > 0) {+ dayData.metrics[metricName] = existing.concat(uniquePoints);+ }+ }++ await writeDayFile(dateStr, dayData);+ flushedDates.add(dateStr);+ delete dayBuckets[dateStr];+ }++ return flushedDates;+}+/*** Stream-parse an Apple Health export.xml file using SAX.- * Accumulates records, aggregates step/sleep metrics, then writes day files.+ * Accumulates records in batches, flushing to disk periodically to avoid OOM.** @param {string} filePath - Absolute path to the XML file (temp upload)* @param {Object|null} io - Socket.IO server instance for progress events@@ -149,6 +255,11 @@ export async function importAppleHealthXml(filePath, io = null) {// dayBuckets: { [dateStr]: { [metricName]: [...dataPoints] } }const dayBuckets = {};let processedRecords = 0;+ let lastFlush = 0;+ const allDays = new Set();+ let flushing = false;++ const inputStream = createReadStream(filePath);await new Promise((resolve, reject) => {const saxStream = sax.createStream(false, { lowercase: true });@@ -164,6 +275,7 @@ export async function importAppleHealthXml(filePath, io = null) {if (!dayBuckets[dateStr]) dayBuckets[dateStr] = {};if (!dayBuckets[dateStr][metricName]) dayBuckets[dateStr][metricName] = [];dayBuckets[dateStr][metricName].push(dataPoint);+ allDays.add(dateStr);processedRecords++;@@ -171,6 +283,18 @@ export async function importAppleHealthXml(filePath, io = null) {io?.emit('health:xml:progress', { processed: processedRecords });console.log(`🍎 XML import progress: ${processedRecords} records`);}++ // Batch flush to prevent OOM — pause input stream, flush to disk, resume+ if (processedRecords - lastFlush >= FLUSH_INTERVAL && !flushing) {+ flushing = true;+ lastFlush = processedRecords;+ inputStream.pause();+ flushDayBuckets(dayBuckets).then(() => {+ console.log(`🍎 Flushed batch at ${processedRecords} records (${allDays.size} days total)`);+ flushing = false;+ inputStream.resume();+ }).catch(reject);+ }});saxStream.on('error', function (e) {@@ -183,50 +307,20 @@ export async function importAppleHealthXml(filePath, io = null) {saxStream.on('end', resolve);saxStream.on('close', resolve);- const readStream = createReadStream(filePath);- readStream.on('error', reject);- readStream.pipe(saxStream);+ inputStream.on('error', reject);+ inputStream.pipe(saxStream);});- console.log(`🍎 XML parsing done: ${processedRecords} raw records across ${Object.keys(dayBuckets).length} days — starting aggregation`);-- // === Aggregate and write day files, freeing each bucket after write ===- const allDates = Object.keys(dayBuckets);- let daysCount = allDates.length;-- for (const dateStr of allDates) {- const metrics = dayBuckets[dateStr];-- // Aggregate step_count: sum all qty values into single daily total- if (metrics.step_count) {- metrics.step_count = aggregateStepCount(metrics.step_count);- }-- // Aggregate sleep_analysis: sum stage durations into daily summary- if (metrics.sleep_analysis) {- metrics.sleep_analysis = aggregateSleepAnalysis(metrics.sleep_analysis);- }-- const dayData = await readDayFile(dateStr);-- for (const [metricName, newPoints] of Object.entries(metrics)) {- const existing = dayData.metrics[metricName] || [];- const existingDates = new Set(existing.map(p => p.date));- const uniquePoints = newPoints.filter(p => !existingDates.has(p.date));- if (uniquePoints.length > 0) {- dayData.metrics[metricName] = existing.concat(uniquePoints);- }- }+ console.log(`🍎 XML parsing done: ${processedRecords} raw records across ${allDays.size} days — flushing remaining`);- await writeDayFile(dateStr, dayData);- delete dayBuckets[dateStr];- }+ // Final flush for remaining records+ await flushDayBuckets(dayBuckets);// Clean up temp fileunlink(filePath, () => {});- io?.emit('health:xml:complete', { days: daysCount, records: processedRecords });- console.log(`🍎 XML import complete: ${processedRecords} records across ${daysCount} days`);+ io?.emit('health:xml:complete', { days: allDays.size, records: processedRecords });+ console.log(`🍎 XML import complete: ${processedRecords} records across ${allDays.size} days`);- return { days: daysCount, records: processedRecords };+ return { days: allDays.size, records: processedRecords };}