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([issue-705]): add health vitals tower to CyberCity (roadmap 2.9)
[._.]/ Adam Eivye24bf73d2875
diff --git a/client/src/components/city/CityHealthTower.jsx b/client/src/components/city/CityHealthTower.jsxnew file mode 100644index 0000000000..f7cb4e1a6b--- /dev/null+++ b/client/src/components/city/CityHealthTower.jsx@@ -0,0 +1,95 @@+import { useMemo, useRef } from 'react';+import { useFrame } from '@react-three/fiber';+import { Text } from '@react-three/drei';+import { PIXEL_FONT_URL } from './cityConstants';+import { computeHealthTower } from '../../utils/cityHealthTower';++// CyberCity's biometric vitals tower (roadmap 2.9): a stacked cylindrical landmark in a+// far-southeast wellness district. Each tier is one Apple Health metric (heart rate, steps,+// active calories, sleep) whose height and glow track that metric's latest value normalized+// against a target. A metric with no data reads as a thin dim disc (absent) — distinct from+// a present-but-zero value, which keeps its lit color. The heart-rate tier pulses like a+// heartbeat, faster as the rate climbs. Mirrors CityBackupVault / CityTaskQueue.+function Segment({ segment, baseRadius, isHeart, heartRef }) {+ const { height, color, intensity } = segment;+ return (+ <mesh ref={isHeart ? heartRef : undefined} position={[0, segment.y, 0]}>+ <cylinderGeometry args={[baseRadius, baseRadius, height, 32]} />+ <meshStandardMaterial+ color={segment.present ? '#0c1620' : '#0a0e16'}+ emissive={color}+ emissiveIntensity={intensity}+ metalness={0.5}+ roughness={0.5}+ toneMapped={false}+ />+ </mesh>+ );+}++export default function CityHealthTower({ healthMetrics, settings }) {+ const tower = useMemo(() => computeHealthTower(healthMetrics), [healthMetrics]);+ const heartRef = useRef();++ // Honor the quality dial: drop the heartbeat pulse on the lowest preset, but keep the+ // static glow so the vitals stay legible.+ const animate = (settings?.particleDensity ?? 1) >= 0.5;++ useFrame(({ clock }) => {+ if (!animate || !heartRef.current || !tower.heartPresent) return;+ // Heartbeat: a higher heart-rate level beats faster. Base intensity comes from the+ // view-model so a present-but-low reading still glows; the pulse rides on top.+ const bpm = 2.2 + tower.heartLevel * 3.5;+ const pulse = (Math.sin(clock.getElapsedTime() * bpm) + 1) / 2; // 0..1+ heartRef.current.material.emissiveIntensity = tower.heartIntensity + pulse * 0.6;+ });++ const { position, baseRadius, segments, totalHeight, hasData } = tower;++ return (+ <group position={position}>+ {/* Plinth the tower rises from */}+ <mesh position={[0, 0.3, 0]}>+ <cylinderGeometry args={[baseRadius * 1.3, baseRadius * 1.45, 0.6, 32]} />+ <meshStandardMaterial color="#0a0e16" emissive="#22c55e" emissiveIntensity={0.08} metalness={0.6} roughness={0.5} />+ </mesh>++ {/* Stacked metric segments — lifted above the plinth */}+ <group position={[0, 0.6, 0]}>+ {segments.map((segment) => (+ <Segment+ key={segment.key}+ segment={segment}+ baseRadius={baseRadius}+ isHeart={segment.key === 'heart_rate'}+ heartRef={heartRef}+ />+ ))}++ {/* Per-segment side labels so each tier is identifiable */}+ {segments.map((segment) => (+ <Text+ key={`label-${segment.key}`}+ position={[baseRadius + 0.6, segment.y, 0]}+ fontSize={0.55}+ color={segment.present ? segment.color : '#64748b'}+ anchorX="left"+ anchorY="middle"+ font={PIXEL_FONT_URL}+ maxWidth={14}+ >+ {segment.present ? `${segment.label} ${segment.value}${segment.unit ? ' ' + segment.unit : ''}` : `${segment.label} —`}+ </Text>+ ))}++ {/* Tower title + status above the stack */}+ <Text position={[0, totalHeight + 1.6, 0]} fontSize={1.2} color="#22c55e" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={18}>+ VITALS+ </Text>+ <Text position={[0, totalHeight + 0.8, 0]} fontSize={0.8} color="#94a3b8" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={18}>+ {hasData ? `${tower.presentCount}/${segments.length} TRACKED` : 'NO HEALTH DATA'}+ </Text>+ </group>+ </group>+ );+}diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsxindex daefd05d3d..f89f5d3a05 100644--- a/client/src/components/city/CityScene.jsx+++ b/client/src/components/city/CityScene.jsx@@ -17,6 +17,7 @@ import CitySkyline from './CitySkyline';import CityFederationHorizon from './CityFederationHorizon';import CityBackupVault from './CityBackupVault';import CityTaskQueue from './CityTaskQueue';+import CityHealthTower from './CityHealthTower';import CityDataRain from './CityDataRain';import CityNeonSigns from './CityNeonSigns';import CityEmbers from './CityEmbers';@@ -27,7 +28,7 @@ import CitySky from './CitySky';import PlayerController from './PlayerController';import CameraTransition from './CameraTransition';-export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, productivityData, settings, playSfx, keysRef, dimmedAppIds }) {+export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, productivityData, settings, playSfx, keysRef, dimmedAppIds }) {const [positions, setPositions] = useState(null);const [proximityApp, setProximityApp] = useState(null);const [transitioning, setTransitioning] = useState(false);@@ -78,6 +79,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,<CityFederationHorizon instances={instances} settings={settings} /><CityBackupVault backupStatus={backupStatus} settings={settings} /><CityTaskQueue cosTasks={cosTasks} settings={settings} />+ <CityHealthTower healthMetrics={healthMetrics} settings={settings} /><CityGround settings={settings} /><BuildingClusterdiff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.jsindex 8b6b057d52..46a69f11af 100644--- a/client/src/hooks/useCityData.js+++ b/client/src/hooks/useCityData.js@@ -2,6 +2,10 @@ import { useState, useEffect, useCallback, useMemo, useRef } from 'react';import * as api from '../services/api';import socket from '../services/socket';import { useAutoRefetch } from './useAutoRefetch';+import { METRICS as HEALTH_TOWER_METRICS } from '../utils/cityHealthTower';++// Metric keys the vitals-tower landmark renders — fetched as the latest-value snapshot.+const HEALTH_METRIC_KEYS = HEALTH_TOWER_METRICS.map(m => m.key);const healthSignature = (h) => {const warnings = (h?.warnings || []).map(w => `${w.type}:${w.message}`).join(';');@@ -20,6 +24,7 @@ export const useCityData = () => {const [notificationCounts, setNotificationCounts] = useState({ unread: 0 });const [backupStatus, setBackupStatus] = useState(null);const [cosTasks, setCosTasks] = useState([]);+ const [healthMetrics, setHealthMetrics] = useState(null);const [loading, setLoading] = useState(true);const logIdRef = useRef(0);@@ -33,7 +38,7 @@ export const useCityData = () => {// /notifications/count returns the lightweight { count } payload — the HUD// and Attention pane only need unread, and notifications:count socket// events keep it fresh after this initial fetch.- const [appsData, agents, cosAgentsData, status, reviewData, instanceData, health, notif, backup, cosTasksData] = await Promise.all([+ const [appsData, agents, cosAgentsData, status, reviewData, instanceData, health, notif, backup, cosTasksData, healthMetricsData] = await Promise.all([api.getApps().catch(() => []),api.getRunningAgents().catch(() => []),api.getCosAgents().catch(() => []),@@ -44,6 +49,7 @@ export const useCityData = () => {api.getNotificationCount().catch(() => ({ count: 0 })),api.getBackupStatus({ silent: true }).catch(() => null),api.getCosTasks({ silent: true }).catch(() => ({ tasks: [] })),+ api.getLatestHealthMetrics(HEALTH_METRIC_KEYS, { silent: true }).catch(() => null),]);setApps(appsData);@@ -56,6 +62,7 @@ export const useCityData = () => {setNotificationCounts({ unread: notif?.count ?? 0 });setBackupStatus(backup);setCosTasks(Array.isArray(cosTasksData?.tasks) ? cosTasksData.tasks : []);+ setHealthMetrics(healthMetricsData);setLoading(false);}, []);@@ -222,6 +229,7 @@ export const useCityData = () => {notificationCounts,backupStatus,cosTasks,+ healthMetrics,loading,connected: socket.connected,};diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsxindex 41885ca863..c92ac807c3 100644--- a/client/src/pages/CyberCity.jsx+++ b/client/src/pages/CyberCity.jsx@@ -13,7 +13,7 @@ import CitySettingsPanel from '../components/city/CitySettingsPanel';import { computeFilterResult } from '../utils/cityFilter';function CyberCityInner() {- const { apps, cosAgents, cosStatus, eventLogs, agentMap, reviewCounts, instances, systemHealth, notificationCounts, backupStatus, cosTasks, loading, connected } = useCityData();+ const { apps, cosAgents, cosStatus, eventLogs, agentMap, reviewCounts, instances, systemHealth, notificationCounts, backupStatus, cosTasks, healthMetrics, loading, connected } = useCityData();const { settings, updateSetting } = useCitySettingsContext();const { playSfx } = useCityAudio(settings);const navigate = useNavigate();@@ -108,6 +108,7 @@ function CyberCityInner() {instances={instances}backupStatus={backupStatus}cosTasks={cosTasks}+ healthMetrics={healthMetrics}productivityData={productivityData}settings={settings}playSfx={playSfx}diff --git a/client/src/services/apiHealth.js b/client/src/services/apiHealth.jsindex c7c7c11de8..3915c667ab 100644--- a/client/src/services/apiHealth.js+++ b/client/src/services/apiHealth.js@@ -18,8 +18,8 @@ export const getAppleHealthSummary = (metricName, from, to) => {return request(`/health/metrics/${metricName}?${params}`);};export const getAvailableHealthMetrics = () => request('/health/metrics/available');-export const getLatestHealthMetrics = (metricNames) =>- request(`/health/metrics/latest?metrics=${metricNames.join(',')}`);+export const getLatestHealthMetrics = (metricNames, options = {}) =>+ request(`/health/metrics/latest?metrics=${metricNames.join(',')}`, options);export const getAppleHealthRange = () => request('/health/range');export const getAppleHealthCorrelation = (from, to) => {const params = new URLSearchParams();diff --git a/client/src/utils/cityHealthTower.js b/client/src/utils/cityHealthTower.jsnew file mode 100644index 0000000000..3cc3d16088--- /dev/null+++ b/client/src/utils/cityHealthTower.js@@ -0,0 +1,96 @@+// Pure, deterministic helpers for CyberCity's biometric vitals tower (roadmap 2.9): a+// stacked landmark in a far-southeast wellness district whose segments visualize the+// latest Apple Health metrics (heart rate / steps / sleep / active calories). Each+// segment's height and glow track that metric's normalized level; a metric with no data+// reads dim (absent) — distinct from a metric whose value is legitimately zero (e.g. a+// 0-step day). No three.js / React imports so the topology is unit-testable (mirrors+// cityBackupVault.js / cityTaskQueue.js).++export const TOWER = {+ position: [48, 0, 28], // far southeast — a wellness district clear of the vault, warehouse, grid, and archive+ baseRadius: 3.2,+ segmentHeight: 3, // height of a fully-lit (level === 1) segment+ segmentGap: 0.25, // vertical gap between stacked segments+ minHeight: 0.35, // floor height so an absent/zero segment still reads as a thin disc, not nothing+};++// One descriptor per visualized metric, in stacking order (bottom → top). `key` is the+// Apple Health metric name as returned by GET /api/health/metrics/latest; `target` is the+// value mapped to a full (level === 1) segment; `color` reuses the meatspace health palette+// (which itself maps to PortOS tokens) so the tower speaks the same visual language.+export const METRICS = [+ { key: 'heart_rate', label: 'HEART', unit: 'bpm', target: 120, color: '#ef4444' }, // port-error red — the pulsing segment+ { key: 'step_count', label: 'STEPS', unit: 'steps', target: 10000, color: '#3b82f6' }, // port-accent blue+ { key: 'active_energy', label: 'CALORIES', unit: 'Cal', target: 600, color: '#f59e0b' }, // port-warning amber+ { key: 'sleep_analysis', label: 'SLEEP', unit: 'hrs', target: 8, color: '#8b5cf6' }, // violet+];++const DIM_COLOR = '#475569'; // slate — an absent (no-data) segment++const clamp01 = (n) => Math.max(0, Math.min(1, n));++// Normalize a raw metric value to a 0..1 level against its target, clamped. Returns null+// for a non-finite input so callers can distinguish "no usable number" from a real 0.+export function normalizeLevel(value, target) {+ if (typeof value !== 'number' || !Number.isFinite(value)) return null;+ if (typeof target !== 'number' || !Number.isFinite(target) || target <= 0) return null;+ return clamp01(value / target);+}++// Derive a single segment's view-model from the latest-metrics payload entry. The endpoint+// returns `{ date, value } | null` per metric — null (or a missing key) is the "absent"+// sentinel and must NOT collapse into the same state as a present value of 0.+export function computeSegment(descriptor, entry) {+ // Absent: key missing, null entry, or a non-numeric/absent value field.+ const rawValue = entry && typeof entry === 'object' ? entry.value : undefined;+ const hasValue = typeof rawValue === 'number' && Number.isFinite(rawValue);+ // normalizeLevel returns null when the value/target can't be normalized; an absent or+ // unnormalizable segment renders at level 0 (its `present` flag disambiguates from a real 0).+ const level = (hasValue ? normalizeLevel(rawValue, descriptor.target) : null) ?? 0;+ return {+ key: descriptor.key,+ label: descriptor.label,+ unit: descriptor.unit,+ present: hasValue,+ value: hasValue ? rawValue : null,+ date: entry && typeof entry === 'object' ? entry.date ?? null : null,+ level, // 0..1; 0 for both an absent segment and a legitimate zero — `present` disambiguates+ color: hasValue ? descriptor.color : DIM_COLOR,+ // Lit segment height scales with level (with a thin floor so it's always visible); an+ // absent segment collapses to the floor height and reads dim.+ height: TOWER.minHeight + (hasValue ? level : 0) * TOWER.segmentHeight,+ // Emissive intensity: present segments glow proportional to level (with a small base so+ // even a zero-value-but-present segment is faintly lit); absent segments stay dark.+ intensity: hasValue ? 0.25 + level * 0.75 : 0.08,+ };+}++// Full derived view-model for the component: a fixed base position plus a bottom→top stack+// of segments with their y offsets pre-computed. `latest` is the raw latest-metrics payload+// (`{ [metricKey]: { date, value } | null }`); a missing/non-object payload yields an+// all-absent tower rather than a crash.+export function computeHealthTower(latest) {+ const payload = latest && typeof latest === 'object' ? latest : {};+ let y = 0;+ const segments = METRICS.map((descriptor) => {+ const segment = computeSegment(descriptor, payload[descriptor.key]);+ const placed = { ...segment, y: y + segment.height / 2 };+ y += segment.height + TOWER.segmentGap;+ return placed;+ });+ const presentCount = segments.filter((s) => s.present).length;+ // The heart-rate segment drives the heartbeat pulse; pre-extract its level/intensity/+ // presence so the component's per-frame loop never re-searches the segment list.+ const heart = segments.find((s) => s.key === 'heart_rate');+ return {+ position: TOWER.position,+ baseRadius: TOWER.baseRadius,+ segments,+ totalHeight: y - (segments.length ? TOWER.segmentGap : 0), // top of the highest segment+ presentCount,+ hasData: presentCount > 0,+ heartPresent: heart?.present ?? false,+ heartLevel: heart?.level ?? 0,+ heartIntensity: heart?.intensity ?? 0,+ };+}diff --git a/client/src/utils/cityHealthTower.test.js b/client/src/utils/cityHealthTower.test.jsnew file mode 100644index 0000000000..b46d7807bd--- /dev/null+++ b/client/src/utils/cityHealthTower.test.js@@ -0,0 +1,157 @@+import { describe, it, expect } from 'vitest';+import {+ TOWER,+ METRICS,+ normalizeLevel,+ computeSegment,+ computeHealthTower,+} from './cityHealthTower';++const full = {+ heart_rate: { date: '2026-06-01', value: 60 },+ step_count: { date: '2026-06-01', value: 5000 },+ active_energy: { date: '2026-06-01', value: 300 },+ sleep_analysis: { date: '2026-06-01', value: 4 },+};++describe('normalizeLevel', () => {+ it('maps value/target into 0..1', () => {+ expect(normalizeLevel(5000, 10000)).toBe(0.5);+ expect(normalizeLevel(120, 120)).toBe(1);+ });++ it('clamps above target to 1 and below zero to 0', () => {+ expect(normalizeLevel(99999, 10000)).toBe(1);+ expect(normalizeLevel(-50, 10000)).toBe(0);+ });++ it('returns null for non-finite values or bad targets', () => {+ expect(normalizeLevel(NaN, 10000)).toBeNull();+ expect(normalizeLevel(undefined, 10000)).toBeNull();+ expect(normalizeLevel('5000', 10000)).toBeNull();+ expect(normalizeLevel(5000, 0)).toBeNull();+ expect(normalizeLevel(5000, -1)).toBeNull();+ });++ it('treats a legitimate zero value as level 0, not absent', () => {+ expect(normalizeLevel(0, 10000)).toBe(0);+ });+});++describe('computeSegment', () => {+ const heart = METRICS.find((m) => m.key === 'heart_rate');++ it('derives a present segment with proportional level and full color', () => {+ const seg = computeSegment(heart, { date: '2026-06-01', value: 60 });+ expect(seg.present).toBe(true);+ expect(seg.value).toBe(60);+ expect(seg.level).toBe(0.5);+ expect(seg.color).toBe(heart.color);+ expect(seg.height).toBeGreaterThan(TOWER.minHeight);+ });++ it('distinguishes a zero-value-but-present metric from an absent one', () => {+ const zero = computeSegment(heart, { date: '2026-06-01', value: 0 });+ expect(zero.present).toBe(true);+ expect(zero.value).toBe(0);+ expect(zero.level).toBe(0);+ expect(zero.color).toBe(heart.color); // still lit color, not the dim slate+ expect(zero.height).toBeCloseTo(TOWER.minHeight);+ expect(zero.intensity).toBeGreaterThan(0.08); // faintly lit, above the absent floor++ const absent = computeSegment(heart, null);+ expect(absent.present).toBe(false);+ expect(absent.value).toBeNull();+ expect(absent.level).toBe(0);+ expect(absent.color).not.toBe(heart.color); // dim slate+ expect(absent.height).toBeCloseTo(TOWER.minHeight);+ expect(absent.intensity).toBeLessThan(zero.intensity);+ });++ it('treats a missing/undefined entry as absent without crashing', () => {+ expect(computeSegment(heart, undefined).present).toBe(false);+ expect(computeSegment(heart, {}).present).toBe(false);+ expect(computeSegment(heart, { date: '2026-06-01', value: null }).present).toBe(false);+ expect(computeSegment(heart, { value: 'oops' }).present).toBe(false);+ });++ it('clamps a level above target to 1', () => {+ const seg = computeSegment(heart, { value: 999 });+ expect(seg.level).toBe(1);+ expect(seg.height).toBeCloseTo(TOWER.minHeight + TOWER.segmentHeight);+ });+});++describe('computeHealthTower', () => {+ it('carries the fixed position and base radius through unchanged', () => {+ const vm = computeHealthTower(full);+ expect(vm.position).toEqual(TOWER.position);+ expect(vm.baseRadius).toBe(TOWER.baseRadius);+ });++ it('produces one segment per metric in stacking order', () => {+ const vm = computeHealthTower(full);+ expect(vm.segments).toHaveLength(METRICS.length);+ expect(vm.segments.map((s) => s.key)).toEqual(METRICS.map((m) => m.key));+ });++ it('stacks segments upward with strictly increasing y', () => {+ const vm = computeHealthTower(full);+ for (let i = 1; i < vm.segments.length; i++) {+ expect(vm.segments[i].y).toBeGreaterThan(vm.segments[i - 1].y);+ }+ });++ it('reports presentCount and hasData from full metrics', () => {+ const vm = computeHealthTower(full);+ expect(vm.presentCount).toBe(METRICS.length);+ expect(vm.hasData).toBe(true);+ expect(vm.heartLevel).toBeCloseTo(0.5);+ });++ it('handles partial metrics — absent segments dim, present ones lit', () => {+ const vm = computeHealthTower({ step_count: { value: 10000 } });+ expect(vm.presentCount).toBe(1);+ expect(vm.hasData).toBe(true);+ const steps = vm.segments.find((s) => s.key === 'step_count');+ const heart = vm.segments.find((s) => s.key === 'heart_rate');+ expect(steps.present).toBe(true);+ expect(steps.level).toBe(1);+ expect(heart.present).toBe(false);+ expect(heart.level).toBe(0);+ });++ it('handles an all-null payload as an all-absent tower (no crash)', () => {+ const vm = computeHealthTower({+ heart_rate: null,+ step_count: null,+ active_energy: null,+ sleep_analysis: null,+ });+ expect(vm.presentCount).toBe(0);+ expect(vm.hasData).toBe(false);+ expect(vm.segments.every((s) => !s.present)).toBe(true);+ });++ it('handles null / undefined / non-object input as all-absent', () => {+ for (const bad of [null, undefined, 'nope', 42, []]) {+ const vm = computeHealthTower(bad);+ expect(vm.presentCount).toBe(0);+ expect(vm.hasData).toBe(false);+ expect(vm.segments).toHaveLength(METRICS.length);+ }+ });++ it('keeps all segment levels within [0,1]', () => {+ const vm = computeHealthTower({+ heart_rate: { value: -10 },+ step_count: { value: 1e9 },+ active_energy: { value: 0 },+ sleep_analysis: { value: 8 },+ });+ for (const s of vm.segments) {+ expect(s.level).toBeGreaterThanOrEqual(0);+ expect(s.level).toBeLessThanOrEqual(1);+ }+ });+});