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 AI Core landmark + live ai:status wiring to CyberCity (roadmap 2.1)
[._.]/ Adam Eivy99fa5b618a08
diff --git a/client/src/components/city/CityAiCore.jsx b/client/src/components/city/CityAiCore.jsxnew file mode 100644index 0000000000..e327ea4662--- /dev/null+++ b/client/src/components/city/CityAiCore.jsx@@ -0,0 +1,102 @@+import { useMemo, useRef } from 'react';+import { useFrame } from '@react-three/fiber';+import { Text } from '@react-three/drei';+import { PIXEL_FONT_URL } from './cityConstants';+import { computeAiCore } from '../../utils/cityAiCore';++// CyberCity's AI Core landmark (roadmap 2.1): a slender central spire above downtown from+// which all model activity radiates. The apex orb glows by the active model tier (cyan+// light → blue medium → violet heavy) and brightens with the number of in-flight calls;+// activity beams fan outward from the apex while AI work is happening, and a fast call+// still produces a brief flare. Idle, the core sits a dim slate. Driven by the live+// `ai:status` op count threaded through useCityData.+//+// `ai:status` carries no originating-building association, so beams radiate at fixed+// angles rather than targeting a specific building (see issue follow-up).+function Beam({ angle, length, apexY, color }) {+ const ref = useRef();+ const { position, rotation } = useMemo(() => {+ // A beam lies along +X then is rotated about Y to its angle; tilt slightly downward+ // so it reads as energy arcing out over the city rather than a flat ray.+ const tilt = -0.18;+ return {+ position: [Math.cos(angle) * (length / 2), apexY - Math.sin(-tilt) * (length / 2), Math.sin(angle) * (length / 2)],+ rotation: [0, -angle, tilt],+ };+ }, [angle, length, apexY]);++ useFrame(({ clock }) => {+ if (!ref.current) return;+ // A pulse travels the beam: opacity breathes out of phase per angle so the beams+ // shimmer rather than blink in unison.+ const t = clock.getElapsedTime() * 3 + angle * 2;+ ref.current.material.opacity = 0.25 + ((Math.sin(t) + 1) / 2) * 0.5;+ });++ return (+ <mesh ref={ref} position={position} rotation={rotation}>+ <boxGeometry args={[length, 0.18, 0.18]} />+ <meshStandardMaterial color={color} emissive={color} emissiveIntensity={1} transparent opacity={0.4} toneMapped={false} depthWrite={false} />+ </mesh>+ );+}++export default function CityAiCore({ aiActivity, settings }) {+ const core = useMemo(+ () => computeAiCore(aiActivity?.ops, aiActivity?.lastStartTs ?? 0),+ [aiActivity],+ );+ const apexRef = useRef();++ const animate = (settings?.particleDensity ?? 1) >= 0.5;++ // Even angular spread for however many beams are active right now.+ const beams = useMemo(() => {+ const out = [];+ for (let i = 0; i < core.beamCount; i++) {+ out.push({ angle: (i / Math.max(core.beamCount, 1)) * Math.PI * 2, key: i });+ }+ return out;+ }, [core.beamCount]);++ useFrame(({ clock }) => {+ if (!animate || !apexRef.current) return;+ // Busy core pulses faster; a flare spikes it; idle breathes slowly.+ const speed = core.busy ? 2.4 : core.flaring ? 3.2 : 0.7;+ const pulse = 0.5 + ((Math.sin(clock.getElapsedTime() * speed) + 1) / 2) * 0.6;+ apexRef.current.material.emissiveIntensity = pulse * (core.intensity + 0.3);+ });++ const { position, height, apexY, color } = core;+ const beamLength = 16;++ return (+ <group position={position}>+ {/* Slender spire body — tapered so it reads as a tower, not a column */}+ <mesh position={[0, height / 2, 0]}>+ <cylinderGeometry args={[0.5, 1.4, height, 8]} />+ <meshStandardMaterial color="#0a0f1c" emissive={color} emissiveIntensity={0.1 + core.intensity * 0.15} metalness={0.7} roughness={0.4} />+ </mesh>+ {/* Apex orb — the live AI-activity indicator */}+ <mesh ref={apexRef} position={[0, apexY, 0]}>+ <icosahedronGeometry args={[1.6, 1]} />+ <meshStandardMaterial color={color} emissive={color} emissiveIntensity={core.intensity} toneMapped={false} />+ </mesh>+ {/* Activity beams fan out from the apex while AI work is in flight */}+ <group position={[0, apexY, 0]}>+ {beams.map(b => (+ <Beam key={b.key} angle={b.angle} length={beamLength} apexY={0} color={color} />+ ))}+ </group>+ {/* Label above the apex */}+ <Text position={[0, apexY + 2.6, 0]} fontSize={1.4} color={color} anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={20}>+ AI CORE+ </Text>+ {core.busy && (+ <Text position={[0, apexY + 1.5, 0]} fontSize={0.85} color="#94a3b8" anchorX="center" anchorY="middle" font={PIXEL_FONT_URL} maxWidth={20}>+ {`${core.activeCount} ACTIVE`}+ </Text>+ )}+ </group>+ );+}diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsxindex 52e8903572..d00db92c60 100644--- a/client/src/components/city/CityScene.jsx+++ b/client/src/components/city/CityScene.jsx@@ -19,6 +19,7 @@ import CityBackupVault from './CityBackupVault';import CityTaskQueue from './CityTaskQueue';import CityHealthTower from './CityHealthTower';import CityVoiceMarker from './CityVoiceMarker';+import CityAiCore from './CityAiCore';import CityDataRain from './CityDataRain';import CityNeonSigns from './CityNeonSigns';import CityEmbers from './CityEmbers';@@ -29,7 +30,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, healthMetrics, voiceState, productivityData, settings, playSfx, keysRef, dimmedAppIds }) {+export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, settings, playSfx, keysRef, dimmedAppIds }) {const [positions, setPositions] = useState(null);const [proximityApp, setProximityApp] = useState(null);const [transitioning, setTransitioning] = useState(false);@@ -82,6 +83,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,<CityTaskQueue cosTasks={cosTasks} settings={settings} /><CityHealthTower healthMetrics={healthMetrics} settings={settings} /><CityVoiceMarker voiceState={voiceState} settings={settings} />+ <CityAiCore aiActivity={aiActivity} settings={settings} /><CityGround settings={settings} /><BuildingClusterdiff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.jsindex e08e21fac4..9fcb53ba55 100644--- a/client/src/hooks/useCityData.js+++ b/client/src/hooks/useCityData.js@@ -3,6 +3,7 @@ import * as api from '../services/api';import socket from '../services/socket';import { useAutoRefetch } from './useAutoRefetch';import { METRICS as HEALTH_TOWER_METRICS } from '../utils/cityHealthTower';+import { applyAiStatusEvent } from '../utils/cityAiCore';// Metric keys the vitals-tower landmark renders — fetched as the latest-value snapshot.const HEALTH_METRIC_KEYS = HEALTH_TOWER_METRICS.map(m => m.key);@@ -29,6 +30,10 @@ export const useCityData = () => {// `live` driven by the per-socket voice:* events (idle | listening | dictating | error).const [voiceState, setVoiceState] = useState(null);const [character, setCharacter] = useState(null);+ // AI Core landmark: in-flight `ai:status` ops keyed by id + the last op-start timestamp+ // (for the flare). Purely event-driven — there's no GET for in-flight ops, so it starts+ // empty and the socket handler below maintains it.+ const [aiActivity, setAiActivity] = useState({ ops: {}, lastStartTs: 0 });const [loading, setLoading] = useState(true);const logIdRef = useRef(0);@@ -235,6 +240,16 @@ export const useCityData = () => {socket.on('voice:error', handleVoiceError);socket.on('voice:idle', handleVoiceIdle);+ // AI Core landmark: every LLM/model call broadcasts phase-tagged `ai:status` events+ // (start → model:loading → model:loaded → complete/error) globally. Track the in-flight+ // set so the central spire glows/beams with live model activity; the pure reducer adds+ // on non-terminal phases, drops on complete/error, and prunes stale ops.+ const handleAiStatus = (event) => setAiActivity(prev => ({+ ops: applyAiStatusEvent(prev.ops, event),+ lastStartTs: event?.phase === 'start' ? Date.now() : prev.lastStartTs,+ }));+ socket.on('ai:status', handleAiStatus);+// Subscribe but do NOT unsubscribe on cleanup. The cos:* and notifications:*// namespaces are shared (useNotifications in Layout, useAgentFeedbackToast).// Server uses a per-socket Set, so unsubscribing here would yank the@@ -256,6 +271,7 @@ export const useCityData = () => {socket.off('voice:dictation', handleVoiceDictation);socket.off('voice:error', handleVoiceError);socket.off('voice:idle', handleVoiceIdle);+ socket.off('ai:status', handleAiStatus);};}, [fetchAll, fetchApps, fetchBackup]);@@ -275,6 +291,7 @@ export const useCityData = () => {healthMetrics,voiceState,character,+ aiActivity,loading,connected: socket.connected,};diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsxindex d697e6eee7..404fa6de43 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, healthMetrics, voiceState, character, loading, connected } = useCityData();+ const { apps, cosAgents, cosStatus, eventLogs, agentMap, reviewCounts, instances, systemHealth, notificationCounts, backupStatus, cosTasks, healthMetrics, voiceState, character, aiActivity, loading, connected } = useCityData();const { settings, updateSetting } = useCitySettingsContext();const { playSfx } = useCityAudio(settings);const navigate = useNavigate();@@ -110,6 +110,7 @@ function CyberCityInner() {cosTasks={cosTasks}healthMetrics={healthMetrics}voiceState={voiceState}+ aiActivity={aiActivity}productivityData={productivityData}settings={settings}playSfx={playSfx}diff --git a/client/src/utils/cityAiCore.js b/client/src/utils/cityAiCore.jsnew file mode 100644index 0000000000..bceb99871d--- /dev/null+++ b/client/src/utils/cityAiCore.js@@ -0,0 +1,97 @@+// Pure, deterministic helpers for CyberCity's AI Core landmark (roadmap 2.1): a central+// spire above downtown from which all model activity radiates. The server broadcasts+// phase-tagged `ai:status` events (start → model:loading → model:loaded → complete/error)+// for every LLM/model call; this module tracks the in-flight set and derives the core's+// glow/beam state. No three.js / React imports so the logic is unit-testable (mirrors+// cityBackupVault.js).+//+// Note: `ai:status` carries no agent/building association, so beams radiate generically+// from the core rather than targeting the originating building — see issue note. Model+// tier is a best-effort heuristic from the model name (the event has no explicit tier).++export const AI_CORE = {+ position: [0, 0, 0], // city center — the spire rises above the building grid+ height: 34, // tall enough to clear downtown and read as the central landmark+ apexY: 34, // beams/glow originate from the apex+ maxBeams: 6, // visible activity beams cap+ // How long an op with no terminal (complete/error) event lingers before being pruned,+ // so a dropped/never-finished call can't pin the core "busy" forever.+ opMaxAgeMs: 60_000,+ // How long after the last op start the core keeps its "just fired" flare.+ flareMs: 1200,+};++const TIER_COLORS = {+ light: '#22d3ee', // cyan — fast/cheap models+ medium: '#3b82f6', // port-accent — standard models+ heavy: '#a855f7', // violet — large/expensive models+ idle: '#334155', // slate — core at rest+};++// Phases that mean the op is no longer in flight.+const TERMINAL_PHASES = new Set(['complete', 'error']);++// Best-effort model-tier classification from the model name. The `ai:status` event has no+// explicit tier, so we pattern-match common families. Unknown models fall to `medium`.+export function modelTier(model) {+ if (!model || typeof model !== 'string') return 'medium';+ const m = model.toLowerCase();+ if (/\b(opus|70b|72b|405b|large|heavy|ultra|max)\b/.test(m) || /:(70|72|405)b/.test(m)) return 'heavy';+ if (/(haiku|mini|flash|lite|light|tiny|small|1\.5b|3b|7b|8b|9b|nano|gemma)/.test(m)) return 'light';+ return 'medium';+}++export function tierColor(tier) {+ return TIER_COLORS[tier] || TIER_COLORS.medium;+}++// Rank tiers so the core can pick the "loudest" active tier when several ops overlap.+const TIER_RANK = { light: 1, medium: 2, heavy: 3 };++// Apply one `ai:status` event to the in-flight op map (plain object keyed by op id),+// returning a NEW object. Terminal phases remove the op; every other phase adds/updates+// it with the event's model + a last-seen timestamp. Entries older than `opMaxAgeMs` are+// pruned so a never-completed op can't wedge the core busy. Pure — `now` is injected.+export function applyAiStatusEvent(ops, event, now = Date.now()) {+ const next = {};+ // Prune stale ops first.+ for (const [id, op] of Object.entries(ops || {})) {+ if (now - op.ts <= AI_CORE.opMaxAgeMs) next[id] = op;+ }+ const id = event?.id;+ if (!id) return next;+ if (TERMINAL_PHASES.has(event.phase)) {+ delete next[id];+ return next;+ }+ next[id] = { id, model: event.model || null, tier: modelTier(event.model), ts: now };+ return next;+}++// Derive the core's view-model from the in-flight op map. `lastStartTs` (the timestamp of+// the most recent op start) drives a brief flare; `now` is injected for determinism.+export function computeAiCore(ops, lastStartTs = 0, now = Date.now()) {+ const active = Object.values(ops || {}).filter(op => now - op.ts <= AI_CORE.opMaxAgeMs);+ const activeCount = active.length;+ const busy = activeCount > 0;+ // Loudest active tier wins the color; idle when nothing is in flight.+ const tier = busy+ ? active.reduce((hi, op) => (TIER_RANK[op.tier] > TIER_RANK[hi] ? op.tier : hi), 'light')+ : 'idle';+ const flaring = lastStartTs > 0 && now - lastStartTs <= AI_CORE.flareMs;+ return {+ position: AI_CORE.position,+ height: AI_CORE.height,+ apexY: AI_CORE.apexY,+ activeCount,+ busy,+ tier,+ color: busy ? tierColor(tier) : TIER_COLORS.idle,+ // Beam count tracks concurrency, capped; at least one beam while flaring even if the+ // op already cleared (so a fast call still produces a visible pulse).+ beamCount: Math.min(Math.max(activeCount, flaring ? 1 : 0), AI_CORE.maxBeams),+ flaring,+ // Idle core breathes faintly; busy core glows; a flare spikes intensity briefly.+ intensity: busy ? 0.7 + Math.min(activeCount, 4) * 0.075 : flaring ? 0.6 : 0.25,+ };+}diff --git a/client/src/utils/cityAiCore.test.js b/client/src/utils/cityAiCore.test.jsnew file mode 100644index 0000000000..b3539eca3b--- /dev/null+++ b/client/src/utils/cityAiCore.test.js@@ -0,0 +1,142 @@+import { describe, it, expect } from 'vitest';+import {+ AI_CORE,+ modelTier,+ tierColor,+ applyAiStatusEvent,+ computeAiCore,+} from './cityAiCore';++const NOW = 1_000_000;+const ev = (id, phase, model, extra = {}) => ({ id, phase, model, ...extra });++describe('modelTier', () => {+ it('classifies heavy families', () => {+ expect(modelTier('claude-opus-4-8')).toBe('heavy');+ expect(modelTier('llama-3.1-70b')).toBe('heavy');+ expect(modelTier('qwen2.5:72b')).toBe('heavy');+ });+ it('classifies light families', () => {+ expect(modelTier('claude-haiku-4-5')).toBe('light');+ expect(modelTier('gpt-4o-mini')).toBe('light');+ expect(modelTier('gemini-1.5-flash')).toBe('light');+ expect(modelTier('llama-3-8b')).toBe('light');+ });+ it('defaults unknown / missing to medium', () => {+ expect(modelTier('some-unknown-model')).toBe('medium');+ expect(modelTier(undefined)).toBe('medium');+ expect(modelTier(null)).toBe('medium');+ expect(modelTier(42)).toBe('medium');+ });+});++describe('tierColor', () => {+ it('maps tiers to distinct colors and falls back to medium', () => {+ expect(tierColor('light')).toBe('#22d3ee');+ expect(tierColor('medium')).toBe('#3b82f6');+ expect(tierColor('heavy')).toBe('#a855f7');+ expect(tierColor('bogus')).toBe(tierColor('medium'));+ });+});++describe('applyAiStatusEvent', () => {+ it('adds an op on a non-terminal phase', () => {+ const ops = applyAiStatusEvent({}, ev('a', 'start', 'gpt-4o-mini'), NOW);+ expect(Object.keys(ops)).toEqual(['a']);+ expect(ops.a.tier).toBe('light');+ expect(ops.a.ts).toBe(NOW);+ });++ it('keeps the op across intermediate phases, refreshing its timestamp', () => {+ let ops = applyAiStatusEvent({}, ev('a', 'start', 'claude-opus-4-8'), NOW);+ ops = applyAiStatusEvent(ops, ev('a', 'model:loading', 'claude-opus-4-8'), NOW + 500);+ expect(Object.keys(ops)).toEqual(['a']);+ expect(ops.a.ts).toBe(NOW + 500);+ expect(ops.a.tier).toBe('heavy');+ });++ it('removes the op on complete and on error', () => {+ let ops = applyAiStatusEvent({}, ev('a', 'start', 'm'), NOW);+ ops = applyAiStatusEvent(ops, ev('b', 'start', 'm'), NOW);+ ops = applyAiStatusEvent(ops, ev('a', 'complete', 'm'), NOW + 1);+ expect(Object.keys(ops)).toEqual(['b']);+ ops = applyAiStatusEvent(ops, ev('b', 'error', 'm'), NOW + 2);+ expect(Object.keys(ops)).toEqual([]);+ });++ it('prunes ops older than opMaxAgeMs', () => {+ let ops = applyAiStatusEvent({}, ev('old', 'start', 'm'), NOW);+ // A later event prunes the stale 'old' op while adding the new one.+ ops = applyAiStatusEvent(ops, ev('new', 'start', 'm'), NOW + AI_CORE.opMaxAgeMs + 1);+ expect(Object.keys(ops)).toEqual(['new']);+ });++ it('ignores an event with no id but still prunes', () => {+ let ops = applyAiStatusEvent({}, ev('old', 'start', 'm'), NOW);+ ops = applyAiStatusEvent(ops, { phase: 'start', model: 'm' }, NOW + AI_CORE.opMaxAgeMs + 1);+ expect(Object.keys(ops)).toEqual([]);+ });++ it('returns a new object (no mutation of the input)', () => {+ const input = {};+ const out = applyAiStatusEvent(input, ev('a', 'start', 'm'), NOW);+ expect(out).not.toBe(input);+ expect(Object.keys(input)).toEqual([]);+ });+});++describe('computeAiCore', () => {+ it('is idle with no ops', () => {+ const vm = computeAiCore({}, 0, NOW);+ expect(vm.busy).toBe(false);+ expect(vm.activeCount).toBe(0);+ expect(vm.tier).toBe('idle');+ expect(vm.color).toBe('#334155');+ expect(vm.beamCount).toBe(0);+ expect(vm.intensity).toBe(0.25);+ expect(vm.position).toEqual(AI_CORE.position);+ });++ it('glows with the loudest active tier when ops overlap', () => {+ const ops = {+ a: { id: 'a', tier: 'light', ts: NOW },+ b: { id: 'b', tier: 'heavy', ts: NOW },+ c: { id: 'c', tier: 'medium', ts: NOW },+ };+ const vm = computeAiCore(ops, NOW, NOW);+ expect(vm.busy).toBe(true);+ expect(vm.activeCount).toBe(3);+ expect(vm.tier).toBe('heavy');+ expect(vm.color).toBe('#a855f7');+ expect(vm.beamCount).toBe(3);+ });++ it('caps beam count at maxBeams', () => {+ const ops = {};+ for (let i = 0; i < AI_CORE.maxBeams + 5; i++) ops[i] = { id: String(i), tier: 'medium', ts: NOW };+ const vm = computeAiCore(ops, NOW, NOW);+ expect(vm.activeCount).toBe(AI_CORE.maxBeams + 5);+ expect(vm.beamCount).toBe(AI_CORE.maxBeams);+ });++ it('ignores stale ops past opMaxAgeMs', () => {+ const ops = { a: { id: 'a', tier: 'heavy', ts: NOW } };+ const vm = computeAiCore(ops, 0, NOW + AI_CORE.opMaxAgeMs + 1);+ expect(vm.busy).toBe(false);+ expect(vm.activeCount).toBe(0);+ });++ it('flares briefly after a start even once the op has cleared', () => {+ const vm = computeAiCore({}, NOW, NOW + 200);+ expect(vm.busy).toBe(false);+ expect(vm.flaring).toBe(true);+ expect(vm.beamCount).toBe(1); // a fast call still pulses+ expect(vm.intensity).toBe(0.6);+ });++ it('stops flaring after flareMs', () => {+ const vm = computeAiCore({}, NOW, NOW + AI_CORE.flareMs + 1);+ expect(vm.flaring).toBe(false);+ expect(vm.beamCount).toBe(0);+ });+});