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 chronotype energy overlay to CyberCity (roadmap 3.1)
[._.]/ Adam Eivy6c341a72ad72
diff --git a/client/src/components/city/CityEnergyOverlay.jsx b/client/src/components/city/CityEnergyOverlay.jsxnew file mode 100644index 0000000000..bf386e37c0--- /dev/null+++ b/client/src/components/city/CityEnergyOverlay.jsx@@ -0,0 +1,52 @@+import { useRef } from 'react';+import { useFrame } from '@react-three/fiber';+import { computeChronotypeEnergy } from '../../utils/cityChronotype';++// CyberCity's chronotype energy overlay (roadmap 3.1): a subtle ambient atmosphere+// that brightens and warms the city during the user's peak focus hours and dims it+// during wind-down and recovery hours. It does NOT replace the scene lighting+// (CityLights) — it composes on top with a single gentle, energy-tinted ambient+// light so the user's circadian rhythm reads as the city's mood. No label; it's+// pure ambiance.+//+// The pure helper (cityChronotype.js) takes the hour as a parameter for testability;+// the live hour is computed here in the component.++// Energy mid-point — at neutral energy the overlay contributes almost nothing.+const BASE_INTENSITY = 0.12;++export default function CityEnergyOverlay({ chronotype, settings }) {+ const lightRef = useRef();++ // Honor the quality dial: skip the per-frame energy lerp on the lowest preset, but+ // still apply a static energy tint so the chronotype mood is legible.+ const animate = (settings?.particleDensity ?? 1) >= 0.5;++ // Smoothed brightness so a clock tick across an hour boundary fades rather than jumps.+ const smoothedRef = useRef(null);++ useFrame((_, delta) => {+ if (!lightRef.current) return;++ const hour = new Date().getHours() + new Date().getMinutes() / 60;+ const { brightness } = computeChronotypeEnergy(chronotype, hour);++ // High energy → warmer/brighter; low energy → cooler/dimmer. Intensity rides+ // the brightness modifier (clamped 0.7–1.15 in the helper) so it stays subtle.+ const targetIntensity = BASE_INTENSITY * brightness;++ if (!animate || smoothedRef.current === null) {+ smoothedRef.current = targetIntensity;+ } else {+ const lf = Math.min(1, delta * 1.5);+ smoothedRef.current += (targetIntensity - smoothedRef.current) * lf;+ }++ lightRef.current.intensity = smoothedRef.current;+ });++ // A warm-tinted ambient fill — peak hours glow a touch warmer/brighter, recovery+ // hours fade it toward nothing. Faint by design so it layers over CityLights+ // without washing out the existing palette.+ return <ambientLight ref={lightRef} intensity={BASE_INTENSITY} color="#ffd9a0" />;+}diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsxindex 48e31adbb6..1dcdd6de68 100644--- a/client/src/components/city/CityScene.jsx+++ b/client/src/components/city/CityScene.jsx@@ -29,10 +29,11 @@ import CityEffects from './CityEffects';import CityClouds from './CityClouds';import CitySignalBeacons from './CitySignalBeacons';import CitySky from './CitySky';+import CityEnergyOverlay from './CityEnergyOverlay';import PlayerController from './PlayerController';import CameraTransition from './CameraTransition';-export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, goals, settings, playSfx, keysRef, dimmedAppIds }) {+export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, goals, chronotype, settings, playSfx, keysRef, dimmedAppIds }) {const [positions, setPositions] = useState(null);const [proximityApp, setProximityApp] = useState(null);const [transitioning, setTransitioning] = useState(false);@@ -76,6 +77,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,<CitySky settings={settings} /><CityClouds settings={settings} /><CityLights settings={settings} />+ <CityEnergyOverlay chronotype={chronotype} settings={settings} /><CityStarfield settings={settings} /><CityShootingStars playSfx={playSfx} settings={settings} />{!explorationMode && <CityCelestial settings={settings} />}diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsxindex 7c18f44c43..314191f5bf 100644--- a/client/src/pages/CyberCity.jsx+++ b/client/src/pages/CyberCity.jsx@@ -75,6 +75,14 @@ function CyberCityInner() {120_000,);+ // Chronotype profile drives the ambient energy overlay — the city brightens during+ // peak focus hours and dims during recovery. Low-frequency: the daily schedule+ // rarely changes. Same last-good-snapshot semantics as the fetches above.+ const { data: chronotypeData } = useAutoRefetch(+ () => api.getChronotype({ silent: true }),+ 600_000,+ );+const handleBuildingClick = useCallback((app) => {if (app?.id) {navigate(`/apps/${app.id}`);@@ -120,6 +128,7 @@ function CyberCityInner() {aiActivity={aiActivity}productivityData={productivityData}goals={goalsData}+ chronotype={chronotypeData}settings={settings}playSfx={playSfx}keysRef={keysRef}diff --git a/client/src/services/apiGoals.js b/client/src/services/apiGoals.jsindex 72642bc041..1b008d6686 100644--- a/client/src/services/apiGoals.js+++ b/client/src/services/apiGoals.js@@ -3,7 +3,7 @@ import { request } from './apiCore.js';// Digital Twin - Identity & Goalsexport const getIdentityStatus = () => request('/digital-twin/identity');export const getCrossInsights = () => request('/digital-twin/identity/cross-insights');-export const getChronotype = () => request('/digital-twin/identity/chronotype');+export const getChronotype = (options) => request('/digital-twin/identity/chronotype', options);export const getChronotypeEnergySchedule = () => request('/digital-twin/identity/chronotype/energy-schedule');export const deriveChronotype = () => request('/digital-twin/identity/chronotype/derive', { method: 'POST' });export const updateChronotypeBehavioral = (data) => request('/digital-twin/identity/chronotype', {diff --git a/client/src/utils/cityChronotype.js b/client/src/utils/cityChronotype.jsnew file mode 100644index 0000000000..cd5c24a1b5--- /dev/null+++ b/client/src/utils/cityChronotype.js@@ -0,0 +1,133 @@+// Pure, deterministic helpers for CyberCity's chronotype energy overlay (roadmap 3.1):+// the city brightens and quickens during the user's peak focus hours and dims/slows+// during wind-down and sleep. Energy is derived from the digital-twin chronotype+// profile's recommended daily schedule (wake / peak focus / wind-down / sleep). No+// three.js / React imports so the topology is unit-testable (mirrors cityBackupVault.js).+//+// The hour-of-day is ALWAYS injected as a parameter — no `new Date()` here — so the+// energy curve is deterministic in tests. The component computes the live hour and+// passes it in.++// Sentinel energy for "no usable profile" — distinct from any real curve value so a+// missing profile is recognizable. It maps to NEUTRAL_MODIFIERS (no visible change),+// NOT to peak brightness, so an unconfigured city looks untouched rather than washed out.+export const NEUTRAL_ENERGY = 1.0;++// Tasteful clamp ranges so the overlay stays atmospheric, never washing out or+// blacking out the existing scene. Brightness rides slightly above/below 1; tempo+// (animation-speed multiplier) is gentler still.+export const ENERGY_RANGE = {+ brightnessMin: 0.7,+ brightnessMax: 1.15,+ tempoMin: 0.8,+ tempoMax: 1.15,+};++// What the overlay applies when there's no usable chronotype profile: a true no-op —+// brightness and tempo at 1.0 so the scene renders exactly as it would without the+// overlay. Keeps "unconfigured / failed to fetch" visually distinct from "low energy."+export const NEUTRAL_MODIFIERS = { energy: NEUTRAL_ENERGY, brightness: 1.0, tempo: 1.0 };++const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));++// Parse "HH:MM" → fractional hours in [0,24). Returns NaN for unparseable input.+// Hours past midnight that belong to "today's" late night (e.g. a 00:30 sleep time)+// are returned as-is (0.5); callers that need a continuous timeline normalize.+export function parseHour(str) {+ if (typeof str !== 'string') return NaN;+ const [h, m] = str.split(':').map(Number);+ if (!Number.isFinite(h) || !Number.isFinite(m)) return NaN;+ const val = h + m / 60;+ return val >= 0 && val < 24 ? val : NaN;+}++// Circular distance between two hours on a 24h clock (shortest arc), in [0,12].+function hourDistance(a, b) {+ const d = Math.abs(a - b) % 24;+ return Math.min(d, 24 - d);+}++// Build the set of energy anchor points from the chronotype recommendations.+// Each anchor is { hour, energy } where energy ∈ [0,1]: 1 at the center of peak+// focus, low through wind-down and sleep, mid on waking. Returns null when the+// profile lacks the timing fields we need (caller falls back to neutral).+function buildAnchors(profile) {+ const rec = profile?.recommendations;+ if (!rec) return null;++ const wake = parseHour(rec.wakeTime);+ const peakStart = parseHour(rec.peakFocusStart);+ const peakEnd = parseHour(rec.peakFocusEnd);+ const windDown = parseHour(rec.windDownStart);+ const sleep = parseHour(rec.sleepTime);++ const anchors = [];++ // Peak focus center → maximum energy. This is the anchor the overlay is built+ // around, so we require at least the peak window to be present.+ if (Number.isFinite(peakStart) && Number.isFinite(peakEnd)) {+ const center = peakStart + ((peakEnd - peakStart + 24) % 24) / 2;+ anchors.push({ hour: center % 24, energy: 1.0 });+ } else {+ return null;+ }++ // Waking → ramping up (mid energy).+ if (Number.isFinite(wake)) anchors.push({ hour: wake, energy: 0.55 });++ // Wind-down → low energy.+ if (Number.isFinite(windDown)) anchors.push({ hour: windDown, energy: 0.3 });++ // Sleep → lowest energy (recovery / dim city).+ if (Number.isFinite(sleep)) anchors.push({ hour: sleep, energy: 0.12 });++ return anchors;+}++// Given the chronotype profile and the current hour (0..23, fractional ok), compute+// an energy level in [0,1]. Energy is the inverse-distance-weighted blend of the+// nearest anchors on the 24h clock — smooth, wrap-around-aware, no hard edges.+// Returns `null` (sentinel) when there's no usable profile or the hour is non-finite,+// so callers can distinguish "no profile" from a real curve value that happens to be+// 1.0 (peak focus center). Callers map null → neutral (no visible change).+export function computeEnergy(profile, hour) {+ const anchors = buildAnchors(profile);+ if (!anchors || !Number.isFinite(hour)) return null;++ let weightSum = 0;+ let energySum = 0;+ for (const a of anchors) {+ const dist = hourDistance(hour, a.hour);+ // Exact hit on an anchor returns it directly (avoids divide-by-zero).+ if (dist < 1e-6) return clamp(a.energy, 0, 1);+ const weight = 1 / (dist * dist);+ weightSum += weight;+ energySum += weight * a.energy;+ }+ return clamp(energySum / weightSum, 0, 1);+}++// Map an energy level 0..1 → the tasteful, clamped display modifiers the overlay+// applies: a brightness multiplier and a tempo (animation-speed) multiplier. Energy+// 1 → top of each range, energy 0 → bottom; linear in between. A null/non-finite+// energy (no usable profile) returns NEUTRAL_MODIFIERS — a true no-op.+export function energyModifiers(energy) {+ if (!Number.isFinite(energy)) return { ...NEUTRAL_MODIFIERS };+ const e = clamp(energy, 0, 1);+ const { brightnessMin, brightnessMax, tempoMin, tempoMax } = ENERGY_RANGE;+ return {+ energy: e,+ brightness: clamp(brightnessMin + e * (brightnessMax - brightnessMin), brightnessMin, brightnessMax),+ tempo: clamp(tempoMin + e * (tempoMax - tempoMin), tempoMin, tempoMax),+ };+}++// Full derived view-model for the component: energy + brightness + tempo. `hour` is+// injected so the whole view-model is deterministic under test. A missing/partial+// profile (or non-finite hour) yields NEUTRAL_MODIFIERS — a true no-op (brightness+// and tempo at 1.0), so an unconfigured city is untouched rather than washed out or+// dimmed. A real curve value of exactly 1.0 (peak focus center) still maps to peak+// brightness because computeEnergy returns null — not 1.0 — for the "no profile" case.+export function computeChronotypeEnergy(profile, hour) {+ return energyModifiers(computeEnergy(profile, hour));+}diff --git a/client/src/utils/cityChronotype.test.js b/client/src/utils/cityChronotype.test.jsnew file mode 100644index 0000000000..f365370b89--- /dev/null+++ b/client/src/utils/cityChronotype.test.js@@ -0,0 +1,152 @@+import { describe, it, expect } from 'vitest';+import {+ NEUTRAL_ENERGY,+ NEUTRAL_MODIFIERS,+ ENERGY_RANGE,+ parseHour,+ computeEnergy,+ energyModifiers,+ computeChronotypeEnergy,+} from './cityChronotype';++// A representative "intermediate" chronotype profile (mirrors the shape returned by+// GET /api/digital-twin/identity/chronotype — only the recommendations the overlay+// reads are included).+const PROFILE = {+ type: 'intermediate',+ recommendations: {+ wakeTime: '07:00',+ sleepTime: '23:00',+ peakFocusStart: '09:30',+ peakFocusEnd: '13:00',+ windDownStart: '21:30',+ },+};+// Peak focus center is (9.5 + 13) / 2 = 11.25.+const PEAK_HOUR = 11.25;++describe('parseHour', () => {+ it('parses HH:MM to fractional hours', () => {+ expect(parseHour('09:30')).toBeCloseTo(9.5);+ expect(parseHour('00:00')).toBe(0);+ expect(parseHour('23:45')).toBeCloseTo(23.75);+ });++ it('returns NaN for non-strings or out-of-range values', () => {+ expect(parseHour(null)).toBeNaN();+ expect(parseHour(undefined)).toBeNaN();+ expect(parseHour('not-a-time')).toBeNaN();+ expect(parseHour('24:00')).toBeNaN();+ });+});++describe('computeEnergy', () => {+ it('is highest at the peak focus center', () => {+ const atPeak = computeEnergy(PROFILE, PEAK_HOUR);+ const atWake = computeEnergy(PROFILE, 7);+ const atSleep = computeEnergy(PROFILE, 23);+ expect(atPeak).toBeGreaterThan(atWake);+ expect(atPeak).toBeGreaterThan(atSleep);+ expect(atPeak).toBeCloseTo(1.0, 5);+ });++ it('is lowest during recovery (sleep) hours', () => {+ const atSleep = computeEnergy(PROFILE, 23);+ const atPeak = computeEnergy(PROFILE, PEAK_HOUR);+ expect(atSleep).toBeLessThan(atPeak);+ expect(atSleep).toBeLessThan(0.5);+ });++ it('returns null (sentinel) for a missing or partial profile (no crash)', () => {+ expect(computeEnergy(null, 12)).toBeNull();+ expect(computeEnergy({}, 12)).toBeNull();+ expect(computeEnergy({ recommendations: {} }, 12)).toBeNull();+ // peak window missing → can't anchor → null+ expect(computeEnergy({ recommendations: { wakeTime: '07:00' } }, 12)).toBeNull();+ });++ it('returns null when the hour is not finite', () => {+ expect(computeEnergy(PROFILE, NaN)).toBeNull();+ expect(computeEnergy(PROFILE, undefined)).toBeNull();+ });++ it('stays within [0,1] across the whole day', () => {+ for (let h = 0; h < 24; h += 0.5) {+ const e = computeEnergy(PROFILE, h);+ expect(e).toBeGreaterThanOrEqual(0);+ expect(e).toBeLessThanOrEqual(1);+ }+ });++ it('handles wrap-around midnight for an evening chronotype with after-midnight sleep', () => {+ const evening = {+ recommendations: {+ wakeTime: '08:30',+ sleepTime: '00:30', // 12:30 AM — wraps past midnight+ peakFocusStart: '11:00',+ peakFocusEnd: '15:00',+ windDownStart: '23:00',+ },+ };+ // The post-midnight small hours should read as low energy (close to the 00:30 sleep anchor).+ const at1am = computeEnergy(evening, 1);+ const atPeak = computeEnergy(evening, 13); // peak center+ expect(at1am).toBeLessThan(atPeak);+ expect(at1am).toBeLessThan(0.5);+ });+});++describe('energyModifiers', () => {+ it('maps energy 1 to the top of each clamped range', () => {+ const m = energyModifiers(1);+ expect(m.brightness).toBeCloseTo(ENERGY_RANGE.brightnessMax);+ expect(m.tempo).toBeCloseTo(ENERGY_RANGE.tempoMax);+ expect(m.energy).toBe(1);+ });++ it('maps energy 0 to the bottom of each clamped range', () => {+ const m = energyModifiers(0);+ expect(m.brightness).toBeCloseTo(ENERGY_RANGE.brightnessMin);+ expect(m.tempo).toBeCloseTo(ENERGY_RANGE.tempoMin);+ });++ it('clamps out-of-range energy and treats null/non-finite as a neutral no-op', () => {+ expect(energyModifiers(5).brightness).toBeCloseTo(ENERGY_RANGE.brightnessMax);+ expect(energyModifiers(-3).brightness).toBeCloseTo(ENERGY_RANGE.brightnessMin);+ // null/NaN energy (no usable profile) → neutral no-op, brightness 1.0 (untouched scene).+ expect(energyModifiers(null)).toEqual(NEUTRAL_MODIFIERS);+ expect(energyModifiers(NaN)).toEqual(NEUTRAL_MODIFIERS);+ });++ it('keeps brightness and tempo strictly inside the tasteful bounds', () => {+ for (let e = 0; e <= 1; e += 0.1) {+ const m = energyModifiers(e);+ expect(m.brightness).toBeGreaterThanOrEqual(ENERGY_RANGE.brightnessMin);+ expect(m.brightness).toBeLessThanOrEqual(ENERGY_RANGE.brightnessMax);+ expect(m.tempo).toBeGreaterThanOrEqual(ENERGY_RANGE.tempoMin);+ expect(m.tempo).toBeLessThanOrEqual(ENERGY_RANGE.tempoMax);+ }+ });+});++describe('computeChronotypeEnergy', () => {+ it('peak hour → high brightness, recovery hour → low brightness', () => {+ const peak = computeChronotypeEnergy(PROFILE, PEAK_HOUR);+ const recovery = computeChronotypeEnergy(PROFILE, 23);+ expect(peak.brightness).toBeGreaterThan(recovery.brightness);+ expect(peak.tempo).toBeGreaterThan(recovery.tempo);+ });++ it('missing profile → neutral no-op modifiers (brightness 1.0), no crash', () => {+ const m = computeChronotypeEnergy(null, 12);+ expect(m).toEqual(NEUTRAL_MODIFIERS);+ expect(m.energy).toBe(NEUTRAL_ENERGY);+ expect(m.brightness).toBe(1.0);+ });++ it('peak focus center (real energy 1.0) maps to peak brightness, not the neutral no-op', () => {+ const m = computeChronotypeEnergy(PROFILE, PEAK_HOUR);+ expect(m.brightness).toBeCloseTo(ENERGY_RANGE.brightnessMax);+ expect(m.brightness).not.toBe(1.0);+ });+});