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

Merge remote-tracking branch 'origin/main' into claim/issue-2592

[._.]/ Adam Eivy5c61b19dae36
diff --cc .changelog/NEXT.md
index 3367a6e1ed,095bce0443..26d982782c
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@@ -7,7 -14,9 +14,10 @@@
## 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-2592] Add an adaptive render budget and visibility-aware frameloop to CyberCity.** City gains an **Auto quality mode** (City Settings → Performance): 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); sustained sub-cutoff frames still downshift via a synthetic pressure window. 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 Performance tab shows the effective tier (`AUTO · HIGH`) plus a local-only diagnostics readout (tier, FPS, p75) that is never persisted or transmitted, and disables the Auto-controlled Reflections/Particle-density fields. New unit tests cover downshift, recovery, cooldown, ignored samples (warm-up/gap), sustained slowness, storage compatibility, Manual mode, and visibility transitions.
+ - **[issue-2591] Responsive City HUD + City settings on the shared Drawer.** The CyberCity HUD now adapts to the viewport instead of stacking every desktop panel on top of the 3D scene at phone width. A new `useCityViewport` hook brackets the window into desktop (≥1024, unchanged cockpit), compact (640–1023) and phone (<640); below desktop the HUD collapses to a small clock/health chip, a status chip and a bottom dock of 44×44 launchers, keeping ≥70% of the scene unobscured on load. Secondary surfaces (vitals, attention, timeline, activity, map, filter, legend) open as ONE mutually-exclusive disclosure sheet driven by a `cityPane` URL param, so only one shows at a time and the open one is deep-linkable, reload-safe and restored by browser back/forward (the desktop Intel pane's active tab reads the same param). City settings moved off the bespoke bottom-right scroller onto the shared tabbed `Drawer` (`size="sm"`, Performance/Audio/Visual/Explore, active tab deep-linked via `useDrawerTab`'s `cityTab` param, `TabPills` mobile dropdown), preserving the `/city/settings` route.
+
+ - **[issue-2550] Add direct unit tests for `telegramClient`, the telegram service, and `errorHandler.asyncHandler`.** Three previously under-covered modules gain colocated `*.test.js` suites, all driven with an injected/mock `fetch` (no network): `server/lib/telegramClient.test.js` now covers the poll loop (getUpdates dispatch to matching/non-matching `onText` + `message`/`callback_query` listeners, offset advance, `stopPolling` abort, and non-ok retry via fake timers) and the `apiCall` methods (`getMe`/`sendMessage` happy path, `reply_markup` string→object parse, non-ok throw); a new `server/services/telegram.test.js` exercises the token-bucket rate limiter (30-message cap then `Rate limit exceeded`) and unauthorized-chat rejection (message/command/callback_query paths) through `init()` with all deps mocked; and `server/lib/errorHandler.test.js` adds `asyncHandler` coverage (thrown ServerError → status+body+emit, plain Error → 500 normalization, success no-op, and the no-io path). Test-only change — no runtime behavior change.
- **[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 --cc client/src/components/city/CitySettingsDrawer.jsx
index 23d0eb5d11,47967cf54b..01b5b9d010
--- a/client/src/components/city/CitySettingsDrawer.jsx
+++ b/client/src/components/city/CitySettingsDrawer.jsx
@@@ -2,48 -3,42 +3,43 @@@ import useDrawerTab from '../../hooks/u
import { useCitySettingsContext } from './CitySettingsContext';
import { QUALITY_PRESETS } from '../../hooks/useCitySettings';
- function HudCorner({ position = 'tl', color = 'cyan' }) {
- const corners = {
- tl: 'top-0 left-0 border-t border-l',
- tr: 'top-0 right-0 border-t border-r',
- bl: 'bottom-0 left-0 border-b border-l',
- br: 'bottom-0 right-0 border-b border-r',
- };
- return (
- <div
- className={`absolute w-2 h-2 ${corners[position]} border-${color}-400/60`}
- style={{ borderWidth: '1px' }}
- />
- );
- }
+ // City settings migrated onto the shared tabbed <Drawer> (issue #2591) — replaces
+ // the old bespoke bottom-right 19rem page-length scroller. Grouped into
+ // Performance / Audio / Visual / Explore so no single tab is a long scroll, with the
+ // active tab deep-linked through the `cityTab` URL param (useDrawerTab). All mutable
+ // state lives in CitySettingsContext ABOVE this remounting body, so switching tabs
+ // (which remounts the body) never drops an edit.
- function SettingToggle({ label, value, onChange, description, disabled = false }) {
-function SettingToggle({ id, label, value, onChange, description }) {
++function SettingToggle({ id, label, value, onChange, description, disabled = false }) {
return (
- <div className={`flex items-center justify-between py-1.5 group ${disabled ? 'opacity-40' : ''}`} title={description}>
- <span className="font-pixel text-[10px] text-gray-400 tracking-wide group-hover:text-gray-300 transition-colors">
- <div className="flex items-center justify-between py-2 group" title={description}>
- <label htmlFor={id} className="font-pixel text-[11px] text-gray-300 tracking-wide cursor-pointer">
++ <div className={`flex items-center justify-between py-2 group ${disabled ? 'opacity-40' : ''}`} title={description}>
++ <label htmlFor={id} className={`font-pixel text-[11px] text-gray-300 tracking-wide ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}>
{label}
- </span>
+ </label>
<button
- onClick={() => !disabled && onChange(!value)}
+ id={id}
+ type="button"
+ role="switch"
+ aria-checked={value}
+ aria-label={label}
- onClick={() => onChange(!value)}
- className={`w-11 h-6 rounded-full relative transition-colors border ${value ? 'bg-cyan-500/40 border-cyan-500/60' : 'bg-gray-700/40 border-gray-600/40'}`}
+ disabled={disabled}
- className={`w-9 h-5 rounded-full relative transition-colors ${value ? 'bg-cyan-500/40 border-cyan-500/60' : 'bg-gray-700/40 border-gray-600/40'} border ${disabled ? 'cursor-not-allowed' : ''}`}
++ onClick={() => !disabled && onChange(!value)}
++ className={`w-11 h-6 rounded-full relative transition-colors border ${value ? 'bg-cyan-500/40 border-cyan-500/60' : 'bg-gray-700/40 border-gray-600/40'} ${disabled ? 'cursor-not-allowed' : ''}`}
>
- <div
- className={`absolute top-0.5 w-3 h-3 rounded-full transition-all ${value ? 'left-[16px] bg-cyan-400 shadow-[0_0_6px_rgba(6,182,212,0.5)]' : 'left-[2px] bg-gray-500'}`}
+ <span
+ className={`absolute top-0.5 w-4 h-4 rounded-full transition-all ${value ? 'left-[22px] bg-cyan-400 shadow-[0_0_6px_rgba(6,182,212,0.5)]' : 'left-[2px] bg-gray-500'}`}
/>
</button>
</div>
);
}
- function SettingSlider({ label, value, onChange, min = 0, max = 1, step = 0.05, format, description, disabled = false }) {
- const displayValue = format
- ? format(value)
- : `${Math.round(value * 100)}%`;
-function SettingSlider({ id, label, value, onChange, min = 0, max = 1, step = 0.05, format, description }) {
++function SettingSlider({ id, label, value, onChange, min = 0, max = 1, step = 0.05, format, description, disabled = false }) {
+ const displayValue = format ? format(value) : `${Math.round(value * 100)}%`;
return (
- <div className={`py-1.5 ${disabled ? 'opacity-40' : ''}`} title={description}>
- <div className="flex items-center justify-between mb-1">
- <span className="font-pixel text-[10px] text-gray-400 tracking-wide">{label}</span>
- <div className="py-2" title={description}>
++ <div className={`py-2 ${disabled ? 'opacity-40' : ''}`} title={description}>
+ <div className="flex items-center justify-between mb-1.5">
+ <label htmlFor={id} className="font-pixel text-[11px] text-gray-300 tracking-wide">{label}</label>
<span className="font-pixel text-[10px] text-cyan-400/70">{displayValue}</span>
</div>
<input
@@@ -52,9 -48,9 +49,10 @@@
max={max}
step={step}
value={value}
+ disabled={disabled}
onChange={(e) => onChange(parseFloat(e.target.value))}
- className={`w-full h-1.5 bg-gray-700 rounded-full appearance-none accent-cyan-500 ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}
+ aria-label={label}
- className="w-full h-2 bg-gray-700 rounded-full appearance-none cursor-pointer accent-cyan-500"
++ className={`w-full h-2 bg-gray-700 rounded-full appearance-none accent-cyan-500 ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}
style={{
background: `linear-gradient(to right, #06b6d4 0%, #06b6d4 ${(value - min) / (max - min) * 100}%, #374151 ${(value - min) / (max - min) * 100}%, #374151 100%)`,
}}
@@@ -101,102 -97,68 +99,111 @@@ function SectionHeader({ title, subtitl
);
}
+ export const CITY_SETTINGS_TABS = [
+ { id: 'performance', label: 'Performance' },
+ { id: 'audio', label: 'Audio' },
+ { id: 'visual', label: 'Visual' },
+ { id: 'explore', label: 'Explore' },
+ ];
+ const TAB_IDS = CITY_SETTINGS_TABS.map(t => t.id);
+
-export default function CitySettingsDrawer({ open, onClose }) {
+// 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();
++export default function CitySettingsDrawer({ open, onClose, qualityMode = 'manual', effectiveTier = 'high', diagnostics = null }) {
const { settings, updateSetting, resetSettings } = useCitySettingsContext();
+ const [activeTab, setActiveTab] = useDrawerTab('cityTab', 'performance', TAB_IDS);
- if (!settings) return null;
+ if (!open || !settings) return null;
++ // Auto quality mode (#2592). 'auto' engages the adaptive render budget; picking a named
++ // preset pins Manual (handled in useCitySettings). In Auto the scene derives reflections +
++ // particle density from the effective tier, so those (disabled) controls display the
++ // effective preset's values and follow live tier changes rather than a stale manual value.
+ const isAuto = qualityMode === 'auto';
- const modeLabel = isAuto
- ? `AUTO · ${String(effectiveTier).toUpperCase()}`
- : `MANUAL · ${String(settings.qualityPreset || 'high').toUpperCase()}`;
-
++ const effectivePreset = isAuto ? (QUALITY_PRESETS[effectiveTier] || QUALITY_PRESETS.high) : null;
++ const reflectionsValue = effectivePreset ? effectivePreset.reflectionsEnabled : settings.reflectionsEnabled;
++ const particleValue = effectivePreset ? effectivePreset.particleDensity : settings.particleDensity;
+ 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);
+ };
+
- // In Auto mode the scene derives reflections + particle density from the effective
- // tier, not the saved manual values — so the (disabled) controls display the effective
- // preset's values and follow live tier changes rather than showing a stale manual value.
- const effectivePreset = isAuto ? (QUALITY_PRESETS[effectiveTier] || QUALITY_PRESETS.high) : null;
- const reflectionsValue = effectivePreset ? effectivePreset.reflectionsEnabled : settings.reflectionsEnabled;
- const particleValue = effectivePreset ? effectivePreset.particleDensity : settings.particleDensity;
-
return (
- <div className="absolute bottom-4 right-4 z-50 pointer-events-auto animate-in slide-in-from-bottom-4 duration-300">
- <div
- className="relative bg-black/92 backdrop-blur-md border border-cyan-500/35 rounded-lg w-76 max-h-[80vh] overflow-y-auto"
- style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(6,182,212,0.2) transparent', width: '19rem' }}
- >
- <HudCorner position="tl" />
- <HudCorner position="tr" />
- <HudCorner position="bl" />
- <HudCorner position="br" />
-
- {/* Header */}
- <div className="sticky top-0 z-10 bg-black/95 flex items-center justify-between px-4 py-3 border-b border-cyan-500/25">
- <span className="font-pixel text-[12px] text-cyan-400 tracking-widest" style={{ textShadow: '0 0 8px rgba(6,182,212,0.4)' }}>
- SETTINGS
- </span>
- <button
- onClick={() => navigate('/city')}
- className="font-pixel text-[11px] text-gray-500 hover:text-cyan-400 transition-colors tracking-wide w-8 h-8 flex items-center justify-center rounded hover:bg-cyan-500/10"
- >
- [X]
- </button>
- </div>
-
- <div className="px-4 py-3 space-y-5">
- {/* Quality */}
+ <Drawer
+ open={open}
+ onClose={onClose}
+ title="City Settings"
+ size="sm"
+ tabs={CITY_SETTINGS_TABS}
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ closeLabel="Close city settings"
+ >
+ {activeTab === 'performance' && (
+ <div className="space-y-5">
<div>
- <SectionHeader title="QUALITY" subtitle={modeLabel} />
- {/* AUTO adapts the effective tier to sustained frame pressure. */}
- <SectionHeader title="QUALITY PRESET" subtitle="Controls overall visual fidelity" />
++ <SectionHeader
++ title="QUALITY"
++ subtitle={isAuto ? `AUTO · ${String(effectiveTier).toUpperCase()}` : `MANUAL · ${String(settings.qualityPreset || 'high').toUpperCase()}`}
++ />
++ {/* AUTO adapts the effective tier to sustained frame pressure (#2592). */}
+ <button
++ type="button"
++ aria-pressed={isAuto}
+ onClick={() => setQuality('auto')}
- className={`w-full font-pixel text-[9px] py-2 mb-1.5 rounded border transition-all tracking-wide ${
++ className={`w-full font-pixel text-[10px] min-h-[44px] 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'
++ : 'bg-gray-800/40 border-gray-700/40 text-gray-400 hover:border-gray-600 hover:text-gray-300'
+ }`}
+ >
+ AUTO {isAuto ? `· ${String(effectiveTier).toUpperCase()}` : ''}
+ </button>
- <div className="grid grid-cols-4 gap-1.5">
+ <div className="grid grid-cols-4 gap-1.5" role="group" aria-label="Quality preset">
{Object.keys(QUALITY_PRESETS).map(preset => (
<button
key={preset}
+ type="button"
- aria-pressed={settings.qualityPreset === preset}
- onClick={() => updateSetting('qualityPreset', preset)}
++ aria-pressed={!isAuto && settings.qualityPreset === preset}
+ onClick={() => setQuality(preset)}
- className={`font-pixel text-[9px] py-2 rounded border transition-all tracking-wide ${
+ className={`font-pixel text-[10px] min-h-[44px] 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'
+ : 'bg-gray-800/40 border-gray-700/40 text-gray-400 hover:border-gray-600 hover:text-gray-300'
}`}
>
{preset.toUpperCase()}
</button>
))}
</div>
- {/* Local-only diagnostics — never persisted or transmitted (issue #2592). */}
++ {/* Local-only diagnostics — never persisted or transmitted (#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">
++ <div className="mt-2 px-2 py-1.5 rounded bg-black/40 border border-cyan-500/10 font-pixel text-[9px] text-gray-400 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>
+ <SettingSlider
+ id="city-particle-density"
+ label="PARTICLE DENSITY"
- value={settings.particleDensity}
++ value={particleValue}
+ onChange={(v) => updateSetting('particleDensity', v)}
+ min={0.25}
+ max={2}
+ step={0.25}
- description="Amount of floating particles in the scene"
++ description={isAuto ? 'Set automatically by Auto quality' : 'Amount of floating particles in the scene'}
++ disabled={isAuto}
+ />
+ </div>
+ )}
- <div className="border-t border-cyan-500/10" />
-
- {/* Music */}
+ {activeTab === 'audio' && (
+ <div className="space-y-5">
<div>
<SectionHeader title="MUSIC" subtitle="Procedural synthwave background" />
<SettingToggle
@@@ -233,20 -197,22 +242,23 @@@
/>
)}
</div>
+ </div>
+ )}
- <div className="border-t border-cyan-500/10" />
-
- {/* Visual Effects */}
+ {activeTab === 'visual' && (
+ <div className="space-y-5">
<div>
- <SectionHeader title="VISUAL FX" subtitle={isAuto ? 'Reflections + density controlled by Auto' : 'Reflections and atmosphere'} />
+ <SectionHeader title="VISUAL FX" subtitle="Reflections and atmosphere" />
<SettingToggle
+ id="city-reflections"
label="REFLECTIONS"
- value={settings.reflectionsEnabled}
+ value={reflectionsValue}
onChange={(v) => updateSetting('reflectionsEnabled', v)}
- description="Wet street reflections and puddles"
+ description={isAuto ? 'Set automatically by Auto quality' : 'Wet street reflections and puddles'}
+ disabled={isAuto}
/>
<SettingToggle
+ id="city-scanlines"
label="SCANLINES"
value={settings.scanlineOverlay}
onChange={(v) => updateSetting('scanlineOverlay', v)}
diff --cc client/src/components/city/CitySettingsDrawer.test.jsx
index 0000000000,ba06feb943..717cf50d6f
mode 000000,100644..100644
--- a/client/src/components/city/CitySettingsDrawer.test.jsx
+++ b/client/src/components/city/CitySettingsDrawer.test.jsx
@@@ -1,0 -1,64 +1,86 @@@
+ import { describe, it, expect, vi } from 'vitest';
+ import { render, screen, fireEvent } from '@testing-library/react';
+ import { MemoryRouter, useLocation } from 'react-router-dom';
+ import CitySettingsDrawer from './CitySettingsDrawer';
+ import { CitySettingsProvider } from './CitySettingsContext';
+
+ function Loc() {
+ const l = useLocation();
+ return <div data-testid="loc">{l.search}</div>;
+ }
+
+ const renderDrawer = (search = '', onClose = () => {}) =>
+ render(
+ <MemoryRouter initialEntries={[`/city/settings${search}`]}>
+ <CitySettingsProvider>
+ <CitySettingsDrawer open onClose={onClose} />
+ </CitySettingsProvider>
+ <Loc />
+ </MemoryRouter>,
+ );
+
+ describe('CitySettingsDrawer', () => {
+ it('renders the shared Drawer with the four grouped tabs', () => {
+ renderDrawer();
+ expect(screen.getByRole('dialog', { name: 'City Settings' })).toBeInTheDocument();
+ ['Performance', 'Audio', 'Visual', 'Explore'].forEach(label => {
+ expect(screen.getByRole('tab', { name: label })).toBeInTheDocument();
+ });
+ // Default tab content.
- expect(screen.getByText('QUALITY PRESET')).toBeInTheDocument();
++ expect(screen.getByText('QUALITY')).toBeInTheDocument();
+ });
+
+ it('switches tabs and persists the active tab in the URL', () => {
+ renderDrawer();
+ fireEvent.click(screen.getByRole('tab', { name: 'Audio' }));
+ expect(screen.getByText('MUSIC')).toBeInTheDocument();
- expect(screen.queryByText('QUALITY PRESET')).not.toBeInTheDocument();
++ expect(screen.queryByText('QUALITY')).not.toBeInTheDocument();
+ expect(screen.getByTestId('loc').textContent).toContain('cityTab=audio');
+ });
+
++ it('shows the Auto effective-tier label and local diagnostics when in Auto mode', () => {
++ render(
++ <MemoryRouter initialEntries={['/city/settings']}>
++ <CitySettingsProvider>
++ <CitySettingsDrawer
++ open
++ onClose={() => {}}
++ qualityMode="auto"
++ effectiveTier="medium"
++ diagnostics={{ fps: 58, p75: 16.2 }}
++ />
++ </CitySettingsProvider>
++ </MemoryRouter>,
++ );
++ // AUTO button reflects the effective tier, and the local diagnostics readout renders.
++ expect(screen.getByRole('button', { name: /AUTO · MEDIUM/ })).toHaveAttribute('aria-pressed', 'true');
++ expect(screen.getByText('58 FPS')).toBeInTheDocument();
++ expect(screen.getByText('P75 16.2ms')).toBeInTheDocument();
++ // The Auto-controlled particle-density slider is disabled.
++ expect(screen.getByLabelText('PARTICLE DENSITY')).toBeDisabled();
++ });
++
+ it('deep-links the active tab from the URL param', () => {
+ renderDrawer('?cityTab=visual');
+ expect(screen.getByText('VISUAL FX')).toBeInTheDocument();
+ expect(screen.getByRole('tab', { name: 'Visual', selected: true })).toBeInTheDocument();
+ });
+
+ it('invokes onClose from the Drawer close control', () => {
+ const onClose = vi.fn();
+ renderDrawer('', onClose);
+ fireEvent.click(screen.getByRole('button', { name: 'Close city settings' }));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it('renders nothing when closed', () => {
+ const { container } = render(
+ <MemoryRouter initialEntries={['/city']}>
+ <CitySettingsProvider>
+ <CitySettingsDrawer open={false} onClose={() => {}} />
+ </CitySettingsProvider>
+ </MemoryRouter>,
+ );
+ expect(container.querySelector('[role="dialog"]')).toBeNull();
+ });
+ });
diff --cc client/src/pages/CyberCity.jsx
index 22dc436bfb,e4cc6eecc3..6bd2777bb1
--- a/client/src/pages/CyberCity.jsx
+++ b/client/src/pages/CyberCity.jsx
@@@ -13,8 -13,7 +13,8 @@@ import CityScanlines from '../component
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 CitySettingsDrawer from '../components/city/CitySettingsDrawer';
import { computeFilterResult } from '../utils/cityFilter';
import { DEFAULT_PRESET_ID, cyclePreset } from '../utils/cityPhotoMode';
import { computeSoundscape } from '../utils/citySoundscape';
@@@ -468,13 -435,9 +468,16 @@@ function CyberCityInner()
onExit={playback.exit}
/>
<CityScanlines settings={settings} crt={cityPalette.crt} />
- {showSettings && (
- <CitySettingsPanel
- qualityMode={qualityMode}
- effectiveTier={effectiveTier}
- diagnostics={qualityMode === 'auto' ? autoDiagnostics : null}
- />
- )}
+ {/* Settings on the shared Drawer (issue #2591). Closing preserves other query
- params (e.g. an open cityPane) so the disclosure state survives. */}
- <CitySettingsDrawer open={showSettings} onClose={() => navigate(`/city${location.search}`)} />
++ params (e.g. an open cityPane) so the disclosure state survives. The Auto-quality
++ props (#2592) drive the Performance tab's effective-tier label + local diagnostics. */}
++ <CitySettingsDrawer
++ open={showSettings}
++ onClose={() => navigate(`/city${location.search}`)}
++ qualityMode={qualityMode}
++ effectiveTier={effectiveTier}
++ diagnostics={qualityMode === 'auto' ? autoDiagnostics : null}
++ />
</div>
</CityPaletteProvider>
);