Skip to content

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

feat: adaptive render budget and visibility-aware frameloop for City (#2592)

[._.]/ Adam Eivyf9314ef1efda
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 380b4358ae..3367a6e1ed 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -7,6 +7,7 @@
## Changed
+- **[issue-2592] Add an adaptive render budget and visibility-aware frameloop to CyberCity.** City gains an **Auto quality mode** (Settings → Quality): new installs default to Auto starting at High, while existing saved settings load as **Manual** and keep their preset (adaptation never touches a chosen fixed preset, and never rewrites localStorage). A pure state machine, `client/src/utils/cityRenderBudget.js`, watches p75 frame time over 2s rolling windows — ignoring the startup warm-up and frame gaps above 250ms — and steps the effective detail tier **down** after two windows above 25ms, **up** after five below 18ms, with a 10s cooldown and never more than one tier per decision (the 18–25ms dead band is the anti-oscillation gap). The runtime effective tier is separate from persisted settings and drives reflections, particle density, DPR, interior-window shaders, and set dressing via an explicit `effectiveTier` (replacing the old `particleDensity`-as-quality proxy in `cityShowDetail`/`cityShowInteriorWindows`). The live City frameloop now **pauses while the tab is hidden** (`frameloop="never"`) and resumes with a fresh warm-up when visible again — Photo mode keeps its demand loop and capture behavior untouched. The settings panel shows the effective tier (`AUTO · HIGH`) plus a local-only diagnostics readout (tier, FPS, p75) that is never persisted or transmitted. New unit tests cover downshift, recovery, cooldown, ignored samples (warm-up/gap), storage compatibility, Manual mode, and visibility transitions.
- **[issue-2530] Decompose `cos.js` `dequeueNextTask` and split `cosAgents.js` into focused modules.** The ~370-line `dequeueNextTask` scheduler is now a thin orchestrator that threads a shared `ctx` through five `spawnDequeuePriorityN(ctx)` tier helpers (mirroring `evaluateTasks`), with the pure per-cycle capacity tracker (`createDequeueCapacity`) and mission/idle tier-eligibility predicates extracted to a new `server/services/cosDequeue.js` — so the scheduler and its unit tests exercise the *same* guards instead of a local replica. The ~1090-line `cosAgents.js` is split into focused siblings — `cosAgentIndex.js` (date-bucket index / migration / prune / archive layout), `cosAgentLifecycle.js` (register / complete / output / terminate / pause / kill / BTW / zombie cleanup), `cosAgentFeedback.js` (feedback capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — with `cosAgents.js` kept as a thin barrel so every existing import path is unchanged. Pure mechanical refactor: no behavior change.
- **[issue-2533] Thin the apps-list route and split the imageGen setup routes into their own module.** The `GET /api/apps` handler's ~80 lines of inline PM2 enrichment (one read per `pm2Home`, absent-vs-empty status classification, ecosystem-config process backfill, port derivation) moved into a new `server/services/appListEnrichment.js` (`enrichAppsWithPm2Status(apps)`), so the route just fetches the raw records and responds; the pure port/status helpers (`deriveUiPort`/`deriveAppPorts`/`computeOverallStatus`) live there too and are re-exported from `routes/apps/shared.js` so the detail/lifecycle routes keep one shared implementation. The `/api/image-gen/setup/*` handlers (python probe/venv bootstrap, FLUX.2 install/status, HuggingFace-token store, pip installer) split out of the large `routes/imageGen.js` render router into `routes/imageGenSetup.js`, with the setup-check cache and pip allowlist relocated to `services/imageGen/setup.js`. Pure mechanical refactor — no behavior change.
- **[issue-2531] Split the pipeline `issues.js` and `visualStages.js` monoliths along CRUD/stage/sync seams.** The ~1470-line `server/services/pipeline/issues.js` is now a thin barrel over `issuesShared.js` (store facade + per-series write queue + record sanitizers + `renumberInline`), `issueCrud.js` (create/read/list/update/delete + numbering/reassign), `issueStages.js` (per-stage merge/history/restore), and `issueSync.js` (peer-sync LWW merge + tombstone GC). The ~1760-line `visualStages.js` is now a thin barrel over `visualStageHelpers.js` (shared style/prompt composers + image-gen enqueue plumbing), `covers.js` (comic + volume front/back covers), `comicPages.js` (comic page renders + panel prompt refine), and `storyboards.js` (scene/shot renders + scene refine). Pure mechanical refactor — no behavior change; the single-tail-per-series write serialization (`queueSeriesIssuesWrite`) and the store's `queueTypeIndexWrite` merge snapshot are preserved, and every existing `from './issues.js'` / `from './visualStages.js'` import path still resolves through the barrels.
diff --git a/client/src/components/city/CityAdaptiveQuality.jsx b/client/src/components/city/CityAdaptiveQuality.jsx
new file mode 100644
index 0000000000..b86a13b280
--- /dev/null
+++ b/client/src/components/city/CityAdaptiveQuality.jsx
@@ -0,0 +1,69 @@
+import { useRef, useEffect } from 'react';
+import { useFrame } from '@react-three/fiber';
+import {
+ createRenderBudget,
+ recordFrame,
+ restartWarmup,
+ resetRenderBudget,
+ getEffectiveTier,
+} from '../../utils/cityRenderBudget.js';
+
+// In-Canvas driver for Auto quality mode (issue #2592). It samples per-frame delta
+// times via useFrame, feeds them to the pure render-budget state machine, and lifts
+// tier changes + (throttled) diagnostics back up to CyberCity through callbacks.
+// It renders nothing. All impurity (timers, refs, frame loop) lives here so the
+// state machine stays pure and unit-tested.
+//
+// - `enabled`: Auto mode is on. When off, the machine is left idle (Manual mode).
+// - `startTier`: the tier to (re)start the budget at when Auto engages.
+// - `resumeToken`: bumped by CityScene when the frameloop resumes after the tab was
+// hidden — re-arms the warm-up so post-resume jank doesn't drive a bogus decision.
+// - `diagnosticsEnabled`: only push diagnostics upward while the settings panel is
+// open, so the 0.5Hz readout doesn't re-render the scene when nobody's watching.
+export default function CityAdaptiveQuality({
+ enabled,
+ startTier = 'high',
+ resumeToken = 0,
+ diagnosticsEnabled = false,
+ onTierChange,
+ onDiagnostics,
+}) {
+ const stateRef = useRef(null);
+ if (stateRef.current === null) {
+ stateRef.current = createRenderBudget(startTier, typeof performance !== 'undefined' ? performance.now() : 0);
+ }
+
+ // Re-start the budget whenever Auto (re)engages or the starting tier changes, so a
+ // Manual→Auto switch always begins at High rather than resuming a stale tier.
+ useEffect(() => {
+ if (!enabled) return;
+ const now = typeof performance !== 'undefined' ? performance.now() : 0;
+ stateRef.current = resetRenderBudget(stateRef.current, startTier, now);
+ onTierChange?.(getEffectiveTier(stateRef.current));
+ // Deps are intentionally just [enabled, startTier] — a fresh onTierChange callback
+ // identity must not reset the live budget mid-run.
+ }, [enabled, startTier]);
+
+ // Re-arm warm-up on frameloop resume (tab became visible again).
+ useEffect(() => {
+ if (!enabled) return;
+ const now = typeof performance !== 'undefined' ? performance.now() : 0;
+ stateRef.current = restartWarmup(stateRef.current, now);
+ }, [resumeToken]);
+
+ useFrame((_, delta) => {
+ if (!enabled) return;
+ const now = typeof performance !== 'undefined' ? performance.now() : 0;
+ const prevTier = getEffectiveTier(stateRef.current);
+ stateRef.current = recordFrame(stateRef.current, { now, dt: delta * 1000 });
+ const nextTier = getEffectiveTier(stateRef.current);
+ if (nextTier !== prevTier) onTierChange?.(nextTier);
+ // Diagnostics refresh only when a window closes (~0.5Hz) and only if someone's
+ // watching — keeps the hot loop from re-rendering the page.
+ if (diagnosticsEnabled && stateRef.current.windowClosed) {
+ onDiagnostics?.(stateRef.current.diagnostics);
+ }
+ });
+
+ return null;
+}
diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsx
index b0304181c4..1ff9ef1d1c 100644
--- a/client/src/components/city/CityScene.jsx
+++ b/client/src/components/city/CityScene.jsx
@@ -47,18 +47,32 @@ import PlayerController from './PlayerController';
import CameraTransition from './CameraTransition';
import CityPhotoCamera from './CityPhotoCamera';
import CityDepthOfField from './CityDepthOfField';
+import CityAdaptiveQuality from './CityAdaptiveQuality';
import { cityDayMix } from './cityConstants';
import { CityPaletteProvider } from './CityPaletteContext';
import ErrorBoundary from '../ErrorBoundary';
+import { useVisibilityEvent } from '../../hooks/useVisibilityEvent';
const STARTUP_PARTICLE_DENSITY = 0.49;
-export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCameraView, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, activityCalendar, goals, character, chronotype, memoryGraph, inboxDepth, jiraTickets, introspection, playback = false, photoMode, photoPresetId, photoDof, onPhotoCaptureReady, settings, playSfx, keysRef, dimmedAppIds, background, palette }) {
+export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCameraView, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, activityCalendar, goals, character, chronotype, memoryGraph, inboxDepth, jiraTickets, introspection, playback = false, photoMode, photoPresetId, photoDof, onPhotoCaptureReady, settings, playSfx, keysRef, dimmedAppIds, background, palette, autoQuality = false, autoStartTier = 'high', diagnosticsEnabled = false, onAutoTierChange, onAutoDiagnostics }) {
const [positions, setPositions] = useState(null);
const [proximityApp, setProximityApp] = useState(null);
const [transitioning, setTransitioning] = useState(false);
const [webglLost, setWebglLost] = useState(false);
const [startupSettled, setStartupSettled] = useState(false);
+ // Visibility-aware frameloop (issue #2592): pause the live City render loop while the
+ // tab is hidden, resume (with a fresh warm-up) when it's shown again. `resumeToken`
+ // bumps on each show so the warm-up effect re-runs and the adaptive budget re-arms.
+ const [documentHidden, setDocumentHidden] = useState(
+ () => typeof document !== 'undefined' && document.visibilityState === 'hidden'
+ );
+ const [resumeToken, setResumeToken] = useState(0);
+ useVisibilityEvent(useCallback((state) => {
+ const hidden = state === 'hidden';
+ setDocumentHidden(hidden);
+ if (!hidden) setResumeToken(t => t + 1);
+ }, []));
const prevExplorationRef = useRef(false);
const orbitRef = useRef(null);
const contextCleanupRef = useRef(null);
@@ -80,7 +94,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCam
setStartupSettled(false);
const timer = window.setTimeout(() => setStartupSettled(true), 1200);
return () => window.clearTimeout(timer);
- }, [apps.length, photoMode]);
+ }, [apps.length, photoMode, resumeToken]);
const renderSettings = useMemo(() => {
if (photoMode || startupSettled) return settings;
@@ -197,8 +211,10 @@ export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCam
// Photo mode freezes the scene for a clean still (roadmap 3.6): "demand" stops the
// frameloop once the camera-fly settles, so particles/streams/weather/pulses pause for a
// deliberate shot. CityPhotoCamera pumps invalidate() during the fly; capture renders
- // directly via gl.render(). Live mode keeps the always-on loop the dashboard relies on.
- frameloop={photoMode ? 'demand' : 'always'}
+ // directly via gl.render(). Live mode keeps the always-on loop the dashboard relies on —
+ // except while the tab is hidden, where "never" halts rendering entirely (issue #2592).
+ // Photo mode always keeps its own demand loop so capture still works in a hidden tab.
+ frameloop={photoMode ? 'demand' : (documentHidden ? 'never' : 'always')}
onCreated={handleCanvasCreated}
style={{ background: sceneClearColor, cursor: explorationMode ? 'crosshair' : 'auto', opacity: webglLost ? 0 : 1 }}
// preserveDrawingBuffer is only needed while taking postcards. Keeping it
@@ -319,6 +335,19 @@ export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCam
touches={{ ONE: THREE.TOUCH.PAN, TWO: THREE.TOUCH.DOLLY_ROTATE }}
/>
)}
+ {/* Auto quality mode: samples frame times inside the live loop and lifts tier
+ changes back up to the page. Never mounted in photo mode (its demand loop
+ isn't a steady-state signal). Renders nothing. */}
+ {!photoMode && (
+ <CityAdaptiveQuality
+ enabled={autoQuality}
+ startTier={autoStartTier}
+ resumeToken={resumeToken}
+ diagnosticsEnabled={diagnosticsEnabled}
+ onTierChange={onAutoTierChange}
+ onDiagnostics={onAutoDiagnostics}
+ />
+ )}
<CameraTransition
active={explorationMode}
onTransitionComplete={handleTransitionComplete}
diff --git a/client/src/components/city/CitySettingsPanel.jsx b/client/src/components/city/CitySettingsPanel.jsx
index df735a1d76..dc0f7b11db 100644
--- a/client/src/components/city/CitySettingsPanel.jsx
+++ b/client/src/components/city/CitySettingsPanel.jsx
@@ -99,12 +99,28 @@ function SectionHeader({ title, subtitle }) {
);
}
-export default function CitySettingsPanel() {
+// Format a diagnostics number, guarding the not-yet-measured (null) case.
+function fmt(value, digits = 0) {
+ return typeof value === 'number' && Number.isFinite(value) ? value.toFixed(digits) : '—';
+}
+
+export default function CitySettingsPanel({ qualityMode = 'manual', effectiveTier = 'high', diagnostics = null }) {
const navigate = useNavigate();
const { settings, updateSetting, resetSettings } = useCitySettingsContext();
if (!settings) return null;
+ const isAuto = qualityMode === 'auto';
+ const modeLabel = isAuto
+ ? `AUTO · ${String(effectiveTier).toUpperCase()}`
+ : `MANUAL · ${String(settings.qualityPreset || 'high').toUpperCase()}`;
+
+ const setQuality = (key) => {
+ // 'auto' engages the adaptive budget; a named preset pins Manual (handled in the hook).
+ if (key === 'auto') updateSetting('qualityMode', 'auto');
+ else updateSetting('qualityPreset', key);
+ };
+
return (
<div className="absolute bottom-4 right-4 z-50 pointer-events-auto animate-in slide-in-from-bottom-4 duration-300">
<div
@@ -130,16 +146,27 @@ export default function CitySettingsPanel() {
</div>
<div className="px-4 py-3 space-y-5">
- {/* Quality Preset */}
+ {/* Quality */}
<div>
- <SectionHeader title="QUALITY PRESET" subtitle="Controls overall visual fidelity" />
+ <SectionHeader title="QUALITY" subtitle={modeLabel} />
+ {/* AUTO adapts the effective tier to sustained frame pressure. */}
+ <button
+ onClick={() => setQuality('auto')}
+ className={`w-full font-pixel text-[9px] py-2 mb-1.5 rounded border transition-all tracking-wide ${
+ isAuto
+ ? 'bg-cyan-500/20 border-cyan-500/50 text-cyan-400 shadow-[0_0_8px_rgba(6,182,212,0.2)]'
+ : 'bg-gray-800/40 border-gray-700/40 text-gray-500 hover:border-gray-600 hover:text-gray-400'
+ }`}
+ >
+ AUTO {isAuto ? `· ${String(effectiveTier).toUpperCase()}` : ''}
+ </button>
<div className="grid grid-cols-4 gap-1.5">
{Object.keys(QUALITY_PRESETS).map(preset => (
<button
key={preset}
- onClick={() => updateSetting('qualityPreset', preset)}
+ onClick={() => setQuality(preset)}
className={`font-pixel text-[9px] py-2 rounded border transition-all tracking-wide ${
- settings.qualityPreset === preset
+ !isAuto && settings.qualityPreset === preset
? 'bg-cyan-500/20 border-cyan-500/50 text-cyan-400 shadow-[0_0_8px_rgba(6,182,212,0.2)]'
: 'bg-gray-800/40 border-gray-700/40 text-gray-500 hover:border-gray-600 hover:text-gray-400'
}`}
@@ -148,6 +175,14 @@ export default function CitySettingsPanel() {
</button>
))}
</div>
+ {/* Local-only diagnostics — never persisted or transmitted (issue #2592). */}
+ {isAuto && (
+ <div className="mt-2 px-2 py-1.5 rounded bg-black/40 border border-cyan-500/10 font-pixel text-[8px] text-gray-500 tracking-wide flex items-center justify-between">
+ <span>TIER <span className="text-cyan-400/70">{String(effectiveTier).toUpperCase()}</span></span>
+ <span>{fmt(diagnostics?.fps)} FPS</span>
+ <span>P75 {fmt(diagnostics?.p75, 1)}ms</span>
+ </div>
+ )}
</div>
<div className="border-t border-cyan-500/10" />
diff --git a/client/src/components/city/cityConstants.js b/client/src/components/city/cityConstants.js
index aea29a1623..52870e1c78 100644
--- a/client/src/components/city/cityConstants.js
+++ b/client/src/components/city/cityConstants.js
@@ -215,17 +215,30 @@ export const cityDayMix = (settings) => {
return smoothstepRange(0.35, 1, preset?.daylightFactor ?? 0);
};
-// True when the active quality preset is above "low" (particleDensity 0.5) — the shared
-// gate for optional set dressing (rooftop kits, street furniture, transit trams). The
-// boundary is exact-0.5-excluded on purpose: the low preset renders structure only.
-export const cityShowDetail = (settings) => (settings?.particleDensity ?? 1) > 0.5;
-
-// True when the active quality preset is "high" or above (particleDensity ≥ 1.0)
-// — the gate for the heavier InteriorMappingMaterial window panes, which
-// ray-march a fake interior per pane and so cost more than the flat window
-// texture. Held one tier above cityShowDetail so medium-tier machines keep the
-// rest of the set dressing but skip the per-pane interior shader.
-export const cityShowInteriorWindows = (settings) => (settings?.particleDensity ?? 1) >= 1;
+// Explicit tier rank for the detail gates below. `settings.effectiveTier` is the
+// runtime tier (Auto mode's adaptive tier, or the Manual preset) — a first-class
+// signal that replaces the old `particleDensity`-as-quality-proxy (issue #2592).
+// When it's absent (older payloads, tests, or code that never set it) we fall back
+// to the legacy particleDensity thresholds so behavior is unchanged.
+const DETAIL_TIER_RANK = { low: 0, medium: 1, high: 2, ultra: 3 };
+
+// True at medium tier and above — the shared gate for optional set dressing (rooftop
+// kits, street furniture, transit trams). The low tier renders structure only.
+export const cityShowDetail = (settings) => (
+ settings?.effectiveTier
+ ? (DETAIL_TIER_RANK[settings.effectiveTier] ?? DETAIL_TIER_RANK.high) >= DETAIL_TIER_RANK.medium
+ : (settings?.particleDensity ?? 1) > 0.5
+);
+
+// True at high tier and above — the gate for the heavier InteriorMappingMaterial
+// window panes, which ray-march a fake interior per pane and so cost more than the
+// flat window texture. Held one tier above cityShowDetail so medium-tier machines
+// keep the rest of the set dressing but skip the per-pane interior shader.
+export const cityShowInteriorWindows = (settings) => (
+ settings?.effectiveTier
+ ? (DETAIL_TIER_RANK[settings.effectiveTier] ?? DETAIL_TIER_RANK.high) >= DETAIL_TIER_RANK.high
+ : (settings?.particleDensity ?? 1) >= 1
+);
// Drei <Text> props for an informational in-world label that stays legible in both
// the night-neon scene AND the bright daytime scene. At night (dayMix→0) the label
diff --git a/client/src/components/city/cityTheme.test.js b/client/src/components/city/cityTheme.test.js
index fee7ac3385..06f17a7fd8 100644
--- a/client/src/components/city/cityTheme.test.js
+++ b/client/src/components/city/cityTheme.test.js
@@ -314,4 +314,14 @@ describe('quality-preset gates', () => {
expect(cityShowInteriorWindows({ particleDensity: 1.5 })).toBe(true);
expect(cityShowInteriorWindows(undefined)).toBe(true); // defaults to 1
});
+
+ it('detail gates prefer the explicit effectiveTier over particleDensity', () => {
+ // effectiveTier is authoritative when present — it ignores particleDensity, so a
+ // temporarily-reduced density (startup warm-up) can't flip the detail gates.
+ expect(cityShowDetail({ effectiveTier: 'low', particleDensity: 2 })).toBe(false);
+ expect(cityShowDetail({ effectiveTier: 'medium', particleDensity: 0.1 })).toBe(true);
+ expect(cityShowInteriorWindows({ effectiveTier: 'medium', particleDensity: 2 })).toBe(false);
+ expect(cityShowInteriorWindows({ effectiveTier: 'high', particleDensity: 0.1 })).toBe(true);
+ expect(cityShowInteriorWindows({ effectiveTier: 'ultra' })).toBe(true);
+ });
});
diff --git a/client/src/hooks/useCitySettings.js b/client/src/hooks/useCitySettings.js
index 68e6585fa1..864e3f3346 100644
--- a/client/src/hooks/useCitySettings.js
+++ b/client/src/hooks/useCitySettings.js
@@ -42,6 +42,9 @@ const DEFAULT_SETTINGS = {
musicVolume: 0.3,
sfxEnabled: true,
sfxVolume: 0.5,
+ // Auto quality (issue #2592): new installs adapt at runtime, beginning at High.
+ // `qualityPreset` still names the manual preset AND the Auto starting tier.
+ qualityMode: 'auto', // 'auto' = adaptive render budget; 'manual' = fixed preset
qualityPreset: 'high',
timeOfDay: 'auto', // 'auto' follows the active theme's day/night mode; 'day'/'night' force it
explorationMode: false,
@@ -59,7 +62,15 @@ const loadSettings = () => {
return DEFAULT_SETTINGS; // Corrupt stored JSON — fall back to defaults.
}
if (!parsed || typeof parsed !== 'object') return DEFAULT_SETTINGS;
- return { ...DEFAULT_SETTINGS, ...parsed };
+ const merged = { ...DEFAULT_SETTINGS, ...parsed };
+ // Migration: an existing payload predating Auto mode has no `qualityMode` key.
+ // Such installs keep their chosen fixed preset — Manual — rather than being
+ // silently opted into adaptation. Presence of the key (even 'auto') is honored;
+ // this is the "absent vs. present" distinction, so a stored 'auto' survives.
+ if (!Object.prototype.hasOwnProperty.call(parsed, 'qualityMode')) {
+ merged.qualityMode = 'manual';
+ }
+ return merged;
};
export { QUALITY_PRESETS };
@@ -82,9 +93,10 @@ export default function useCitySettings() {
const updateSetting = useCallback((key, value) => {
setSettings(prev => {
- // If changing quality preset, apply bulk changes
+ // If changing quality preset, apply bulk changes. Explicitly picking a preset
+ // also pins Manual mode — the user has chosen a fixed tier over adaptation.
if (key === 'qualityPreset' && QUALITY_PRESETS[value]) {
- const next = { ...prev, qualityPreset: value, ...QUALITY_PRESETS[value] };
+ const next = { ...prev, qualityPreset: value, qualityMode: 'manual', ...QUALITY_PRESETS[value] };
safeWriteStorage(STORAGE_KEY, JSON.stringify(next));
return next;
}
diff --git a/client/src/hooks/useCitySettings.test.jsx b/client/src/hooks/useCitySettings.test.jsx
index c828736e78..0a38c6b0e1 100644
--- a/client/src/hooks/useCitySettings.test.jsx
+++ b/client/src/hooks/useCitySettings.test.jsx
@@ -50,6 +50,41 @@ describe('useCitySettings localStorage resilience', () => {
expect(settings.timeOfDay).toBe('night');
});
+ it('defaults a fresh install to Auto quality beginning at High', () => {
+ const { result } = renderHook(() => useCitySettings());
+ const [settings] = result.current;
+ expect(settings.qualityMode).toBe('auto');
+ expect(settings.qualityPreset).toBe('high');
+ });
+
+ it('loads an existing pre-Auto payload as Manual, keeping its preset', () => {
+ // A stored payload from before Auto mode has no `qualityMode` key.
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ qualityPreset: 'ultra' }));
+ const { result } = renderHook(() => useCitySettings());
+ const [settings] = result.current;
+ expect(settings.qualityMode).toBe('manual');
+ expect(settings.qualityPreset).toBe('ultra');
+ });
+
+ it('preserves a stored qualityMode of auto (present-but-set, not absent)', () => {
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ qualityMode: 'auto', qualityPreset: 'medium' }));
+ const { result } = renderHook(() => useCitySettings());
+ const [settings] = result.current;
+ expect(settings.qualityMode).toBe('auto');
+ });
+
+ it('picking a manual preset pins Manual mode', () => {
+ const { result } = renderHook(() => useCitySettings());
+ act(() => {
+ const [, updateSetting] = result.current;
+ updateSetting('qualityPreset', 'low');
+ });
+ const [settings] = result.current;
+ expect(settings.qualityMode).toBe('manual');
+ expect(settings.qualityPreset).toBe('low');
+ expect(settings.reflectionsEnabled).toBe(false); // low preset bulk-applied
+ });
+
it('handles the time-of-day-auto event without throwing when writes fail', () => {
// This is the listener fired by useTheme.setTheme; with storage blocked its
// write must not surface an unhandled error on the theme-switch path.
diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsx
index fdc40e42c2..7ead1a8ee5 100644
--- a/client/src/pages/CyberCity.jsx
+++ b/client/src/pages/CyberCity.jsx
@@ -13,6 +13,7 @@ import CityScanlines from '../components/city/CityScanlines';
import CityPhotoOverlay from '../components/city/CityPhotoOverlay';
import CityPlaybackOverlay from '../components/city/CityPlaybackOverlay';
import { CitySettingsProvider, useCitySettingsContext } from '../components/city/CitySettingsContext';
+import { QUALITY_PRESETS } from '../hooks/useCitySettings';
import CitySettingsPanel from '../components/city/CitySettingsPanel';
import { computeFilterResult } from '../utils/cityFilter';
import { DEFAULT_PRESET_ID, cyclePreset } from '../utils/cityPhotoMode';
@@ -54,10 +55,31 @@ function CyberCityInner() {
// the backdrop swaps between the blue day sky and the dark night void to match.
const cityTimeOfDay = resolveCityTimeOfDay(settings?.timeOfDay, cityPalette.isDay);
const sceneBackground = cityTimeOfDay.daytime ? CITY_COLORS.timeOfDay.noon.midSky : cityPalette.nightBackground;
- const sceneSettings = useMemo(
- () => ({ ...settings, skyTheme: 'cyberpunk', timeOfDay: cityTimeOfDay.presetKey }),
- [settings, cityTimeOfDay.presetKey],
- );
+
+ // Auto quality mode (issue #2592). In Auto, an adaptive render budget picks the
+ // effective tier at runtime (starting at High); in Manual, the effective tier is the
+ // saved preset. The runtime tier is deliberately separate from persisted settings —
+ // adaptation never rewrites localStorage. `autoDiagnostics` is a local-only readout
+ // (never persisted or transmitted). Auto always *starts* at High per the spec, even
+ // if the user last had a different manual preset.
+ const qualityMode = settings?.qualityMode === 'auto' ? 'auto' : 'manual';
+ const [autoTier, setAutoTier] = useState('high');
+ const [autoDiagnostics, setAutoDiagnostics] = useState(null);
+ const effectiveTier = qualityMode === 'auto' ? autoTier : (settings?.qualityPreset ?? 'high');
+
+ const sceneSettings = useMemo(() => {
+ const base = { ...settings, effectiveTier, skyTheme: 'cyberpunk', timeOfDay: cityTimeOfDay.presetKey };
+ if (qualityMode !== 'auto') return base;
+ // Derive the render-affecting fields (reflections, particle density, DPR) from the
+ // adaptive tier; leave user-tuned lighting/scanline toggles untouched.
+ const tierCfg = QUALITY_PRESETS[effectiveTier] || QUALITY_PRESETS.high;
+ return {
+ ...base,
+ reflectionsEnabled: tierCfg.reflectionsEnabled,
+ particleDensity: tierCfg.particleDensity,
+ dpr: tierCfg.dpr,
+ };
+ }, [settings, effectiveTier, qualityMode, cityTimeOfDay.presetKey]);
const [filter, setFilter] = useState(() => {
// try/catch is necessary because sessionStorage values are external state
@@ -380,6 +402,11 @@ function CyberCityInner() {
playSfx={playSfx}
keysRef={keysRef}
dimmedAppIds={filterResult.dimmed}
+ autoQuality={qualityMode === 'auto'}
+ autoStartTier="high"
+ diagnosticsEnabled={showSettings}
+ onAutoTierChange={setAutoTier}
+ onAutoDiagnostics={setAutoDiagnostics}
/>
{/* The full HUD hides in photo + playback mode so the view is clean; each
mode's overlay replaces it. */}
@@ -435,7 +462,13 @@ function CyberCityInner() {
onExit={playback.exit}
/>
<CityScanlines settings={settings} crt={cityPalette.crt} />
- {showSettings && <CitySettingsPanel />}
+ {showSettings && (
+ <CitySettingsPanel
+ qualityMode={qualityMode}
+ effectiveTier={effectiveTier}
+ diagnostics={qualityMode === 'auto' ? autoDiagnostics : null}
+ />
+ )}
</div>
</CityPaletteProvider>
);
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index d1e686f56a..84d7ca3e1f 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -87,6 +87,7 @@ its tunable constants and placement helpers.
| `cityPhotoMode` | Photo-mode camera presets, the demand-loop fly stepper, postcard stats, and screenshot filename (`getPreset`, `cyclePreset`, `stepFly`). |
| `cityPlan` | Master town plan: district parcels, shoreline/bay, plaza, transit loop, street network (`PARCELS`, `WORLD`, `computeStreets`, `computeStreetProps`, `isInWater`). |
| `cityPlayerRig` | Exploration player-rig math: third-person follow camera, boom collision, damping, facing, avatar state (`thirdPersonCamera`, `resolveBoom`, `dampAngle`, `moveFacing`, `avatarState`). |
+| `cityRenderBudget` | 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`). |
| `cityRooftops` | Deterministic rooftop fixture kits (antenna/tank/AC/dish) per app name (`computeRooftopKit`). |
| `cityProductivity` | Productivity monument from streak/velocity tiers (`computeProductivityMonument`). |
| `citySeasonalDecor` | Season/holiday resolution → seasonal decoration placements (`computeSeasonalDecor`). |
diff --git a/client/src/utils/cityRenderBudget.js b/client/src/utils/cityRenderBudget.js
new file mode 100644
index 0000000000..1c28091854
--- /dev/null
+++ b/client/src/utils/cityRenderBudget.js
@@ -0,0 +1,174 @@
+// Pure render-budget state machine for CyberCity's Auto quality mode (issue #2592).
+//
+// It observes per-frame delta times and decides when the *effective* detail tier
+// should step down (frame pressure) or up (headroom), with hysteresis + a cooldown
+// so it settles instead of oscillating between adjacent tiers. It is intentionally
+// side-effect free: `recordFrame` takes the wall-clock `now` and frame `dt` as inputs
+// (never reads `performance.now()` itself) so the whole decision path is deterministic
+// and unit-testable. The component that drives it (`CityAdaptiveQuality`) owns all the
+// impurity (useFrame, timers, React state).
+//
+// Tiers are ordered low → medium → high → ultra. A "decision" can move at most one
+// tier. Runtime tier lives here, entirely separate from the user's persisted settings —
+// nothing in this module reads or writes localStorage.
+
+export const QUALITY_TIERS = ['low', 'medium', 'high', 'ultra'];
+
+// 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 both
+// streaks so we never ping-pong across an adjacent boundary.
+export const DEFAULT_RENDER_BUDGET_CONFIG = Object.freeze({
+ warmupMs: 1200, // ignore frames within this window after start/resume
+ maxFrameGapMs: 250, // ignore a frame whose dt exceeds this (tab-hidden, GC, alt-tab)
+ windowMs: 2000, // rolling window length
+ percentile: 0.75, // frame-time percentile evaluated per window
+ downshiftFrameMs: 25,
+ downshiftWindows: 2,
+ upshiftFrameMs: 18,
+ upshiftWindows: 5,
+ cooldownMs: 10000, // no further tier change for this long after a change
+});
+
+export function tierToIndex(tier) {
+ const i = QUALITY_TIERS.indexOf(tier);
+ return i === -1 ? QUALITY_TIERS.indexOf('high') : i;
+}
+
+export function getEffectiveTier(state) {
+ return QUALITY_TIERS[state.tierIndex];
+}
+
+// Nearest-rank percentile over an unsorted sample array. Returns null for empty input.
+export function percentile(samples, p) {
+ if (!samples || samples.length === 0) return null;
+ const sorted = [...samples].sort((a, b) => a - b);
+ const rank = Math.ceil(p * sorted.length);
+ const idx = Math.min(sorted.length, Math.max(1, rank)) - 1;
+ return sorted[idx];
+}
+
+function mean(samples) {
+ if (!samples || samples.length === 0) return null;
+ let total = 0;
+ for (const s of samples) total += s;
+ return total / samples.length;
+}
+
+export function createRenderBudget(startTier = 'high', now = 0) {
+ const idx = tierToIndex(startTier);
+ return {
+ tierIndex: idx,
+ startedAt: now, // warm-up baseline
+ windowStart: now,
+ samples: [],
+ pressureStreak: 0,
+ headroomStreak: 0,
+ lastChangeAt: -Infinity, // first change is allowed immediately once a streak is met
+ windowClosed: false, // true on the frame that just closed & classified a window
+ diagnostics: {
+ effectiveTier: QUALITY_TIERS[idx],
+ p75: null,
+ fps: null,
+ sampleCount: 0,
+ windows: 0,
+ },
+ };
+}
+
+// Re-arm the warm-up without touching the current tier — used when the City frameloop
+// resumes after the tab was hidden, so the first sluggish post-resume frames (and any
+// pre-hide pressure/headroom streaks) don't drive a bogus decision.
+export function restartWarmup(state, now) {
+ return {
+ ...state,
+ startedAt: now,
+ windowStart: now,
+ samples: [],
+ pressureStreak: 0,
+ headroomStreak: 0,
+ windowClosed: false,
+ };
+}
+
+// Reset the whole machine to a fresh start at `startTier` (e.g. Manual→Auto switch, or
+// the Auto starting tier changing). Keeps the module pure — caller passes `now`.
+export function resetRenderBudget(state, startTier, now) {
+ return createRenderBudget(startTier, now);
+}
+
+// Feed one frame. Returns a NEW state object (never mutates). `sample` is { now, dt }
+// in milliseconds. Frames during warm-up or with a gap above maxFrameGapMs are dropped
+// from the window (but still advance nothing else). A window is classified only once
+// `windowMs` of wall-clock has elapsed AND it holds at least one valid sample.
+export function recordFrame(state, sample, config = DEFAULT_RENDER_BUDGET_CONFIG) {
+ const { now, dt } = sample;
+ const inWarmup = now - state.startedAt < config.warmupMs;
+ const isGap = dt > config.maxFrameGapMs || dt <= 0;
+
+ const samples = !inWarmup && !isGap ? state.samples.concat(dt) : state.samples;
+
+ // Window still open — accumulate and return.
+ if (now - state.windowStart < config.windowMs) {
+ return { ...state, samples, windowClosed: false };
+ }
+
+ // Window elapsed but no valid samples (e.g. entire window was warm-up or gaps):
+ // roll the window forward without classifying so streaks stay intact.
+ if (samples.length === 0) {
+ return { ...state, windowStart: now, samples: [], windowClosed: false };
+ }
+
+ const p75 = percentile(samples, config.percentile);
+ const fps = 1000 / mean(samples);
+
+ let pressureStreak = state.pressureStreak;
+ let headroomStreak = state.headroomStreak;
+ if (p75 > config.downshiftFrameMs) {
+ pressureStreak += 1;
+ headroomStreak = 0;
+ } else if (p75 < config.upshiftFrameMs) {
+ headroomStreak += 1;
+ pressureStreak = 0;
+ } else {
+ // Dead band — a mixed window breaks both streaks (this is the anti-oscillation gap).
+ pressureStreak = 0;
+ headroomStreak = 0;
+ }
+
+ let tierIndex = state.tierIndex;
+ let lastChangeAt = state.lastChangeAt;
+ const cooledDown = now - state.lastChangeAt >= config.cooldownMs;
+
+ if (cooledDown) {
+ if (pressureStreak >= config.downshiftWindows && tierIndex > 0) {
+ tierIndex -= 1;
+ lastChangeAt = now;
+ pressureStreak = 0;
+ headroomStreak = 0;
+ } else if (headroomStreak >= config.upshiftWindows && tierIndex < QUALITY_TIERS.length - 1) {
+ tierIndex += 1;
+ lastChangeAt = now;
+ pressureStreak = 0;
+ headroomStreak = 0;
+ }
+ }
+
+ return {
+ ...state,
+ tierIndex,
+ windowStart: now,
+ samples: [],
+ pressureStreak,
+ headroomStreak,
+ lastChangeAt,
+ windowClosed: true,
+ diagnostics: {
+ effectiveTier: QUALITY_TIERS[tierIndex],
+ p75,
+ fps,
+ sampleCount: samples.length,
+ windows: state.diagnostics.windows + 1,
+ },
+ };
+}
diff --git a/client/src/utils/cityRenderBudget.test.js b/client/src/utils/cityRenderBudget.test.js
new file mode 100644
index 0000000000..0a4778852d
--- /dev/null
+++ b/client/src/utils/cityRenderBudget.test.js
@@ -0,0 +1,158 @@
+import { describe, it, expect } from 'vitest';
+import {
+ QUALITY_TIERS,
+ DEFAULT_RENDER_BUDGET_CONFIG,
+ createRenderBudget,
+ recordFrame,
+ restartWarmup,
+ resetRenderBudget,
+ getEffectiveTier,
+ percentile,
+ tierToIndex,
+} from './cityRenderBudget.js';
+
+const CFG = DEFAULT_RENDER_BUDGET_CONFIG;
+
+// Deterministic driver over the pure state machine. `now` is a monotonic virtual
+// clock (starts just past warm-up so samples are actually recorded). `window(dt)`
+// feeds constant-`dt` frames until EXACTLY one window is classified — sidestepping
+// the frame-count/window-boundary drift that makes raw counts brittle.
+function makeDriver(startTier) {
+ let s = createRenderBudget(startTier, 0);
+ let now = CFG.warmupMs + 1;
+ return {
+ get tier() { return getEffectiveTier(s); },
+ get state() { return s; },
+ window(dt) {
+ let guard = 0;
+ for (;;) {
+ now += dt;
+ s = recordFrame(s, { now, dt });
+ if (s.windowClosed) return s;
+ if ((guard += 1) > 200000) throw new Error('window never closed');
+ }
+ },
+ advance(ms) { now += ms; },
+ hide(gapMs = 60000) { now += gapMs; s = restartWarmup(s, now); },
+ raw(dt) { now += dt; s = recordFrame(s, { now, dt }); return s; },
+ };
+}
+
+describe('cityRenderBudget — helpers', () => {
+ it('percentile uses nearest-rank and handles empty input', () => {
+ expect(percentile([], 0.75)).toBeNull();
+ expect(percentile([10, 20, 30, 40], 0.75)).toBe(30);
+ expect(percentile([5], 0.75)).toBe(5);
+ });
+
+ it('tierToIndex falls back to high on unknown tier', () => {
+ expect(tierToIndex('low')).toBe(0);
+ expect(tierToIndex('ultra')).toBe(QUALITY_TIERS.length - 1);
+ expect(tierToIndex('bogus')).toBe(QUALITY_TIERS.indexOf('high'));
+ });
+});
+
+describe('cityRenderBudget — warm-up & gap rejection (ignored samples)', () => {
+ it('ignores frames inside the warm-up window but records after it', () => {
+ let s = createRenderBudget('high', 0);
+ // Frames before warmupMs never accumulate (dt=40 would otherwise be pressure).
+ for (let now = 40; now <= 800; now += 40) s = recordFrame(s, { now, dt: 40 });
+ expect(s.samples.length).toBe(0);
+ expect(s.diagnostics.windows).toBe(0);
+ // A frame past the warm-up baseline IS recorded.
+ s = recordFrame(s, { now: CFG.warmupMs + 100, dt: 16 });
+ expect(s.samples.length).toBe(1);
+ });
+
+ it('ignores frames with a dt above maxFrameGapMs', () => {
+ let s = createRenderBudget('high', 0);
+ s = recordFrame(s, { now: CFG.warmupMs + 5000, dt: 4000 });
+ expect(s.samples.length).toBe(0);
+ expect(s.diagnostics.windows).toBe(0);
+ });
+});
+
+describe('cityRenderBudget — downshift', () => {
+ it('steps down exactly one tier after two consecutive pressure windows', () => {
+ const d = makeDriver('high');
+ d.window(30); // window 1: p75 30ms > 25ms
+ expect(d.tier).toBe('high');
+ d.window(30); // window 2 → downshift by one
+ expect(d.tier).toBe('medium');
+ expect(d.state.tierIndex).toBe(tierToIndex('medium'));
+ });
+
+ it('does not downshift below the lowest tier', () => {
+ const d = makeDriver('low');
+ for (let w = 0; w < 6; w += 1) {
+ d.window(40);
+ d.advance(CFG.cooldownMs); // clear cooldown between decisions
+ }
+ expect(d.tier).toBe('low');
+ });
+});
+
+describe('cityRenderBudget — recovery (upshift)', () => {
+ it('steps up one tier after five consecutive headroom windows', () => {
+ const d = makeDriver('medium');
+ for (let w = 0; w < 4; w += 1) d.window(10); // four fast windows: not enough
+ expect(d.tier).toBe('medium');
+ d.window(10); // fifth → step up
+ expect(d.tier).toBe('high');
+ });
+
+ it('dead-band windows (18–25ms) break the streak and prevent oscillation', () => {
+ const d = makeDriver('medium');
+ for (let w = 0; w < 4; w += 1) d.window(10);
+ d.window(21); // neutral → resets headroom streak
+ expect(d.state.headroomStreak).toBe(0);
+ d.window(10); // only one fast window again → no upshift
+ expect(d.tier).toBe('medium');
+ });
+});
+
+describe('cityRenderBudget — cooldown', () => {
+ it('blocks a second tier change until the cooldown elapses', () => {
+ const d = makeDriver('high');
+ d.window(30);
+ d.window(30); // → downshift to medium, cooldown starts
+ expect(d.tier).toBe('medium');
+ d.window(30);
+ d.window(30); // two more pressure windows within cooldown → no change
+ expect(d.tier).toBe('medium');
+ d.advance(CFG.cooldownMs); // let the cooldown fully elapse
+ d.window(30); // pending pressure now resolves
+ expect(d.tier).toBe('low');
+ });
+});
+
+describe('cityRenderBudget — visibility transitions', () => {
+ it('restartWarmup re-arms warm-up and clears streaks/samples without changing tier', () => {
+ const d = makeDriver('high');
+ d.window(30); // pressure streak = 1
+ expect(d.state.pressureStreak).toBe(1);
+ d.hide(); // tab hidden, then visible → restartWarmup
+ expect(d.state.pressureStreak).toBe(0);
+ expect(d.state.samples.length).toBe(0);
+ expect(d.tier).toBe('high');
+ // First frames after resume land in the fresh warm-up → ignored.
+ d.raw(30);
+ expect(d.state.samples.length).toBe(0);
+ });
+
+ it('resetRenderBudget returns a fresh machine at the given start tier', () => {
+ const s = resetRenderBudget(createRenderBudget('low', 0), 'ultra', 5000);
+ expect(getEffectiveTier(s)).toBe('ultra');
+ expect(s.startedAt).toBe(5000);
+ expect(s.diagnostics.windows).toBe(0);
+ });
+});
+
+describe('cityRenderBudget — purity', () => {
+ it('recordFrame does not mutate the input state', () => {
+ const s = createRenderBudget('high', 0);
+ const before = JSON.stringify(s);
+ recordFrame(s, { now: CFG.warmupMs + 100, dt: 16 });
+ expect(JSON.stringify(s)).toBe(before);
+ });
+});
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 2951c80154..0a3dccdd7f 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -56,6 +56,7 @@ export * from './cityMiniMap.js';
export * from './cityPhotoMode.js';
export * from './cityPlan.js';
export * from './cityPlayerRig.js';
+export * from './cityRenderBudget.js';
export * from './cityRooftops.js';
export * from './cityProductivity.js';
export * from './citySeasonalDecor.js';