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 character XP HUD badge to CyberCity (roadmap 2.11)
[._.]/ Adam Eivyf9b57ee0b7a3
diff --git a/client/src/components/city/CityHud.jsx b/client/src/components/city/CityHud.jsxindex 95fe76f42e..3dd52f32b7 100644--- a/client/src/components/city/CityHud.jsx+++ b/client/src/components/city/CityHud.jsx@@ -3,6 +3,7 @@ import { useNavigate, useLocation } from 'react-router-dom';import CityIntelPane from './CityIntelPane';import CityAgentBar from './CityAgentBar';import CityFilterBar from './CityFilterBar';+import CityXpBadge from './CityXpBadge';// WASD controls hint shown briefly on first exploration entryfunction ControlsHint({ visible }) {@@ -160,7 +161,7 @@ function HealthBar({ value, max, color }) {);}-export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, connected, apps, reviewCounts, instances, productivityData, systemHealth, notificationCounts, filter, onFilterChange, onJumpToFirst, matchCount, onToggleExploration, explorationMode }) {+export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, connected, apps, reviewCounts, instances, productivityData, systemHealth, notificationCounts, character, filter, onFilterChange, onJumpToFirst, matchCount, onToggleExploration, explorationMode }) {const navigate = useNavigate();const location = useLocation();const [time, setTime] = useState(new Date());@@ -421,6 +422,9 @@ export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, con{/* Bottom: Agent status bar */}<CityAgentBar cosAgents={cosAgents} agentMap={agentMap} />+ {/* Bottom-right: character level / XP HUD badge (roadmap 2.11) */}+ <CityXpBadge character={character} />+{/* Center crosshair in exploration mode */}{explorationMode && (<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 pointer-events-none">diff --git a/client/src/components/city/CityXpBadge.jsx b/client/src/components/city/CityXpBadge.jsxnew file mode 100644index 0000000000..47ab8ee72e--- /dev/null+++ b/client/src/components/city/CityXpBadge.jsx@@ -0,0 +1,130 @@+import { useState, useEffect, useRef, useMemo } from 'react';+import { useNavigate } from 'react-router-dom';+import { computeXpView, diffXp } from '../../utils/characterXp';++// CyberCity character XP HUD badge (roadmap 2.11). A compact floating panel showing the+// current level + an XP progress bar toward the next level (and HP when known). Since+// there's no XP-gain socket event, useCityData polls the character on an interval; this+// component diffs successive snapshots and fires a transient flash on XP gain — a louder,+// longer celebratory flash on level-up.+//+// Animations are self-contained (transient state + inline transition) so the component+// stays standalone and doesn't depend on global keyframes.+export default function CityXpBadge({ character }) {+ const navigate = useNavigate();+ const view = useMemo(() => computeXpView(character), [character]);++ const prevCharRef = useRef(null);+ // burst.kind: null | 'gain' | 'levelup' — drives the flash overlay; burst.seq forces a+ // re-trigger even when two consecutive bursts are the same kind.+ const [burst, setBurst] = useState({ kind: null, seq: 0, gained: 0 });+ const burstTimerRef = useRef(null);++ useEffect(() => {+ const prev = prevCharRef.current;+ prevCharRef.current = character;+ if (!character) return;++ const { gained, leveledUp } = diffXp(prev, character);+ if (gained <= 0) return;++ setBurst(b => ({ kind: leveledUp ? 'levelup' : 'gain', seq: b.seq + 1, gained }));+ clearTimeout(burstTimerRef.current);+ burstTimerRef.current = setTimeout(+ () => setBurst(b => ({ ...b, kind: null })),+ leveledUp ? 2200 : 1100,+ );+ }, [character]);++ // Clear the pending flash timer on unmount so it can't fire into a dead component.+ useEffect(() => () => clearTimeout(burstTimerRef.current), []);++ // Render nothing until we have a real character — avoids a flash of a zeroed badge+ // before the first poll lands (absent vs. a legitimate level-1 zero-XP character).+ if (!character) return null;++ const leveling = burst.kind === 'levelup';+ const gaining = burst.kind !== null;+ const barColor = leveling ? '#f59e0b' : '#06b6d4';+ const pct = Math.round(view.progress * 100);++ return (+ <div className="absolute bottom-16 right-3 pointer-events-auto">+ <button+ type="button"+ onClick={() => navigate('/character')}+ title="Open character sheet"+ className={`relative block w-40 sm:w-48 bg-black/85 backdrop-blur-sm border rounded-lg px-3 py-2.5 overflow-hidden text-left transition-all duration-300 hover:bg-cyan-500/10 ${+ leveling+ ? 'border-amber-400/70 shadow-[0_0_16px_rgba(245,158,11,0.5)]'+ : gaining+ ? 'border-cyan-400/70 shadow-[0_0_12px_rgba(6,182,212,0.45)]'+ : 'border-cyan-500/30'+ }`}+ >+ {/* Transient flash overlay keyed on burst.seq so it re-mounts each gain */}+ {gaining && (+ <div+ key={burst.seq}+ className="absolute inset-0 pointer-events-none"+ style={{+ background: leveling+ ? 'radial-gradient(circle at 50% 50%, rgba(245,158,11,0.45), transparent 70%)'+ : 'radial-gradient(circle at 50% 50%, rgba(6,182,212,0.35), transparent 70%)',+ animation: leveling ? 'cos-pulse 0.55s ease-in-out 3' : 'cos-pulse 0.5s ease-in-out 2',+ }}+ />+ )}++ <div className="relative flex items-center justify-between gap-2">+ <div className="flex items-center gap-2">+ <span+ className={`font-pixel text-base tracking-wider ${leveling ? 'text-amber-300' : 'text-cyan-300'}`}+ style={{ textShadow: leveling ? '0 0 10px rgba(245,158,11,0.7)' : '0 0 8px rgba(6,182,212,0.5)' }}+ >+ LV {view.level}+ </span>+ {view.atMax && (+ <span className="font-pixel text-[8px] text-amber-400/80 tracking-wider">MAX</span>+ )}+ </div>+ {gaining && burst.gained > 0 && (+ <span+ className={`font-pixel text-[10px] tracking-wide ${leveling ? 'text-amber-300' : 'text-emerald-400'}`}+ style={{ textShadow: '0 0 6px currentColor' }}+ >+ +{burst.gained}+ </span>+ )}+ </div>++ {/* XP progress bar toward next level */}+ <div className="relative mt-1.5 w-full h-1.5 bg-gray-800/70 rounded-full overflow-hidden">+ <div+ className="h-full rounded-full transition-all duration-700"+ style={{+ width: `${view.atMax ? 100 : pct}%`,+ backgroundColor: barColor,+ boxShadow: `0 0 6px ${barColor}`,+ }}+ />+ </div>++ <div className="relative flex items-center justify-between mt-1">+ <span className="font-pixel text-[8px] text-gray-500 tracking-wider">+ {view.atMax ? 'MAX LEVEL' : `${view.xpIntoLevel}/${view.xpForNextLevel} XP`}+ </span>+ {view.hp != null && view.maxHp != null && (+ <span+ className={`font-pixel text-[8px] tracking-wider ${+ view.maxHp > 0 && view.hp / view.maxHp <= 0.25 ? 'text-red-400' : 'text-rose-300/70'+ }`}+ >+ {view.hp}/{view.maxHp} HP+ </span>+ )}+ </div>+ </button>+ </div>+ );+}diff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.jsindex 8b6b057d52..96dc343e35 100644--- a/client/src/hooks/useCityData.js+++ b/client/src/hooks/useCityData.js@@ -20,6 +20,7 @@ export const useCityData = () => {const [notificationCounts, setNotificationCounts] = useState({ unread: 0 });const [backupStatus, setBackupStatus] = useState(null);const [cosTasks, setCosTasks] = useState([]);+ const [character, setCharacter] = useState(null);const [loading, setLoading] = useState(true);const logIdRef = useRef(0);@@ -33,7 +34,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, characterData] = await Promise.all([api.getApps().catch(() => []),api.getRunningAgents().catch(() => []),api.getCosAgents().catch(() => []),@@ -44,6 +45,7 @@ export const useCityData = () => {api.getNotificationCount().catch(() => ({ count: 0 })),api.getBackupStatus({ silent: true }).catch(() => null),api.getCosTasks({ silent: true }).catch(() => ({ tasks: [] })),+ api.getCharacter({ silent: true }).catch(() => null),]);setApps(appsData);@@ -56,6 +58,7 @@ export const useCityData = () => {setNotificationCounts({ unread: notif?.count ?? 0 });setBackupStatus(backup);setCosTasks(Array.isArray(cosTasksData?.tasks) ? cosTasksData.tasks : []);+ if (characterData) setCharacter(characterData);setLoading(false);}, []);@@ -82,6 +85,15 @@ export const useCityData = () => {});}, []);+ // Character XP badge: there's no XP-gain socket event, so the only way an XP+ // gain (e.g. a synced JIRA ticket / completed task) surfaces in the HUD is a+ // periodic poll. The Xp badge diffs successive snapshots to fire its burst.+ // Preserve last-good character on a transient blip (don't wipe to null).+ const fetchCharacter = useCallback(async () => {+ const next = await api.getCharacter({ silent: true }).catch(() => null);+ if (next) setCharacter(next);+ }, []);+// Only overwrite the running-agents HUD/list when a fresh fetch lands —// a transient blip used to wipe the visible agents to `[]` until the// next successful poll.@@ -100,6 +112,7 @@ export const useCityData = () => {// cadence without double-fetching at mount.useAutoRefetch(fetchRunningAgents, 10_000, { immediate: false, pollOnly: true });useAutoRefetch(fetchHealth, 15_000, { immediate: false, pollOnly: true });+ useAutoRefetch(fetchCharacter, 15_000, { immediate: false, pollOnly: true });const agentMap = useMemo(() => {const map = new Map();@@ -222,6 +235,7 @@ export const useCityData = () => {notificationCounts,backupStatus,cosTasks,+ character,loading,connected: socket.connected,};diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsxindex 41885ca863..990fb979a0 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, character, loading, connected } = useCityData();const { settings, updateSetting } = useCitySettingsContext();const { playSfx } = useCityAudio(settings);const navigate = useNavigate();@@ -126,6 +126,7 @@ function CyberCityInner() {productivityData={productivityData}systemHealth={systemHealth}notificationCounts={notificationCounts}+ character={character}filter={filter}onFilterChange={setFilter}onJumpToFirst={handleJumpToFirst}diff --git a/client/src/services/README.md b/client/src/services/README.mdindex b0952f8d9c..454b9ff68c 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -55,7 +55,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiRuns.js` | Agent run history. || `apiScaffold.js` | App scaffolding templates. || `apiSchedules.js` | Automation schedules. |-| `apiSystem.js` | System info (CPU/memory/ports/alerts). |+| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter. || `apiLoops.js` | Scheduled loops. |## Personal data / identitydiff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex ff2b2f45eb..23cc0df9d5 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -3,6 +3,9 @@ import { request } from './apiCore.js';// Alertsexport const getAlertsSummary = (options) => request('/alerts/summary', options);+// Character sheet (D&D-style XP / level / HP — powers the CyberCity XP HUD badge)+export const getCharacter = (options) => request('/character', options);+// Healthexport const checkHealth = () => request('/system/health');export const getSystemHealth = (options) => request('/system/health/details', options);diff --git a/client/src/utils/characterXp.js b/client/src/utils/characterXp.jsnew file mode 100644index 0000000000..9a98937630--- /dev/null+++ b/client/src/utils/characterXp.js@@ -0,0 +1,82 @@+// Pure, deterministic helpers for CyberCity's character XP HUD badge (roadmap 2.11):+// given the D&D-style character sheet from GET /api/character, compute a view-model+// for the floating level/XP badge (current level, progress toward the next level) and+// detect XP gains / level-ups by diffing two successive character snapshots. No React+// imports so the math is unit-testable (mirrors cityTaskQueue.js).++// MIRRORS the server constant `XP_THRESHOLDS` in server/services/character.js — index i+// is the cumulative XP required to reach level i+1. Keep these two arrays in sync: if the+// server's level curve changes, update this copy (and the test) in the same change.+export const XP_THRESHOLDS = [+ 0, 300, 900, 2700, 6500, 14000, 23000, 34000, 48000, 64000,+ 85000, 100000, 120000, 140000, 165000, 195000, 225000, 265000, 305000, 355000,+];++export const MAX_LEVEL = XP_THRESHOLDS.length;++// Level for a given total XP, mirroring server `getLevelFromXP`. Clamps negative/NaN xp+// to level 1 so a missing/garbage value can't produce a negative or NaN level.+export function levelFromXP(xp) {+ const safeXp = Number.isFinite(xp) ? xp : 0;+ for (let i = XP_THRESHOLDS.length - 1; i >= 0; i--) {+ if (safeXp >= XP_THRESHOLDS[i]) return i + 1;+ }+ return 1;+}++// Derived view-model for the XP badge. Tolerates a missing/null character (returns a sane+// level-1 zero view). `progress` is 0..1 within the current level; at max level it pins to+// 1 with `atMax: true` and never produces NaN (no "next threshold" to divide by).+export function computeXpView(character) {+ const rawXp = character?.xp;+ const xp = Number.isFinite(rawXp) ? Math.max(0, rawXp) : 0;+ // Trust the server's stored level when present and consistent; otherwise derive it so a+ // legacy/absent level field still yields a correct badge.+ const level = Number.isFinite(character?.level) && character.level >= 1+ ? Math.min(MAX_LEVEL, Math.floor(character.level))+ : levelFromXP(xp);++ const atMax = level >= MAX_LEVEL;+ const levelFloor = XP_THRESHOLDS[level - 1] ?? 0;+ const nextThreshold = atMax ? null : XP_THRESHOLDS[level];++ const xpIntoLevel = Math.max(0, xp - levelFloor);+ const xpForNextLevel = atMax ? 0 : nextThreshold - levelFloor;+ const progress = atMax+ ? 1+ : (xpForNextLevel > 0 ? Math.min(1, Math.max(0, xpIntoLevel / xpForNextLevel)) : 0);++ return {+ xp,+ level,+ xpIntoLevel,+ xpForNextLevel,+ xpToNext: atMax ? 0 : Math.max(0, nextThreshold - xp),+ progress,+ atMax,+ hp: Number.isFinite(character?.hp) ? character.hp : null,+ maxHp: Number.isFinite(character?.maxHp) ? character.maxHp : null,+ };+}++// Compare two character snapshots to detect a fresh XP gain / level-up so the badge can+// fire a transient burst. Tolerates null on either side (first poll has no prev). `gained`+// is clamped to >= 0 so a manual XP reset (xp dropping) never reports a negative burst.+export function diffXp(prev, next) {+ const prevXp = Number.isFinite(prev?.xp) ? prev.xp : null;+ const nextXp = Number.isFinite(next?.xp) ? next.xp : null;+ const prevLevel = Number.isFinite(prev?.level) ? prev.level : null;+ const nextLevel = Number.isFinite(next?.level) ? next.level : null;++ // No comparable prior snapshot → treat as no change (first load shouldn't burst).+ if (prevXp == null || nextXp == null) {+ return { gained: 0, leveledUp: false };+ }++ const gained = Math.max(0, nextXp - prevXp);+ const leveledUp = prevLevel != null && nextLevel != null+ ? nextLevel > prevLevel+ : levelFromXP(nextXp) > levelFromXP(prevXp);++ return { gained, leveledUp: gained > 0 && leveledUp };+}diff --git a/client/src/utils/characterXp.test.js b/client/src/utils/characterXp.test.jsnew file mode 100644index 0000000000..abf6315d73--- /dev/null+++ b/client/src/utils/characterXp.test.js@@ -0,0 +1,134 @@+import { describe, it, expect } from 'vitest';+import {+ XP_THRESHOLDS,+ MAX_LEVEL,+ levelFromXP,+ computeXpView,+ diffXp,+} from './characterXp';++describe('levelFromXP', () => {+ it('maps XP to the right level at and above each threshold', () => {+ expect(levelFromXP(0)).toBe(1);+ expect(levelFromXP(299)).toBe(1);+ expect(levelFromXP(300)).toBe(2); // boundary is inclusive+ expect(levelFromXP(899)).toBe(2);+ expect(levelFromXP(900)).toBe(3);+ });++ it('caps at MAX_LEVEL for very high XP', () => {+ expect(levelFromXP(XP_THRESHOLDS[MAX_LEVEL - 1])).toBe(MAX_LEVEL);+ expect(levelFromXP(10_000_000)).toBe(MAX_LEVEL);+ });++ it('clamps negative / NaN XP to level 1', () => {+ expect(levelFromXP(-50)).toBe(1);+ expect(levelFromXP(NaN)).toBe(1);+ expect(levelFromXP(undefined)).toBe(1);+ });+});++describe('computeXpView', () => {+ it('computes progress mid-level', () => {+ // Level 2 spans [300, 900) — 600 XP wide. At 600 XP we're 300 into 600.+ const vm = computeXpView({ xp: 600, level: 2 });+ expect(vm.level).toBe(2);+ expect(vm.xpIntoLevel).toBe(300);+ expect(vm.xpForNextLevel).toBe(600);+ expect(vm.progress).toBeCloseTo(0.5);+ expect(vm.xpToNext).toBe(300);+ expect(vm.atMax).toBe(false);+ });++ it('is 0 progress exactly at a level floor (inclusive boundary)', () => {+ const vm = computeXpView({ xp: 300, level: 2 });+ expect(vm.level).toBe(2);+ expect(vm.xpIntoLevel).toBe(0);+ expect(vm.progress).toBe(0);+ });++ it('approaches 1 just below the next threshold without reaching it', () => {+ const vm = computeXpView({ xp: 899, level: 2 });+ expect(vm.progress).toBeGreaterThan(0.99);+ expect(vm.progress).toBeLessThan(1);+ });++ it('at max level: atMax true, progress pinned to 1, no NaN', () => {+ const maxXp = XP_THRESHOLDS[MAX_LEVEL - 1] + 50_000;+ const vm = computeXpView({ xp: maxXp, level: MAX_LEVEL });+ expect(vm.level).toBe(MAX_LEVEL);+ expect(vm.atMax).toBe(true);+ expect(vm.progress).toBe(1);+ expect(vm.xpForNextLevel).toBe(0);+ expect(vm.xpToNext).toBe(0);+ expect(Number.isNaN(vm.progress)).toBe(false);+ });++ it('returns a sane zero view for null / missing character', () => {+ for (const input of [null, undefined, {}]) {+ const vm = computeXpView(input);+ expect(vm.xp).toBe(0);+ expect(vm.level).toBe(1);+ expect(vm.progress).toBe(0);+ expect(vm.atMax).toBe(false);+ expect(vm.hp).toBeNull();+ expect(vm.maxHp).toBeNull();+ expect(Number.isNaN(vm.progress)).toBe(false);+ }+ });++ it('derives level from xp when the level field is absent / invalid', () => {+ const vm = computeXpView({ xp: 1000 }); // no level field → derive (level 3)+ expect(vm.level).toBe(3);+ });++ it('carries hp / maxHp through when present', () => {+ const vm = computeXpView({ xp: 0, level: 1, hp: 12, maxHp: 15 });+ expect(vm.hp).toBe(12);+ expect(vm.maxHp).toBe(15);+ });++ it('distinguishes absent xp (zero view) from a legitimate zero xp', () => {+ expect(computeXpView({}).xp).toBe(0);+ expect(computeXpView({ xp: 0, level: 1 }).xp).toBe(0);+ // both render as zero, but neither throws or NaNs+ expect(computeXpView({ xp: 0, level: 1 }).progress).toBe(0);+ });+});++describe('diffXp', () => {+ it('reports a gain when XP increased without a level change', () => {+ const d = diffXp({ xp: 100, level: 1 }, { xp: 250, level: 1 });+ expect(d.gained).toBe(150);+ expect(d.leveledUp).toBe(false);+ });++ it('reports no change when XP is identical', () => {+ const d = diffXp({ xp: 250, level: 2 }, { xp: 250, level: 2 });+ expect(d.gained).toBe(0);+ expect(d.leveledUp).toBe(false);+ });++ it('reports a level-up when XP crosses a threshold', () => {+ const d = diffXp({ xp: 250, level: 1 }, { xp: 400, level: 2 });+ expect(d.gained).toBe(150);+ expect(d.leveledUp).toBe(true);+ });++ it('infers level-up from XP when level fields are absent', () => {+ const d = diffXp({ xp: 250 }, { xp: 400 }); // crosses the 300 threshold+ expect(d.gained).toBe(150);+ expect(d.leveledUp).toBe(true);+ });++ it('does not burst on the first poll (no prior snapshot)', () => {+ expect(diffXp(null, { xp: 500, level: 2 })).toEqual({ gained: 0, leveledUp: false });+ expect(diffXp(undefined, { xp: 500 })).toEqual({ gained: 0, leveledUp: false });+ });++ it('never reports a negative gain when XP drops (reset)', () => {+ const d = diffXp({ xp: 5000, level: 4 }, { xp: 0, level: 1 });+ expect(d.gained).toBe(0);+ expect(d.leveledUp).toBe(false);+ });+});