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

fix: discard partial budget windows on frame gaps, gate cooldown on window start, re-arm budget on reset-defaults (#2592)

[._.]/ Adam Eivy38a99ed3ed95
diff --git a/client/src/components/city/CityAdaptiveQuality.jsx b/client/src/components/city/CityAdaptiveQuality.jsx
index 0e8b1f9fee..fbf255a4f4 100644
--- a/client/src/components/city/CityAdaptiveQuality.jsx
+++ b/client/src/components/city/CityAdaptiveQuality.jsx
@@ -24,6 +24,7 @@ export default function CityAdaptiveQuality({
enabled,
startTier = 'high',
resumeToken = 0,
+ resetToken = 0,
diagnosticsEnabled = false,
onTierChange,
onDiagnostics,
@@ -39,16 +40,17 @@ export default function CityAdaptiveQuality({
// frame classify against pre-hide samples first.
const seenResumeRef = useRef(resumeToken);
- // 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.
+ // Re-start the budget whenever Auto (re)engages, the starting tier changes, or the user
+ // resets defaults (resetToken) — so a Manual→Auto switch and a RESET DEFAULTS both begin
+ // adaptation fresh at the start tier rather than resuming a stale runtime tier.
useEffect(() => {
if (!enabled) return;
stateRef.current = resetRenderBudget(stateRef.current, startTier, nowMs());
seenResumeRef.current = resumeToken;
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]);
+ // Deps are intentionally [enabled, startTier, resetToken] — a fresh onTierChange
+ // callback identity must not reset the live budget mid-run.
+ }, [enabled, startTier, resetToken]);
useFrame((_, delta) => {
if (!enabled) return;
diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsx
index bbbf5f61f7..758e756088 100644
--- a/client/src/components/city/CityScene.jsx
+++ b/client/src/components/city/CityScene.jsx
@@ -55,7 +55,7 @@ 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, autoQuality = false, autoStartTier = 'high', diagnosticsEnabled = false, onAutoTierChange, onAutoDiagnostics }) {
+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', autoResetToken = 0, diagnosticsEnabled = false, onAutoTierChange, onAutoDiagnostics }) {
const [positions, setPositions] = useState(null);
const [proximityApp, setProximityApp] = useState(null);
const [transitioning, setTransitioning] = useState(false);
@@ -348,6 +348,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCam
enabled={autoQuality}
startTier={autoStartTier}
resumeToken={resumeToken}
+ resetToken={autoResetToken}
diagnosticsEnabled={diagnosticsEnabled}
onTierChange={onAutoTierChange}
onDiagnostics={onAutoDiagnostics}
diff --git a/client/src/components/city/CitySettingsContext.jsx b/client/src/components/city/CitySettingsContext.jsx
index 5e7b95acdd..d780f887a0 100644
--- a/client/src/components/city/CitySettingsContext.jsx
+++ b/client/src/components/city/CitySettingsContext.jsx
@@ -4,10 +4,10 @@ import useCitySettings from '../../hooks/useCitySettings';
const CitySettingsContext = createContext(null);
export function CitySettingsProvider({ children }) {
- const [settings, updateSetting, resetSettings] = useCitySettings();
+ const [settings, updateSetting, resetSettings, resetNonce] = useCitySettings();
return (
- <CitySettingsContext.Provider value={{ settings, updateSetting, resetSettings }}>
+ <CitySettingsContext.Provider value={{ settings, updateSetting, resetSettings, resetNonce }}>
{children}
</CitySettingsContext.Provider>
);
@@ -15,6 +15,6 @@ export function CitySettingsProvider({ children }) {
export function useCitySettingsContext() {
const ctx = useContext(CitySettingsContext);
- if (!ctx) return { settings: null, updateSetting: () => {}, resetSettings: () => {} };
+ if (!ctx) return { settings: null, updateSetting: () => {}, resetSettings: () => {}, resetNonce: 0 };
return ctx;
}
diff --git a/client/src/hooks/useCitySettings.js b/client/src/hooks/useCitySettings.js
index 0b08f12f93..1887495d35 100644
--- a/client/src/hooks/useCitySettings.js
+++ b/client/src/hooks/useCitySettings.js
@@ -77,6 +77,10 @@ export { QUALITY_PRESETS };
export default function useCitySettings() {
const [settings, setSettings] = useState(loadSettings);
+ // Monotonic counter bumped on every reset. The runtime render budget (Auto mode) lives
+ // outside `settings`, so a "RESET DEFAULTS" that leaves qualityMode/preset unchanged
+ // would otherwise not re-arm it — consumers watch this token to reset the budget too.
+ const [resetNonce, setResetNonce] = useState(0);
useEffect(() => {
const handleTimeOfDayAuto = () => {
@@ -109,7 +113,8 @@ export default function useCitySettings() {
const resetSettings = useCallback(() => {
safeRemoveStorage(STORAGE_KEY);
setSettings(DEFAULT_SETTINGS);
+ setResetNonce(n => n + 1);
}, []);
- return [settings, updateSetting, resetSettings];
+ return [settings, updateSetting, resetSettings, resetNonce];
}
diff --git a/client/src/hooks/useCitySettings.test.jsx b/client/src/hooks/useCitySettings.test.jsx
index 0a38c6b0e1..23aa731742 100644
--- a/client/src/hooks/useCitySettings.test.jsx
+++ b/client/src/hooks/useCitySettings.test.jsx
@@ -85,6 +85,18 @@ describe('useCitySettings localStorage resilience', () => {
expect(settings.reflectionsEnabled).toBe(false); // low preset bulk-applied
});
+ it('bumps resetNonce on reset so the runtime budget can re-arm', () => {
+ const { result } = renderHook(() => useCitySettings());
+ const before = result.current[3];
+ act(() => {
+ const resetSettings = result.current[2];
+ resetSettings();
+ });
+ expect(result.current[3]).toBe(before + 1);
+ const [settings] = result.current;
+ expect(settings.qualityMode).toBe('auto'); // reset restores Auto default
+ });
+
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 7ead1a8ee5..e793cdabef 100644
--- a/client/src/pages/CyberCity.jsx
+++ b/client/src/pages/CyberCity.jsx
@@ -24,7 +24,7 @@ import { useThemeContext } from '../components/ThemeContext';
function CyberCityInner() {
const { apps, cosAgents, cosStatus, eventLogs, agentMap, reviewCounts, instances, systemHealth, notificationCounts, backupStatus, cosTasks, healthMetrics, voiceState, character, aiActivity, loading, connected } = useCityData();
- const { settings, updateSetting } = useCitySettingsContext();
+ const { settings, updateSetting, resetNonce } = useCitySettingsContext();
// Ambient soundscape (roadmap 3.4): the music's mood follows system health and its energy
// follows live agent activity. Derived from data the page already has — no extra fetch.
@@ -67,6 +67,10 @@ function CyberCityInner() {
const [autoDiagnostics, setAutoDiagnostics] = useState(null);
const effectiveTier = qualityMode === 'auto' ? autoTier : (settings?.qualityPreset ?? 'high');
+ // On RESET DEFAULTS, clear the stale local diagnostics readout; the adaptive budget
+ // itself re-arms via CityScene's autoResetToken and re-reports tier + fresh samples.
+ useEffect(() => { setAutoDiagnostics(null); }, [resetNonce]);
+
const sceneSettings = useMemo(() => {
const base = { ...settings, effectiveTier, skyTheme: 'cyberpunk', timeOfDay: cityTimeOfDay.presetKey };
if (qualityMode !== 'auto') return base;
@@ -404,6 +408,7 @@ function CyberCityInner() {
dimmedAppIds={filterResult.dimmed}
autoQuality={qualityMode === 'auto'}
autoStartTier="high"
+ autoResetToken={resetNonce}
diagnosticsEnabled={showSettings}
onAutoTierChange={setAutoTier}
onAutoDiagnostics={setAutoDiagnostics}
diff --git a/client/src/utils/cityRenderBudget.js b/client/src/utils/cityRenderBudget.js
index c564be5707..39c2c21a6a 100644
--- a/client/src/utils/cityRenderBudget.js
+++ b/client/src/utils/cityRenderBudget.js
@@ -106,35 +106,44 @@ export function recordFrame(state, sample, config = DEFAULT_RENDER_BUDGET_CONFIG
const inWarmup = now - state.startedAt < config.warmupMs;
const isGap = dt > config.maxFrameGapMs || dt <= 0;
+ // A frame inside the warm-up is dropped AND keeps the window clock pinned to now, so
+ // the first real window starts measuring only once warm-up ends.
+ if (inWarmup) {
+ return { ...state, windowStart: now, samples: [], windowClosed: false };
+ }
+
+ // A >250ms gap (tab hidden, main-thread stall, GC) breaks the continuity of the current
+ // rolling window: discard whatever partial window we'd accumulated and restart the clock
+ // after the gap, so a lone pre-gap sample can't be classified as a full window.
+ if (isGap) {
+ return { ...state, windowStart: now, samples: [], windowClosed: false };
+ }
+
// The window clock starts at its FIRST valid sample, not at reset time — otherwise the
- // 1.2s warm-up (or a long gap) eats most of the first 2s window and it closes with a
- // fraction of a window's samples yet still counts toward a streak. Pinning windowStart
- // to the first sample guarantees every classified window spans a full windowMs of
- // measured frames.
+ // warm-up (or a long gap) eats most of the first 2s window and it closes with a fraction
+ // of a window's samples yet still counts toward a streak. Pinning windowStart to the
+ // first sample guarantees every classified window spans a full windowMs of measured
+ // frames.
let samples = state.samples;
let windowStart = state.windowStart;
- if (!inWarmup && !isGap) {
- if (samples.length === 0) windowStart = now;
- samples = samples.concat(dt);
- }
+ if (samples.length === 0) windowStart = now;
+ samples = samples.concat(dt);
// Window still open — accumulate and return.
if (now - windowStart < config.windowMs) {
return { ...state, samples, windowStart, 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 tierIndex = state.tierIndex;
let lastChangeAt = state.lastChangeAt;
- const cooledDown = now - state.lastChangeAt >= config.cooldownMs;
+ // Cooldown eligibility keys on the window's START, not its close — a window that opened
+ // during the cooldown but happens to close just after expiry is NOT fresh evidence. Only
+ // windows that began fully after the cooldown ended count toward a streak, so a change
+ // requires two (or five) *complete* post-cooldown windows.
+ const cooledDown = windowStart - state.lastChangeAt >= config.cooldownMs;
// Observation freeze during cooldown: windows classified inside the cooldown do NOT
// bank a streak. Otherwise a streak accumulated while cooling would fire the instant
diff --git a/client/src/utils/cityRenderBudget.test.js b/client/src/utils/cityRenderBudget.test.js
index 35a89af239..98306097bc 100644
--- a/client/src/utils/cityRenderBudget.test.js
+++ b/client/src/utils/cityRenderBudget.test.js
@@ -71,6 +71,19 @@ describe('cityRenderBudget — warm-up & gap rejection (ignored samples)', () =>
expect(s.diagnostics.windows).toBe(0);
});
+ it('discards a partial window when a frame gap interrupts it', () => {
+ let s = createRenderBudget('high', 0);
+ // One valid sample past warm-up opens a window holding a single sample.
+ s = recordFrame(s, { now: CFG.warmupMs + 100, dt: 30 });
+ expect(s.samples.length).toBe(1);
+ // A long gap whose `now` is past windowMs must NOT classify the 1-sample window.
+ s = recordFrame(s, { now: CFG.warmupMs + 100 + CFG.windowMs + 500, dt: CFG.windowMs + 500 });
+ expect(s.windowClosed).toBe(false);
+ expect(s.diagnostics.windows).toBe(0);
+ expect(s.pressureStreak).toBe(0);
+ expect(s.samples.length).toBe(0);
+ });
+
it('starts the window clock at the first post-warm-up sample (full first window)', () => {
// The budget resets at t=0 but the first real frame lands well after warm-up. The
// first classified window must still span a full windowMs of samples, not close