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: improve OpenWorld gameplay feedback and performance
[._.]/ Adam Eivy17cb961ad5df
diff --git a/client/src/components/openworld/OpenWorldHud.jsx b/client/src/components/openworld/OpenWorldHud.jsxindex b93ff25ee7..3212b4eb54 100644--- a/client/src/components/openworld/OpenWorldHud.jsx+++ b/client/src/components/openworld/OpenWorldHud.jsx@@ -11,7 +11,7 @@ import OpenWorldMiniMap from './OpenWorldMiniMap';import OpenWorldHudCompact from './OpenWorldHudCompact';import OpenWorldInteractionPrompt from './OpenWorldInteractionPrompt';import OpenWorldSpeedometer from './OpenWorldSpeedometer';-import { HealthBar, getHealthSentinel } from './openWorldHudBits';+import { HealthBar, getHealthSentinel, metricColor } from './openWorldHudBits';import useOpenWorldViewport from '../../hooks/useOpenWorldViewport';import { formatClockTime } from '../../utils/formatters';@@ -60,6 +60,17 @@ function Crosshair() {);}+function SystemMetric({ label, value }) {+ return (+ <div className="flex items-baseline justify-between gap-1">+ <span className="font-pixel text-[8px] tracking-[0.12em] text-[rgb(var(--port-text-muted))]">{label}</span>+ <span className={`font-pixel text-[9px] tracking-wide ${metricColor(value)}`}>+ {value != null ? `${value}%` : '—'}+ </span>+ </div>+ );+}+// The HUD floats over a keyboard-driven world: a pointer click must not leave// focus parked on the button, or Space stops jumping and starts re-pressing it.function HudAction({ icon: Icon, label, hint, active, primary = false, onClick }) {@@ -202,6 +213,14 @@ export default function OpenWorldHud({<div className="mt-2"><HealthBar value={activeApps} max={totalApps} color="rgb(var(--port-accent))" /></div>+ <div+ className="mt-2 grid grid-cols-3 gap-3 border-t border-[rgb(var(--port-accent)/.14)] pt-2"+ aria-label="System resource usage"+ >+ <SystemMetric label="CPU" value={cpuPct} />+ <SystemMetric label="MEM" value={memPct} />+ <SystemMetric label="DISK" value={diskPct} />+ </div><div className="mt-2 flex items-center justify-between gap-3 font-pixel text-[8px] tracking-[0.12em] text-[rgb(var(--port-text-muted))]"><span className="truncate">{activeRegion?.label || 'DOWNTOWN'}</span><span className={sentinel.text}>{sentinel.label}</span>@@ -330,6 +349,9 @@ export default function OpenWorldHud({onOpenDestination={onOpenDestination}onAttentionItem={onAttentionItem}proximityTarget={proximityTarget}+ playerPose={playerPose}+ collectedCount={collectedCount}+ totalShards={totalShards}/>)}diff --git a/client/src/components/openworld/OpenWorldHud.test.jsx b/client/src/components/openworld/OpenWorldHud.test.jsxnew file mode 100644index 0000000000..2abef26381--- /dev/null+++ b/client/src/components/openworld/OpenWorldHud.test.jsx@@ -0,0 +1,57 @@+import { describe, expect, it, vi } from 'vitest';+import { render, screen, within } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++vi.mock('../../hooks/useOpenWorldViewport', () => ({+ default: () => ({ isDesktop: true }),+}));+vi.mock('./OpenWorldIntelPane', () => ({ default: () => null }));+vi.mock('./OpenWorldFocusPanel', () => ({ default: () => null }));+vi.mock('./OpenWorldAgentBar', () => ({ default: () => null }));+vi.mock('./OpenWorldXpBadge', () => ({ default: () => null }));+vi.mock('./OpenWorldMiniMap', () => ({ default: () => null }));++import OpenWorldHud from './OpenWorldHud';++const renderHud = (overrides = {}) => render(+ <MemoryRouter initialEntries={['/openworld']}>+ <OpenWorldHud+ cosStatus={{ running: false }}+ cosAgents={[]}+ agentMap={new Map()}+ eventLogs={[]}+ connected+ apps={[{ id: 'app-1', name: 'Example App', overallStatus: 'online' }]}+ reviewCounts={{ total: 0, alert: 0 }}+ instances={{ peers: [] }}+ productivityData={null}+ systemHealth={{+ overallHealth: 'warning',+ system: {+ cpu: { usagePercent: 42 },+ memory: { usagePercent: 76 },+ disk: { usagePercent: 91 },+ },+ }}+ notificationCounts={{ unread: 0 }}+ character={null}+ filter={null}+ explorationMode={false}+ {...overrides}+ />+ </MemoryRouter>,+);++describe('OpenWorldHud', () => {+ it('keeps CPU, memory, and disk pressure visible in the desktop cockpit', () => {+ renderHud();++ const metrics = screen.getByLabelText('System resource usage');+ expect(within(metrics).getByText('CPU')).toBeInTheDocument();+ expect(within(metrics).getByText('42%')).toBeInTheDocument();+ expect(within(metrics).getByText('MEM')).toBeInTheDocument();+ expect(within(metrics).getByText('76%')).toBeInTheDocument();+ expect(within(metrics).getByText('DISK')).toBeInTheDocument();+ expect(within(metrics).getByText('91%')).toBeInTheDocument();+ });+});diff --git a/client/src/components/openworld/OpenWorldHudCompact.jsx b/client/src/components/openworld/OpenWorldHudCompact.jsxindex 58f4c16234..1084c89a90 100644--- a/client/src/components/openworld/OpenWorldHudCompact.jsx+++ b/client/src/components/openworld/OpenWorldHudCompact.jsx@@ -91,6 +91,9 @@ export default function OpenWorldHudCompact({onCloseFocus,onFocusInWorld,proximityTarget,+ playerPose,+ collectedCount = 0,+ totalShards = 0,}) {const navigate = useNavigate();const location = useLocation();@@ -104,6 +107,7 @@ export default function OpenWorldHudCompact({);const criticalCount = items.filter(i => i.severity === 'critical').length;const hasApps = (apps || []).length > 0;+ const speedKmh = Math.round(Math.abs(playerPose?.speed || 0) * 3.6);// No usable level → the birth-date CTA distinguishes a genuinely unset date ("set") from a// present-but-unusable one ("fix" — invalid/future/unreadable) so we don't tell the user to// set a date they already entered (#2757). Null when a real level exists.@@ -154,7 +158,9 @@ export default function OpenWorldHudCompact({<buttontype="button"onClick={() => togglePane('vitals')}- aria-label="Time and system vitals"+ aria-label={explorationMode+ ? `Time and system vitals, ${speedKmh} kilometers per hour, ${collectedCount} of ${totalShards} shards collected`+ : 'Time and system vitals'}aria-pressed={activePane === 'vitals'}className="openworld-hud-chip openworld-hud-action relative px-3 min-h-[44px] flex items-center gap-2">@@ -163,6 +169,16 @@ export default function OpenWorldHudCompact({{formatClockTime(time, { seconds: false })}</span><span className="font-pixel text-[9px] text-cyan-500 tracking-wide">{vitals.activeApps}/{vitals.totalApps}</span>+ {explorationMode && (+ <>+ <span className="h-4 w-px bg-cyan-500/20" aria-hidden="true" />+ <span className="font-pixel text-[11px] text-cyan-300 tracking-wide">{speedKmh}</span>+ <span className="font-pixel text-[7px] text-gray-500 tracking-wide">KM/H</span>+ <span className="font-pixel text-[8px] text-cyan-400 tracking-wide">+ ⯁ {collectedCount}/{totalShards}+ </span>+ </>+ )}</button></div>diff --git a/client/src/components/openworld/OpenWorldHudCompact.test.jsx b/client/src/components/openworld/OpenWorldHudCompact.test.jsxindex 051c4304af..362c3a6de4 100644--- a/client/src/components/openworld/OpenWorldHudCompact.test.jsx+++ b/client/src/components/openworld/OpenWorldHudCompact.test.jsx@@ -95,6 +95,19 @@ describe('OpenWorldHudCompact', () => {expect(screen.getByTestId('openworld-interaction-prompt')).toHaveTextContent('ACTION');});+ it('shows live speed and collectible progress while free roaming', () => {+ renderCompact('', {+ explorationMode: true,+ playerPose: { speed: 10 },+ collectedCount: 4,+ totalShards: 12,+ });++ expect(screen.getByText('36')).toBeInTheDocument();+ expect(screen.getByText('KM/H')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /36 kilometers per hour, 4 of 12 shards collected/i })).toHaveTextContent('4/12');+ });+it('restores the open pane from the URL on load', () => {renderCompact('?openWorldPane=vitals');expect(screen.getByText('SYSTEM VITALS')).toBeInTheDocument();diff --git a/client/src/components/openworld/OpenWorldMobileControls.jsx b/client/src/components/openworld/OpenWorldMobileControls.jsxindex 66bfd36194..d81be9cb61 100644--- a/client/src/components/openworld/OpenWorldMobileControls.jsx+++ b/client/src/components/openworld/OpenWorldMobileControls.jsx@@ -31,6 +31,7 @@ function HoldButton({ label, hint, icon: Icon, onStart, onEnd, wide = false }) {}}onPointerUp={finish}onPointerCancel={finish}+ onLostPointerCapture={finish}onContextMenu={(event) => event.preventDefault()}><Icon size={18} strokeWidth={1.9} aria-hidden="true" />@@ -47,6 +48,7 @@ export default function OpenWorldMobileControls({onToggleExploration,}) {const joystickRef = useRef(null);+ const joystickPointerRef = useRef(null);const lookPointRef = useRef(null);const [stick, setStick] = useState({ x: 0, y: 0 });@@ -75,7 +77,9 @@ export default function OpenWorldMobileControls({}}, [mobileInputRef]);- const resetMovement = useCallback(() => {+ const resetMovement = useCallback((event) => {+ if (event && joystickPointerRef.current !== event.pointerId) return;+ joystickPointerRef.current = null;setStick({ x: 0, y: 0 });if (mobileInputRef.current) {mobileInputRef.current.moveX = 0;@@ -85,25 +89,34 @@ export default function OpenWorldMobileControls({const handleJoystickDown = (event) => {event.preventDefault();+ if (joystickPointerRef.current !== null) return;+ joystickPointerRef.current = event.pointerId;event.currentTarget.setPointerCapture?.(event.pointerId);writeMovement(event.clientX, event.clientY);};+ const handleJoystickMove = (event) => {+ if (joystickPointerRef.current !== event.pointerId) return;+ writeMovement(event.clientX, event.clientY);+ };+const handleLookDown = (event) => {event.preventDefault();+ if (lookPointRef.current) return;event.currentTarget.setPointerCapture?.(event.pointerId);- lookPointRef.current = { x: event.clientX, y: event.clientY };+ lookPointRef.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY };};const handleLookMove = (event) => {const previous = lookPointRef.current;- if (!previous || !mobileInputRef.current) return;+ if (!previous || previous.pointerId !== event.pointerId || !mobileInputRef.current) return;mobileInputRef.current.lookDeltaX += event.clientX - previous.x;mobileInputRef.current.lookDeltaY += event.clientY - previous.y;- lookPointRef.current = { x: event.clientX, y: event.clientY };+ lookPointRef.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY };};- const handleLookEnd = () => {+ const handleLookEnd = (event) => {+ if (event && lookPointRef.current?.pointerId !== event.pointerId) return;lookPointRef.current = null;};@@ -127,6 +140,7 @@ export default function OpenWorldMobileControls({onPointerMove={handleLookMove}onPointerUp={handleLookEnd}onPointerCancel={handleLookEnd}+ onLostPointerCapture={handleLookEnd}onContextMenu={(event) => event.preventDefault()}><span className="openworld-mobile-look-hint">DRAG TO LOOK</span>@@ -138,9 +152,10 @@ export default function OpenWorldMobileControls({role="group"aria-label="Movement joystick"onPointerDown={handleJoystickDown}- onPointerMove={(event) => writeMovement(event.clientX, event.clientY)}+ onPointerMove={handleJoystickMove}onPointerUp={resetMovement}onPointerCancel={resetMovement}+ onLostPointerCapture={resetMovement}onContextMenu={(event) => event.preventDefault()}><spandiff --git a/client/src/components/openworld/OpenWorldMobileControls.test.jsx b/client/src/components/openworld/OpenWorldMobileControls.test.jsxindex dffd68c6ee..c3a50402f7 100644--- a/client/src/components/openworld/OpenWorldMobileControls.test.jsx+++ b/client/src/components/openworld/OpenWorldMobileControls.test.jsx@@ -58,6 +58,16 @@ describe('OpenWorldMobileControls', () => {expect(mobileInputRef.current.jump).toBe(false);});+ it('clears a held action if pointer capture is lost', () => {+ const { mobileInputRef } = renderControls();+ const boost = screen.getByRole('button', { name: 'BOOST' });++ fireEvent.pointerDown(boost, { pointerId: 12 });+ expect(mobileInputRef.current.boost).toBe(true);+ fireEvent.lostPointerCapture(boost, { pointerId: 12 });+ expect(mobileInputRef.current.boost).toBe(false);+ });+it('maps the virtual joystick to normalized drive input', () => {const { mobileInputRef } = renderControls();const joystick = screen.getByRole('group', { name: 'Movement joystick' });@@ -82,6 +92,52 @@ describe('OpenWorldMobileControls', () => {expect(mobileInputRef.current.moveY).toBe(0);});+ it('does not steer from pointer hover without an active drag', () => {+ const { mobileInputRef } = renderControls();+ const joystick = screen.getByRole('group', { name: 'Movement joystick' });+ vi.spyOn(joystick, 'getBoundingClientRect').mockReturnValue({+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ right: 100,+ bottom: 100,+ x: 0,+ y: 0,+ toJSON: () => {},+ });++ fireEvent.pointerMove(joystick, { pointerId: 9, clientX: 75, clientY: 25 });++ expect(mobileInputRef.current.moveX).toBe(0);+ expect(mobileInputRef.current.moveY).toBe(0);+ });++ it('ignores a second pointer and clears movement if capture is lost', () => {+ const { mobileInputRef } = renderControls();+ const joystick = screen.getByRole('group', { name: 'Movement joystick' });+ vi.spyOn(joystick, 'getBoundingClientRect').mockReturnValue({+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ right: 100,+ bottom: 100,+ x: 0,+ y: 0,+ toJSON: () => {},+ });++ fireEvent.pointerDown(joystick, { pointerId: 10, clientX: 75, clientY: 25 });+ const firstX = mobileInputRef.current.moveX;+ fireEvent.pointerMove(joystick, { pointerId: 11, clientX: 25, clientY: 75 });+ expect(mobileInputRef.current.moveX).toBe(firstX);++ fireEvent.lostPointerCapture(joystick, { pointerId: 10 });+ expect(mobileInputRef.current.moveX).toBe(0);+ expect(mobileInputRef.current.moveY).toBe(0);+ });+it('accumulates drag-to-look deltas for the player rig', () => {const { mobileInputRef } = renderControls();const lookZone = screen.getByRole('group', { name: 'Drag to look around' });diff --git a/client/src/components/openworld/OpenWorldScene.jsx b/client/src/components/openworld/OpenWorldScene.jsxindex fb0b814c28..3fca738870 100644--- a/client/src/components/openworld/OpenWorldScene.jsx+++ b/client/src/components/openworld/OpenWorldScene.jsx@@ -1,4 +1,4 @@-import { useState, useCallback, useRef, useEffect, useMemo, Suspense } from 'react';+import { memo, useState, useCallback, useRef, useEffect, useMemo, Suspense } from 'react';import * as THREE from 'three';import { Canvas } from '@react-three/fiber';import { OrbitControls } from '@react-three/drei';@@ -65,7 +65,7 @@ import { useVisibilityEvent } from '../../hooks/useVisibilityEvent';const STARTUP_PARTICLE_DENSITY = 0.49;-export default function OpenWorldScene({+function OpenWorldScene({apps,agentMap,onBuildingClick,@@ -548,3 +548,8 @@ export default function OpenWorldScene({</div>);}++// HUD telemetry (rover pose, clock, socket logs) updates much more often than scene+// inputs. Keep those parent renders out of the expensive r3f tree; React still+// re-enters the scene whenever any actual scene prop changes.+export default memo(OpenWorldScene);diff --git a/client/src/components/openworld/PlayerController.jsx b/client/src/components/openworld/PlayerController.jsxindex 07b2d02422..916d1a2c69 100644--- a/client/src/components/openworld/PlayerController.jsx+++ b/client/src/components/openworld/PlayerController.jsx@@ -27,6 +27,7 @@ const BUILDING_FLYOVER_HEIGHT = 12; // above this the player clears rooftops, soconst AIRBORNE_HEIGHT = EYE_HEIGHT + 0.6; // above this the avatar reads as flying (hover state)const MOUSE_SENSITIVITY = 0.002;const PITCH_LIMIT = Math.PI / 2 - 0.02;+const POSE_REPORT_INTERVAL_SECONDS = 0.1;// Frame-loop scratch vectors (module scope — no per-frame allocation in useFrame).const _forward = new THREE.Vector3();@@ -128,7 +129,7 @@ export default function PlayerController({const lastBoostPadRef = useRef(null);const boostOverrideTimerRef = useRef(0);const localCollectedSetRef = useRef(new Set(collectedShardIds));- const poseTickRef = useRef(0);+ const poseReportElapsedRef = useRef(POSE_REPORT_INTERVAL_SECONDS);const lastSpawnRef = useRef(null);const pointerLockedRef = useRef(false);// Camera boom zoom: `boomZoomTargetRef` is the player's chosen multiplier, `boomZoomRef`@@ -193,6 +194,9 @@ export default function PlayerController({rig.skid = 0;lastSpawnRef.current = rig.position.clone();}+ // Publish the spawn immediately on the next frame so the mini-map never shows+ // the previous street position while the player is dropping back in.+ poseReportElapsedRef.current = POSE_REPORT_INTERVAL_SECONDS;lookInitRef.current = false;}, [active, positions]);@@ -216,6 +220,7 @@ export default function PlayerController({rig.vy = 0;rig.jumping = false;lastSpawnRef.current = rig.position.clone();+ poseReportElapsedRef.current = POSE_REPORT_INTERVAL_SECONDS;lookInitRef.current = false;// `teleport` is read for its coordinates but is not the trigger — see above.// eslint-disable-next-line react-hooks/exhaustive-deps@@ -552,8 +557,11 @@ export default function PlayerController({? rig.speed: (hasHorizontal ? (isSprinting ? SPRINT_SPEED : WALK_SPEED) * (forwardInput < 0 ? -1 : 1) : 0);- poseTickRef.current = (poseTickRef.current || 0) + 1;- if (poseTickRef.current % 3 === 0) {+ // DOM telemetry does not need the 60fps camera cadence. A time-based 10Hz publish+ // stays smooth at both 30fps and 120fps while avoiding ~20 full page renders/sec.+ poseReportElapsedRef.current += delta;+ if (poseReportElapsedRef.current >= POSE_REPORT_INTERVAL_SECONDS) {+ poseReportElapsedRef.current %= POSE_REPORT_INTERVAL_SECONDS;onPlayerPoseChange?.({x: rig.position.x,y: rig.position.y,diff --git a/client/src/components/openworld/PlayerController.test.jsx b/client/src/components/openworld/PlayerController.test.jsxindex 2bc1f741e3..11d5b2b7f3 100644--- a/client/src/components/openworld/PlayerController.test.jsx+++ b/client/src/components/openworld/PlayerController.test.jsx@@ -102,4 +102,21 @@ describe('PlayerController Space (jump) capture', () => {expect(() => act(() => runFrame({}, 1 / 60))).not.toThrow();});++ it('publishes HUD pose telemetry immediately, then at a time-based 10Hz cadence', () => {+ const onPlayerPoseChange = vi.fn();+ renderRig({ onPlayerPoseChange });+ const runFrame = frameCallbacks.at(-1);++ act(() => runFrame({}, 0.016));+ expect(onPlayerPoseChange).toHaveBeenCalledTimes(1);++ act(() => {+ for (let frame = 0; frame < 4; frame += 1) runFrame({}, 0.02);+ });+ expect(onPlayerPoseChange).toHaveBeenCalledTimes(1);++ act(() => runFrame({}, 0.02));+ expect(onPlayerPoseChange).toHaveBeenCalledTimes(2);+ });});diff --git a/client/src/hooks/useOpenWorldData.js b/client/src/hooks/useOpenWorldData.jsindex e1df33fac1..2d25c937a7 100644--- a/client/src/hooks/useOpenWorldData.js+++ b/client/src/hooks/useOpenWorldData.js@@ -5,9 +5,11 @@ import { useAutoRefetch } from './useAutoRefetch';import { METRICS as HEALTH_TOWER_METRICS } from '../utils/openWorldHealthTower';import { applyAiStatusEvent, pruneAiOps, AI_CORE } from '../utils/openWorldAiCore';import { coalesce } from '../utils/coalesce';+import { appendEventLogBatch } from '../utils/openWorldTimeline';// 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 EVENT_LOG_FLUSH_MS = 100;const healthSignature = (h) => {const warnings = (h?.warnings || []).map(w => `${w.type}:${w.message}`).join(';');@@ -37,6 +39,8 @@ export const useOpenWorldData = () => {const [aiActivity, setAiActivity] = useState({ ops: {}, lastStartTs: 0 });const [loading, setLoading] = useState(true);const logIdRef = useRef(0);+ const pendingEventLogsRef = useRef([]);+ const eventLogFlushTimerRef = useRef(null);// One-shot timer that prunes expired AI Core ops. `ai:status` is purely event-driven, so// without this a `done` afterglow (or a flare) beam would linger until the next event —// the render derivations check the clock but nothing re-renders to advance it.@@ -180,6 +184,14 @@ export const useOpenWorldData = () => {useEffect(() => {fetchAll();+ const flushEventLogs = () => {+ eventLogFlushTimerRef.current = null;+ if (pendingEventLogsRef.current.length === 0) return;+ const incoming = pendingEventLogsRef.current;+ pendingEventLogsRef.current = [];+ setEventLogs(prev => appendEventLogBatch(prev, incoming));+ };+const subscribe = () => {socket.emit('cos:subscribe');socket.emit('notifications:subscribe');@@ -208,7 +220,10 @@ export const useOpenWorldData = () => {const handleCosLog = (data) => {const entry = { ...data, timestamp: data.timestamp || Date.now(), _localId: ++logIdRef.current };- setEventLogs(prev => [...prev, entry].slice(-50));+ pendingEventLogsRef.current.push(entry);+ if (eventLogFlushTimerRef.current == null) {+ eventLogFlushTimerRef.current = setTimeout(flushEventLogs, EVENT_LOG_FLUSH_MS);+ }};socket.on('cos:log', handleCosLog);@@ -327,6 +342,9 @@ export const useOpenWorldData = () => {socket.off('voice:idle', handleVoiceIdle);socket.off('ai:status', handleAiStatus);if (aiPruneTimerRef.current) clearTimeout(aiPruneTimerRef.current);+ if (eventLogFlushTimerRef.current != null) clearTimeout(eventLogFlushTimerRef.current);+ eventLogFlushTimerRef.current = null;+ pendingEventLogsRef.current = [];coalescedFetchAll.cancel(); // drop any pending trailing refetch on unmount};}, [fetchAll, fetchApps, fetchBackup, coalescedFetchAll]);diff --git a/client/src/hooks/useOpenWorldData.test.jsx b/client/src/hooks/useOpenWorldData.test.jsxnew file mode 100644index 0000000000..401bfa56e3--- /dev/null+++ b/client/src/hooks/useOpenWorldData.test.jsx@@ -0,0 +1,90 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { act, renderHook } from '@testing-library/react';++const { socketHandlers, socket } = vi.hoisted(() => {+ const handlers = new Map();+ return {+ socketHandlers: handlers,+ socket: {+ connected: true,+ emit: vi.fn(),+ on: vi.fn((event, handler) => handlers.set(event, handler)),+ off: vi.fn((event, handler) => {+ if (handlers.get(event) === handler) handlers.delete(event);+ }),+ },+ };+});++vi.mock('../services/socket', () => ({ default: socket }));+vi.mock('../services/api', () => ({+ getApps: vi.fn(async () => []),+ getRunningAgents: vi.fn(async () => []),+ getCosAgents: vi.fn(async () => []),+ getCosStatus: vi.fn(async () => ({ running: false })),+ getReviewCounts: vi.fn(async () => ({ total: 0, alert: 0, todo: 0, briefing: 0, cos: 0 })),+ getInstances: vi.fn(async () => ({ self: null, peers: [], syncStatus: null })),+ getSystemHealth: vi.fn(async () => null),+ getNotificationCount: vi.fn(async () => ({ count: 0 })),+ getBackupStatus: vi.fn(async () => null),+ getCosTasks: vi.fn(async () => ({ tasks: [] })),+ getLatestHealthMetrics: vi.fn(async () => null),+ getVoiceStatus: vi.fn(async () => null),+ getCharacter: vi.fn(async () => null),+}));+vi.mock('./useAutoRefetch', () => ({ useAutoRefetch: () => ({ data: null }) }));++import { useOpenWorldData } from './useOpenWorldData';++const settleInitialFetch = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ });+};++beforeEach(() => {+ vi.useFakeTimers();+ socketHandlers.clear();+ socket.emit.mockClear();+ socket.on.mockClear();+ socket.off.mockClear();+});++afterEach(() => vi.useRealTimers());++describe('useOpenWorldData activity log batching', () => {+ it('applies a socket burst in one render without dropping entries', async () => {+ let renders = 0;+ const { result } = renderHook(() => {+ renders += 1;+ return useOpenWorldData();+ });+ await settleInitialFetch();+ const rendersAfterMount = renders;++ act(() => {+ for (let index = 0; index < 50; index += 1) {+ socketHandlers.get('cos:log')?.({ message: `event-${index}`, timestamp: index + 1 });+ }+ });+ expect(result.current.eventLogs).toEqual([]);+ expect(renders).toBe(rendersAfterMount);++ act(() => vi.advanceTimersByTime(100));++ expect(result.current.eventLogs).toHaveLength(50);+ expect(result.current.eventLogs.at(-1).message).toBe('event-49');+ expect(renders - rendersAfterMount).toBe(1);+ });++ it('drops a pending batch when the page unmounts', async () => {+ const { unmount } = renderHook(() => useOpenWorldData());+ await settleInitialFetch();+ act(() => socketHandlers.get('cos:log')?.({ message: 'pending' }));++ unmount();+ expect(() => vi.advanceTimersByTime(200)).not.toThrow();+ expect(socketHandlers.has('cos:log')).toBe(false);+ });+});diff --git a/client/src/pages/OpenWorld.jsx b/client/src/pages/OpenWorld.jsxindex 9fb6a7b6c9..3e7b440e42 100644--- a/client/src/pages/OpenWorld.jsx+++ b/client/src/pages/OpenWorld.jsx@@ -28,6 +28,7 @@ import { getCollectiblesList, loadCollectedShardIds, saveCollectedShardIds } froimport { OpenWorldPaletteProvider } from '../components/openworld/OpenWorldPaletteContext';import { useThemeContext } from '../components/ThemeContext';import { useInstanceFeatures } from '../hooks/useInstanceFeatures';+import { recommendOpenWorldStartTier } from '../utils/openWorldRenderBudget';// Internal render budgets only. These tiers are selected from sustained frame time and are// deliberately not persisted or exposed as player settings; art direction stays coherent while@@ -124,7 +125,13 @@ function OpenWorldInner() {// chooses its detail tier from sustained frame time; low/medium/high/ultra are internal// budgets, not design settings. This keeps the settings drawer focused on choices a player// can actually feel (world style, audio, and controls).- const [autoTier, setAutoTier] = useState('high');+ const [renderStartTier] = useState(() => recommendOpenWorldStartTier({+ coarsePointer: typeof window !== 'undefined'+ && Boolean(window.matchMedia?.('(pointer: coarse)').matches),+ hardwareConcurrency: typeof navigator !== 'undefined' ? navigator.hardwareConcurrency : null,+ deviceMemory: typeof navigator !== 'undefined' ? navigator.deviceMemory : null,+ }));+ const [autoTier, setAutoTier] = useState(renderStartTier);const effectiveTier = autoTier;const sceneSettings = useMemo(() => {@@ -589,7 +596,7 @@ function OpenWorldInner() {playerActionRef={playerActionRef}dimmedAppIds={filterResult.dimmed}autoQuality- autoStartTier="high"+ autoStartTier={renderStartTier}autoResetToken={resetNonce}onAutoTierChange={setAutoTier}focusedAppId={appId || null}diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 7b7c547c44..8d923b1ab9 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -99,12 +99,12 @@ its tunable constants and placement helpers.| `openWorldProximity` | Unified player proximity detection across warp pads, buildings, easter eggs, and district landmarks (`detectProximity`, `getResolvedLandmarks`, `WORLD_LANDMARKS`). || `openWorldRegions` | OpenWorld fast-travel registry: named regions over the `openWorldPlan` parcels, each mapped to the PortOS page it visualizes (`OPEN_WORLD_REGIONS`, `getRegion`, `listRegions`, `searchRegions`, `regionArrivalPoint`, `regionPath`). || `openWorldPlayerRig` | Exploration player-rig math: third-person follow camera, boom collision, damping, facing, avatar state (`thirdPersonCamera`, `resolveBoom`, `dampAngle`, `moveFacing`, `avatarState`). |-| `openWorldRenderBudget` | Pure Auto-quality render-budget state machine: p75 frame-time windows, hysteresis, cooldown, warm-up/gap rejection (`createRenderBudget`, `recordFrame`, `restartWarmup`, `resetRenderBudget`, `getEffectiveTier`, `QUALITY_TIERS`, `DEFAULT_RENDER_BUDGET_CONFIG`). |+| `openWorldRenderBudget` | Pure Auto-quality render-budget state machine: capability-aware startup tier (`recommendOpenWorldStartTier`), p75 frame-time windows, hysteresis, cooldown, warm-up/gap rejection (`createRenderBudget`, `recordFrame`, `restartWarmup`, `resetRenderBudget`, `getEffectiveTier`, `QUALITY_TIERS`, `DEFAULT_RENDER_BUDGET_CONFIG`). || `openWorldRooftops` | Deterministic rooftop fixture kits (antenna/tank/AC/dish) per app name (`computeRooftopKit`). || `openWorldProductivity` | Productivity monument from streak/velocity tiers (`computeProductivityMonument`). || `openWorldSoundscape` | Ambient soundscape: mood/energy classification, chord selection (`computeSoundscape`), and the manual mood override (`applyMoodOverride`). || `openWorldSpeedPads` | Luminous road speed boost pads placement and geometric local-coordinate overlap detection (`getSpeedPadsList`, `checkSpeedPadOverlap`, `SPEED_PADS`). || `openWorldTaskFlowRiver` | Task-flow river width/speed from backlog & throughput (`computeTaskFlowRiver`). || `openWorldTaskQueue` | Task-queue state/color from status counts (`computeTaskQueue`). |-| `openWorldTimeline` | Activity-log density bins and timeline buckets (`computeActivityDensity`, `buildTimelineBuckets`). |+| `openWorldTimeline` | Bounded activity-log batch appends plus density bins and timeline buckets (`appendEventLogBatch`, `computeActivityDensity`, `buildTimelineBuckets`). || `openWorldVoiceMarker` | Voice-agent marker state/color/label from voice status (`computeVoiceMarker`). |diff --git a/client/src/utils/openWorldRenderBudget.js b/client/src/utils/openWorldRenderBudget.jsindex b1e9884360..14201d99bd 100644--- a/client/src/utils/openWorldRenderBudget.js+++ b/client/src/utils/openWorldRenderBudget.js@@ -14,6 +14,29 @@export const QUALITY_TIERS = ['low', 'medium', 'high', 'ultra'];+// Pick a conservative first tier from capabilities that are available before the+// frame-time sampler has enough evidence to adapt. Starting every device at High+// made phones and small-memory machines pay the full scene cost for several seconds+// before Auto quality could react. Unknown desktop capabilities remain High; a coarse+// pointer or sub-8-core/sub-8GB device starts at Medium, while clearly constrained+// hardware starts at Low. The live budget can still climb when it measures headroom.+export function recommendOpenWorldStartTier({+ coarsePointer = false,+ hardwareConcurrency = null,+ deviceMemory = null,+} = {}) {+ const cores = Number.isFinite(hardwareConcurrency) && hardwareConcurrency > 0+ ? hardwareConcurrency+ : null;+ const memoryGb = Number.isFinite(deviceMemory) && deviceMemory > 0+ ? deviceMemory+ : null;++ if ((cores !== null && cores <= 2) || (memoryGb !== null && memoryGb <= 4)) return 'low';+ if (coarsePointer || (cores !== null && cores < 8) || (memoryGb !== null && memoryGb < 8)) return 'medium';+ return 'high';+}+// Thresholds from the issue's acceptance criteria. p75 frame time is the signal:// > 25ms (≈40fps) for 2 windows → step down; < 18ms (≈55fps) for 5 windows → step up.// The 18–25ms dead band is the hysteresis gap — a window landing there breaks bothdiff --git a/client/src/utils/openWorldRenderBudget.test.js b/client/src/utils/openWorldRenderBudget.test.jsindex c2a8c6678c..1061f98329 100644--- a/client/src/utils/openWorldRenderBudget.test.js+++ b/client/src/utils/openWorldRenderBudget.test.js@@ -8,6 +8,7 @@ import {resetRenderBudget,getEffectiveTier,percentile,+ recommendOpenWorldStartTier,tierToIndex,} from './openWorldRenderBudget.js';@@ -50,6 +51,20 @@ describe('openWorldRenderBudget — helpers', () => {expect(tierToIndex('ultra')).toBe(QUALITY_TIERS.length - 1);expect(tierToIndex('bogus')).toBe(QUALITY_TIERS.indexOf('high'));});++ it('starts conservatively on touch and lower-capability devices', () => {+ expect(recommendOpenWorldStartTier({ coarsePointer: true, hardwareConcurrency: 12 })).toBe('medium');+ expect(recommendOpenWorldStartTier({ hardwareConcurrency: 6 })).toBe('medium');+ expect(recommendOpenWorldStartTier({ deviceMemory: 6 })).toBe('medium');+ expect(recommendOpenWorldStartTier({ hardwareConcurrency: 2 })).toBe('low');+ expect(recommendOpenWorldStartTier({ deviceMemory: 4 })).toBe('low');+ });++ it('keeps capable and unknown desktops at high', () => {+ expect(recommendOpenWorldStartTier()).toBe('high');+ expect(recommendOpenWorldStartTier({ hardwareConcurrency: 12, deviceMemory: 16 })).toBe('high');+ expect(recommendOpenWorldStartTier({ hardwareConcurrency: 0, deviceMemory: Number.NaN })).toBe('high');+ });});describe('openWorldRenderBudget — warm-up & gap rejection (ignored samples)', () => {diff --git a/client/src/utils/openWorldTimeline.js b/client/src/utils/openWorldTimeline.jsindex 592205cf3c..7c9fc65b25 100644--- a/client/src/utils/openWorldTimeline.js+++ b/client/src/utils/openWorldTimeline.js@@ -10,6 +10,15 @@// up the render. `now` is injectable into both transforms for deterministic tests.const MAX_TIMELINE_EVENTS = 40;+// Append a socket burst to the HUD's bounded activity buffer in one immutable+// update. The data hook batches raw cos:log frames before calling this helper so+// a chatty agent costs one React render per short window, without dropping any+// entries from the burst.+export function appendEventLogBatch(previous, incoming, max = 50) {+ const combined = [...(previous || []), ...(incoming || [])];+ return combined.length > max ? combined.slice(-max) : combined;+}+// Lower-case so lookups against the lower-cased color maps in OpenWorldIntelPane// stay robust; the cos:log stream only emits info/warn/error/success/debug, so// unknown values just fall through to the maps' info default (same as thediff --git a/client/src/utils/openWorldTimeline.test.js b/client/src/utils/openWorldTimeline.test.jsindex e538640ec3..0282f6fefa 100644--- a/client/src/utils/openWorldTimeline.test.js+++ b/client/src/utils/openWorldTimeline.test.js@@ -1,11 +1,23 @@import { describe, it, expect } from 'vitest';-import { computeActivityDensity, buildTimelineBuckets } from './openWorldTimeline';+import { appendEventLogBatch, computeActivityDensity, buildTimelineBuckets } from './openWorldTimeline';// Fixed reference "now" so the relative-age math is deterministic.const NOW = 1_700_000_000_000;const minsAgo = (m) => NOW - m * 60 * 1000;const secsAgo = (s) => NOW - s * 1000;+describe('appendEventLogBatch', () => {+ it('preserves every event in a socket burst and caps the oldest entries', () => {+ const previous = [{ _localId: 1 }, { _localId: 2 }];+ const incoming = [{ _localId: 3 }, { _localId: 4 }, { _localId: 5 }];++ expect(appendEventLogBatch(previous, incoming, 4).map((event) => event._localId))+ .toEqual([2, 3, 4, 5]);+ expect(previous).toHaveLength(2);+ expect(incoming).toHaveLength(3);+ });+});+describe('computeActivityDensity', () => {it('returns one empty slot per bin', () => {const slots = computeActivityDensity([], { now: NOW, bins: 24 });