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: URL-addressable building focus mode in City (#2593)

Adam Eivy7881b22e06c9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d3ff52d053..b8edac7648 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -9,6 +9,8 @@
## Added
+- **[issue-2593] URL-addressable building focus mode in City.** Clicking a building, minimap marker, or search match now focuses it in place at `/city/apps/:appId` instead of leaving City for `/apps/:id` — the camera flies to frame the whole borough (aspect- and HUD-safe-area aware, guarded against intersecting geometry) and the Intel pane is replaced (never overlapped) by a building-detail panel showing status, a process summary with unhealthy processes, and the app's active agents, plus an explicit **Open app** action to the real detail page and a **Close** back to the overview. The focused borough is visually distinguished (accent selection ring + expanded hologram) and its minimap dot exposes `aria-current` to assistive tech. Because the selection lives in the URL, reload/deep-link restores it once positions load, and browser back/forward moves between focused buildings and the overview; stale/deleted ids get an inline "building not found" fallback with a return-to-overview action. Entering Photo, History, or Drop In while focused deterministically clears focus first. On compact viewports the details render as the responsive HUD bottom sheet. New pure helpers `cityFocusCamera` (framing math, unit-tested) and `cityFocusState` (route-param resolution, unit-tested); new `CityFocusCamera` (in-canvas controller) and `CityFocusPanel` components.
+
- **[issue-2610] LLM personality self-profile testing with digital-twin alignment scoring.** New **Digital Twin → Personality** tab (also reachable via ⌘K and voice): pick one or more provider/models and run a single-prompt deep introspective self-evaluation that returns a structured personality profile — agreeableness, humor, error aversion, self-censorship, conciseness, dogmatism, sycophancy, creativity, formality, empathy — each scored 0–100% with the model's own rationale, plus a plain-language summary. An optional follow-up check scores how well that posture aligns with your twin's analyzed traits (Big Five, communication profile, values), with per-dimension notes; it's skipped with a clear message when the twin has no analyzed traits yet. Results render on a radar chart, persist as capped local history (survives restart, delete per entry), and any 2+ past runs can be overlaid on one radar with a side-by-side score table to compare models or track one model over time. The scorer provider/model, history cap, and default alignment toggle are configurable in the tab's Options; both prompts are editable stage templates like any other. Calls fire only from the explicit Run action — never at boot or in the background.
- **First-run tutorial for POST cognitive drills.** The timed, stimulus-driven cognitive drills (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) start flashing a stimulus the instant they mount, which is disorienting the first time you meet one. Each drill type now shows a one-time how-to card — a plain-language goal, numbered steps, and the controls — the first time it's encountered, and holds the drill (and its timers) until you tap **Start drill**. The card is config-aware (it names the n-back lag, the digit-span direction, and the reaction-time mode), then never shows again for that type (tracked per type in `localStorage`). Non-timed drills (math/memory, LLM/verbal) are self-explanatory and are not gated.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 7a95434037..19f1ff2e58 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -298,6 +298,7 @@ export default function App() {
<Route path="devtools/jira/reports" element={<JiraReports />} />
<Route path="city" element={<CyberCity />} />
<Route path="city/settings" element={<CyberCity />} />
+ <Route path="city/apps/:appId" element={<CyberCity />} />
<Route path="data" element={<DataManager />} />
<Route path="character" element={<CharacterSheet />} />
<Route path="ask" element={<Ask />} />
diff --git a/client/src/components/city/Borough.jsx b/client/src/components/city/Borough.jsx
index 005fa4f670..2d933426ae 100644
--- a/client/src/components/city/Borough.jsx
+++ b/client/src/components/city/Borough.jsx
@@ -5,7 +5,7 @@ import Building from './Building';
import AgentEntity from './AgentEntity';
import ProcessBuilding from './ProcessBuilding';
-export default function Borough({ app, position, agentMap, onBuildingClick, playSfx, neonBrightness, isProximity, dimmed = false, settings, playback = false, transitionState = null, onExited }) {
+export default function Borough({ app, position, agentMap, onBuildingClick, playSfx, neonBrightness, isProximity, focused = false, dimmed = false, settings, playback = false, transitionState = null, onExited }) {
const agentData = agentMap.get(app.id);
const agents = agentData?.agents || [];
const height = getBuildingHeight(app);
@@ -50,6 +50,7 @@ export default function Borough({ app, position, agentMap, onBuildingClick, play
interiorWindows={cityShowInteriorWindows(settings)}
neonBrightness={neonBrightness}
isProximity={isProximity}
+ focused={focused}
dimmed={dimmed}
dayMix={dayMix}
playback={playback}
diff --git a/client/src/components/city/Building.jsx b/client/src/components/city/Building.jsx
index 6218335f5c..917db52a23 100644
--- a/client/src/components/city/Building.jsx
+++ b/client/src/components/city/Building.jsx
@@ -394,7 +394,7 @@ function FloorLightBands({ width, depth, height, color, accentColor, seed, dimMu
);
}
-export default function Building({ app, position, agentCount, onClick, playSfx, neonBrightness = 1.2, isProximity = false, dimmed = false, dayMix = 0, playback = false, transitionState = null, onExited, rooftops = true, interiorWindows = false }) {
+export default function Building({ app, position, agentCount, onClick, playSfx, neonBrightness = 1.2, isProximity = false, focused = false, dimmed = false, dayMix = 0, playback = false, transitionState = null, onExited, rooftops = true, interiorWindows = false }) {
const meshRef = useRef();
const glowRef = useRef();
const haloRef = useRef();
@@ -689,6 +689,16 @@ export default function Building({ app, position, agentCount, onClick, playSfx,
{displayName}
</CityLabel>
+ {/* Focus selection ring (issue #2593) — a bright accent ring at the base marking the
+ URL-focused borough. Rendered day AND night (unlike the neon glow) so the selected
+ building is unambiguously distinguished in any lighting. */}
+ {focused && (
+ <mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.04, 0]}>
+ <ringGeometry args={[Math.max(width, depth) * 0.9 + 0.6, Math.max(width, depth) * 0.9 + 0.95, 48]} />
+ <meshBasicMaterial color={accentColor} transparent opacity={0.95} side={THREE.DoubleSide} />
+ </mesh>
+ )}
+
{/* Base glow circle - wider and brighter (night only) */}
{!daytime && (
<mesh ref={glowRef} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.01, 0]}>
@@ -739,12 +749,12 @@ export default function Building({ app, position, agentCount, onClick, playSfx,
/>
)}
- {!dimmed && (hovered || isOnline || app.archived || isProximity) && (
+ {!dimmed && (hovered || isOnline || app.archived || isProximity || focused) && (
<HolographicPanel
app={app}
agentCount={agentCount}
position={[0, height + 1.8, 0]}
- expanded={isProximity}
+ expanded={isProximity || focused}
/>
)}
</group>
diff --git a/client/src/components/city/BuildingCluster.jsx b/client/src/components/city/BuildingCluster.jsx
index b72c9eefb3..eba607e497 100644
--- a/client/src/components/city/BuildingCluster.jsx
+++ b/client/src/components/city/BuildingCluster.jsx
@@ -4,7 +4,7 @@ import { DISTRICT_PARAMS, PIXEL_FONT_URL, cityDayMix } from './cityConstants';
import Borough from './Borough';
import CityLabel from './CityLabel';
-export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPositionsReady, playSfx, settings, proximityAppId, dimmedAppIds, playback = false }) {
+export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPositionsReady, playSfx, settings, proximityAppId, dimmedAppIds, focusedAppId, playback = false }) {
const positions = useMemo(() => computeCityLayout(apps), [apps]);
const dayMix = cityDayMix(settings);
@@ -74,6 +74,7 @@ export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPos
playSfx={playSfx}
neonBrightness={settings?.neonBrightness ?? 1.2}
isProximity={proximityAppId === app.id}
+ focused={focusedAppId === app.id}
dimmed={dimmedAppIds?.has?.(app.id) || false}
settings={settings}
playback={playback}
diff --git a/client/src/components/city/CityFocusCamera.jsx b/client/src/components/city/CityFocusCamera.jsx
new file mode 100644
index 0000000000..d2a6567fae
--- /dev/null
+++ b/client/src/components/city/CityFocusCamera.jsx
@@ -0,0 +1,102 @@
+import { useRef, useEffect } from 'react';
+import { useThree, useFrame } from '@react-three/fiber';
+import * as THREE from 'three';
+import { smoothstep } from '../../utils/easing';
+import { computeFocusCamera } from '../../utils/cityFocusCamera';
+
+// In-canvas camera controller for CyberCity's building focus mode (issue #2593). When the
+// `/city/apps/:appId` route resolves to a placed building, it flies the orbital camera (and the
+// OrbitControls target) to frame that borough; when focus clears it flies back to the overview.
+//
+// Staleness / unmount safety: all motion runs inside useFrame, which is inherently frame-gated —
+// there is NO setTimeout, so a stale deferred emit is impossible. Retargeting to a newly-selected
+// building simply restarts the fly on the frame the id changes (`currentKeyRef`). The unmount
+// cleanup restores OrbitControls if we were mid-fly, so navigating away can't strand the controls
+// disabled.
+
+const OVERVIEW_POS = new THREE.Vector3(0, 25, 45);
+const OVERVIEW_TARGET = new THREE.Vector3(0, 0, 0);
+const DURATION = 0.85; // seconds
+
+// Approximate the camera's current look-at point from its facing (used as the fly's start target
+// when OrbitControls hasn't exposed one yet).
+const deriveLookAt = (camera) => {
+ const dir = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
+ return camera.position.clone().add(dir.multiplyScalar(10));
+};
+
+export default function CityFocusCamera({ focusedAppId, positions, orbitRef, active = true, hudSafe }) {
+ const { camera, size } = useThree();
+ // `null` = overview (no fly needed on a plain /city mount). A transition into/out of focus flips
+ // this and starts a fly.
+ const currentKeyRef = useRef(null);
+ const animRef = useRef(null);
+ const controlsWasEnabledRef = useRef(true);
+
+ useEffect(() => () => {
+ // Restore controls if we unmount mid-fly (e.g. entering exploration/photo mode).
+ const controls = orbitRef?.current;
+ if (controls && animRef.current) controls.enabled = controlsWasEnabledRef.current;
+ }, [orbitRef]);
+
+ useFrame((_, delta) => {
+ const controls = orbitRef?.current;
+
+ const wantFocus = active && typeof focusedAppId === 'string' && focusedAppId.length > 0;
+ const pos = wantFocus ? positions?.get?.(focusedAppId) : null;
+ // Focus wanted but the layout position isn't ready yet → hold and retry next frame.
+ if (wantFocus && !pos) return;
+ const key = wantFocus ? focusedAppId : null;
+
+ if (key !== currentKeyRef.current) {
+ currentKeyRef.current = key;
+ const startTarget = controls?.target ? controls.target.clone() : deriveLookAt(camera);
+
+ let endPos;
+ let endTarget;
+ if (key === null) {
+ endPos = OVERVIEW_POS.clone();
+ endTarget = OVERVIEW_TARGET.clone();
+ } else {
+ const aspect = size.height > 0 ? size.width / size.height : 1;
+ const fovDeg = camera.isPerspectiveCamera ? camera.fov : undefined;
+ const framed = computeFocusCamera({ building: pos, aspect, fovDeg, hudSafe });
+ endPos = new THREE.Vector3(...framed.position);
+ endTarget = new THREE.Vector3(...framed.target);
+ }
+
+ animRef.current = {
+ fromPos: camera.position.clone(),
+ fromTarget: startTarget,
+ toPos: endPos,
+ toTarget: endTarget,
+ t: 0,
+ };
+ // Take over from OrbitControls for the duration of the fly, remembering its prior state.
+ if (controls) {
+ controlsWasEnabledRef.current = controls.enabled;
+ controls.enabled = false;
+ }
+ }
+
+ const anim = animRef.current;
+ if (!anim) return; // settled — let the user orbit freely
+
+ anim.t = Math.min(1, anim.t + delta / DURATION);
+ const e = smoothstep(anim.t);
+ camera.position.lerpVectors(anim.fromPos, anim.toPos, e);
+ const tgt = new THREE.Vector3().lerpVectors(anim.fromTarget, anim.toTarget, e);
+ if (controls) controls.target.copy(tgt);
+ camera.lookAt(tgt);
+
+ if (anim.t >= 1) {
+ animRef.current = null;
+ if (controls) {
+ controls.enabled = controlsWasEnabledRef.current;
+ controls.update?.();
+ }
+ }
+ });
+
+ return null;
+}
diff --git a/client/src/components/city/CityFocusPanel.jsx b/client/src/components/city/CityFocusPanel.jsx
new file mode 100644
index 0000000000..2025233417
--- /dev/null
+++ b/client/src/components/city/CityFocusPanel.jsx
@@ -0,0 +1,179 @@
+import { useMemo } from 'react';
+
+// Building-detail panel shown while a borough is focused (issue #2593). It REPLACES the Intel pane
+// (desktop) / renders as a bottom sheet (compact) — never overlapping it — and surfaces the app's
+// live state from data CyberCity already has: status, process summary + unhealthy processes, and the
+// agents assigned to the app. Two explicit actions: Open app (routes to /apps/:id) and Close
+// (returns to the /city overview). Also renders the stale/deleted-id "not found" fallback.
+
+const STATUS_STYLES = {
+ online: { text: 'text-port-success', dot: 'bg-port-success', label: 'ONLINE' },
+ stopped: { text: 'text-port-error', dot: 'bg-port-error', label: 'STOPPED' },
+ not_started: { text: 'text-violet-400', dot: 'bg-violet-500', label: 'NOT STARTED' },
+ not_found: { text: 'text-gray-400', dot: 'bg-gray-500', label: 'NOT FOUND' },
+ unknown: { text: 'text-gray-400', dot: 'bg-gray-500', label: 'UNKNOWN' },
+};
+
+const UNHEALTHY = new Set(['errored', 'error', 'stopped', 'stopping']);
+
+function StatBlock({ label, value, tone = 'text-cyan-300' }) {
+ return (
+ <div className="bg-black/40 border border-cyan-500/20 rounded px-2 py-1.5">
+ <div className="font-pixel text-[8px] text-cyan-500/50 tracking-wider">{label}</div>
+ <div className={`font-pixel text-[13px] tracking-wide ${tone}`}>{value}</div>
+ </div>
+ );
+}
+
+export default function CityFocusPanel({ app, notFound = false, agents = [], onClose, onOpenApp, isDesktop = true }) {
+ // Desktop: occupy the Intel-pane slot. Compact: a bottom sheet above the dock.
+ const containerClass = isDesktop
+ ? 'absolute top-16 right-3 bottom-20 w-72 pointer-events-auto'
+ : 'absolute inset-x-2 bottom-16 pointer-events-auto';
+
+ const procSummary = useMemo(() => {
+ const status = app?.pm2Status || {};
+ const processes = Array.isArray(app?.processes) ? app.processes : [];
+ const total = processes.length || Object.keys(status).length;
+ const unhealthy = Object.entries(status)
+ .filter(([, s]) => UNHEALTHY.has(s?.status))
+ .map(([name, s]) => ({ name, status: s?.status }));
+ const online = Object.values(status).filter((s) => s?.status === 'online' || s?.status === 'running').length;
+ return { total, unhealthy, online };
+ }, [app?.pm2Status, app?.processes]);
+
+ const activeAgents = useMemo(
+ () => (Array.isArray(agents) ? agents : []).filter(
+ (a) => a && (a.status === 'running' || a.state === 'coding' || a.state === 'thinking' || a.state === 'investigating' || a.status === 'failed' || a.error)
+ ),
+ [agents]
+ );
+
+ if (notFound || !app) {
+ return (
+ <div className={containerClass}>
+ <div
+ className="bg-black/85 backdrop-blur-sm border border-port-warning/40 rounded-lg overflow-hidden flex flex-col"
+ role="region"
+ aria-label="Building not found"
+ >
+ <div className="px-3 py-6 text-center">
+ <div className="font-pixel text-[11px] text-port-warning tracking-wider mb-1">BUILDING NOT FOUND</div>
+ <div className="font-pixel text-[8px] text-gray-500 tracking-wide mb-4">
+ This app may have been archived or removed.
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ className="pointer-events-auto font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-3 py-2 hover:bg-cyan-500/10 transition-colors"
+ >
+ {'<'} RETURN TO OVERVIEW
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const statusKey = app.archived ? 'not_found' : (app.overallStatus || 'unknown');
+ const statusStyle = STATUS_STYLES[statusKey] || STATUS_STYLES.unknown;
+ const title = app.name || app.id;
+
+ return (
+ <div className={containerClass}>
+ <div
+ className={`${isDesktop ? 'h-full' : 'max-h-[55vh]'} bg-black/85 backdrop-blur-sm border border-cyan-500/40 rounded-lg overflow-hidden flex flex-col`}
+ role="region"
+ aria-label={`Focused building: ${title}`}
+ >
+ {/* Header: name + status + close */}
+ <div className="flex items-start gap-2 px-3 py-2 border-b border-cyan-500/20 shrink-0">
+ <div className="flex-1 min-w-0">
+ <div className="font-pixel text-[12px] text-cyan-300 tracking-wide truncate" title={title}>{title}</div>
+ <div className="flex items-center gap-1.5 mt-1">
+ <span className={`w-2 h-2 rounded-full ${statusStyle.dot} shadow-[0_0_4px_currentColor]`} aria-hidden="true" />
+ <span className={`font-pixel text-[9px] tracking-wider ${statusStyle.text}`}>{app.archived ? 'ARCHIVED' : statusStyle.label}</span>
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close focus and return to overview"
+ title="Close (return to overview)"
+ className="shrink-0 w-8 h-8 flex items-center justify-center text-gray-400 hover:text-cyan-400 transition-colors font-pixel text-[13px]"
+ >
+ ✕
+ </button>
+ </div>
+
+ {/* Body */}
+ <div className="flex-1 overflow-y-auto px-3 py-2.5 space-y-3" style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(6,182,212,0.2) transparent' }}>
+ {/* Process summary */}
+ <div>
+ <div className="font-pixel text-[8px] text-cyan-500/50 tracking-wider mb-1.5">PROCESSES</div>
+ <div className="grid grid-cols-3 gap-1.5">
+ <StatBlock label="TOTAL" value={procSummary.total} />
+ <StatBlock label="RUNNING" value={procSummary.online} tone="text-port-success" />
+ <StatBlock label="ISSUES" value={procSummary.unhealthy.length} tone={procSummary.unhealthy.length ? 'text-port-error' : 'text-cyan-300'} />
+ </div>
+ {procSummary.unhealthy.length > 0 && (
+ <ul className="mt-1.5 space-y-1">
+ {procSummary.unhealthy.map((p) => (
+ <li key={p.name} className="flex items-center gap-1.5 font-pixel text-[9px] tracking-wide text-port-error">
+ <span className="w-1.5 h-1.5 rounded-full bg-port-error shrink-0" aria-hidden="true" />
+ <span className="truncate" title={`${p.name} — ${p.status}`}>{p.name}</span>
+ <span className="text-gray-500 ml-auto shrink-0">{p.status}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+
+ {/* Active agents */}
+ <div>
+ <div className="font-pixel text-[8px] text-cyan-500/50 tracking-wider mb-1.5">
+ AGENTS {activeAgents.length > 0 && <span className="text-cyan-400">· {activeAgents.length}</span>}
+ </div>
+ {activeAgents.length === 0 ? (
+ <div className="font-pixel text-[9px] text-gray-500 tracking-wide">No agents assigned</div>
+ ) : (
+ <ul className="space-y-1">
+ {activeAgents.map((agent) => {
+ const id = agent.agentId || agent.id;
+ const failed = agent.status === 'failed' || agent.state === 'error' || agent.error;
+ const label = agent.task || agent.taskTitle || `Agent ${String(id || '').slice(0, 8)}`;
+ return (
+ <li key={id || label} className="flex items-center gap-1.5 font-pixel text-[9px] tracking-wide">
+ <span className={`w-1.5 h-1.5 rounded-full shrink-0 ${failed ? 'bg-port-error' : 'bg-cyan-400 animate-pulse'}`} aria-hidden="true" />
+ <span className={`truncate ${failed ? 'text-port-error' : 'text-cyan-300'}`} title={label}>{label}</span>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ </div>
+
+ {/* Footer actions */}
+ <div className="flex items-center gap-2 px-3 py-2 border-t border-cyan-500/20 shrink-0">
+ <button
+ type="button"
+ onClick={() => onOpenApp?.(app.id)}
+ className="flex-1 font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-2 py-2 hover:bg-cyan-500/10 transition-colors"
+ title="Open the app detail page"
+ >
+ OPEN APP {'>'}
+ </button>
+ <button
+ type="button"
+ onClick={onClose}
+ className="font-pixel text-[10px] text-gray-400 tracking-wider border border-cyan-500/20 rounded px-2 py-2 hover:text-cyan-400 hover:border-cyan-500/40 transition-colors"
+ title="Return to the city overview"
+ >
+ BACK
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/city/CityFocusPanel.test.jsx b/client/src/components/city/CityFocusPanel.test.jsx
new file mode 100644
index 0000000000..95409b1d9b
--- /dev/null
+++ b/client/src/components/city/CityFocusPanel.test.jsx
@@ -0,0 +1,61 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import CityFocusPanel from './CityFocusPanel';
+
+const app = {
+ id: 'alpha',
+ name: 'Alpha Service',
+ overallStatus: 'online',
+ processes: [{ name: 'web' }, { name: 'worker' }],
+ pm2Status: {
+ web: { status: 'online' },
+ worker: { status: 'errored' },
+ },
+};
+
+describe('CityFocusPanel', () => {
+ it('renders app name, status, process summary and unhealthy processes', () => {
+ render(<CityFocusPanel app={app} agents={[]} />);
+ expect(screen.getByText('Alpha Service')).toBeTruthy();
+ // Status pill reads ONLINE (unique — the process stat block uses RUNNING).
+ expect(screen.getByText('ONLINE')).toBeTruthy();
+ expect(screen.getByText('RUNNING')).toBeTruthy();
+ // The unhealthy worker process is listed.
+ expect(screen.getByText('worker')).toBeTruthy();
+ expect(screen.getByText('errored')).toBeTruthy();
+ });
+
+ it('lists active/failed agents assigned to the app', () => {
+ const agents = [
+ { agentId: 'a1', status: 'running', task: 'Refactor module' },
+ { agentId: 'a2', status: 'completed', task: 'Old done task' },
+ ];
+ render(<CityFocusPanel app={app} agents={agents} />);
+ expect(screen.getByText('Refactor module')).toBeTruthy();
+ // A completed (non-active) agent is filtered out.
+ expect(screen.queryByText('Old done task')).toBeNull();
+ });
+
+ it('fires onOpenApp with the app id from the explicit Open app action', () => {
+ const onOpenApp = vi.fn();
+ render(<CityFocusPanel app={app} agents={[]} onOpenApp={onOpenApp} />);
+ fireEvent.click(screen.getByTitle('Open the app detail page'));
+ expect(onOpenApp).toHaveBeenCalledWith('alpha');
+ });
+
+ it('fires onClose from the close and back actions', () => {
+ const onClose = vi.fn();
+ render(<CityFocusPanel app={app} agents={[]} onClose={onClose} />);
+ fireEvent.click(screen.getByLabelText('Close focus and return to overview'));
+ fireEvent.click(screen.getByTitle('Return to the city overview'));
+ expect(onClose).toHaveBeenCalledTimes(2);
+ });
+
+ it('renders the not-found fallback with a return-to-overview action', () => {
+ const onClose = vi.fn();
+ render(<CityFocusPanel app={null} notFound onClose={onClose} />);
+ expect(screen.getByText('BUILDING NOT FOUND')).toBeTruthy();
+ fireEvent.click(screen.getByText(/RETURN TO OVERVIEW/));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/components/city/CityHud.jsx b/client/src/components/city/CityHud.jsx
index 65d22bb63b..8b5235c966 100644
--- a/client/src/components/city/CityHud.jsx
+++ b/client/src/components/city/CityHud.jsx
@@ -1,6 +1,7 @@
import { useState, useEffect, useMemo, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import CityIntelPane from './CityIntelPane';
+import CityFocusPanel from './CityFocusPanel';
import CityAgentBar from './CityAgentBar';
import CityFilterBar from './CityFilterBar';
import CityXpBadge from './CityXpBadge';
@@ -67,7 +68,8 @@ function Crosshair() {
);
}
-export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, connected, apps, reviewCounts, instances, productivityData, systemHealth, notificationCounts, character, filter, onFilterChange, onJumpToFirst, matchCount, onToggleExploration, explorationMode, onSelectApp, onEnterPhotoMode, onEnterPlayback }) {
+export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, connected, apps, reviewCounts, instances, productivityData, systemHealth, notificationCounts, character, filter, onFilterChange, onJumpToFirst, matchCount, onToggleExploration, explorationMode, onSelectApp, onEnterPhotoMode, onEnterPlayback, focusedAppId, focusedApp, focusNotFound, focusAgents, onCloseFocus, onOpenApp }) {
+ const isFocused = Boolean(focusedApp || focusNotFound);
const navigate = useNavigate();
const location = useLocation();
const { isDesktop } = useCityViewport();
@@ -209,16 +211,28 @@ export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, con
</div>
</div>
- {/* Right side: Intel pane (Attention + Activity tabs) */}
- <CityIntelPane
- apps={apps}
- cosAgents={cosAgents}
- reviewCounts={reviewCounts}
- instances={instances}
- systemHealth={systemHealth}
- notificationCounts={notificationCounts}
- eventLogs={eventLogs}
- />
+ {/* Right side: focus detail panel while a borough is focused (issue #2593),
+ otherwise the Intel pane. The focus panel REPLACES the intel pane — never overlaps. */}
+ {isFocused ? (
+ <CityFocusPanel
+ app={focusedApp}
+ notFound={focusNotFound}
+ agents={focusAgents}
+ onClose={onCloseFocus}
+ onOpenApp={onOpenApp}
+ isDesktop
+ />
+ ) : (
+ <CityIntelPane
+ apps={apps}
+ cosAgents={cosAgents}
+ reviewCounts={reviewCounts}
+ instances={instances}
+ systemHealth={systemHealth}
+ notificationCounts={notificationCounts}
+ eventLogs={eventLogs}
+ />
+ )}
{/* Bottom: Agent status bar */}
<CityAgentBar cosAgents={cosAgents} agentMap={agentMap} />
@@ -229,7 +243,7 @@ export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, con
{/* Bottom-left: mini-map + Settings gear + legend + corner decoration */}
<div className="absolute bottom-16 left-3">
{/* Top-down mini-map of every building (roadmap 2.8) */}
- <CityMiniMap apps={apps} onSelectApp={onSelectApp} />
+ <CityMiniMap apps={apps} onSelectApp={onSelectApp} selectedAppId={focusedAppId} />
{/* Status legend */}
<div className="pointer-events-none mb-2 bg-black/70 backdrop-blur-sm border border-cyan-500/15 rounded-lg px-2.5 py-2 space-y-1">
@@ -348,6 +362,12 @@ export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, con
onSelectApp={onSelectApp}
onEnterPhotoMode={onEnterPhotoMode}
onEnterPlayback={onEnterPlayback}
+ focusedAppId={focusedAppId}
+ focusedApp={focusedApp}
+ focusNotFound={focusNotFound}
+ focusAgents={focusAgents}
+ onCloseFocus={onCloseFocus}
+ onOpenApp={onOpenApp}
/>
)}
diff --git a/client/src/components/city/CityHudCompact.jsx b/client/src/components/city/CityHudCompact.jsx
index 32cd23b3bb..f727233a0b 100644
--- a/client/src/components/city/CityHudCompact.jsx
+++ b/client/src/components/city/CityHudCompact.jsx
@@ -6,6 +6,7 @@ import { buildAttentionItems, CityIntelContent } from './CityIntelPane';
import CityVitalsList from './CityVitalsList';
import CityMiniMap from './CityMiniMap';
import CityFilterBar from './CityFilterBar';
+import CityFocusPanel from './CityFocusPanel';
import { CITY_PANE_IDS, CITY_INTEL_PANE_IDS, CITY_PANE_LABELS } from './cityPanes';
// A 44×44 dock control. `active`/`aria-pressed` mark a toggled disclosure launcher;
@@ -81,11 +82,18 @@ export default function CityHudCompact({
onSelectApp,
onEnterPhotoMode,
onEnterPlayback,
+ focusedAppId,
+ focusedApp,
+ focusNotFound,
+ focusAgents,
+ onCloseFocus,
+ onOpenApp,
}) {
const navigate = useNavigate();
const location = useLocation();
const [activePane, setActivePane] = useDrawerTab('cityPane', null, CITY_PANE_IDS);
const togglePane = (id) => setActivePane(activePane === id ? null : id);
+ const isFocused = Boolean(focusedApp || focusNotFound);
const items = useMemo(
() => buildAttentionItems({ apps, cosAgents, reviewCounts, instances, systemHealth, notificationCounts }),
@@ -106,7 +114,7 @@ export default function CityHudCompact({
}
if (activePane === 'map') {
return hasApps
- ? <div className="p-3 flex justify-center"><CityMiniMap apps={apps} onSelectApp={onSelectApp} alwaysShow /></div>
+ ? <div className="p-3 flex justify-center"><CityMiniMap apps={apps} onSelectApp={onSelectApp} selectedAppId={focusedAppId} alwaysShow /></div>
: <div className="p-6 text-center font-pixel text-[9px] text-cyan-500/40 tracking-wide">No buildings to map</div>;
}
if (activePane === 'filter') {
@@ -175,8 +183,21 @@ export default function CityHudCompact({
)}
</div>
+ {/* Focused building detail sheet (issue #2593) — replaces the disclosure sheet while a
+ borough is focused so the two never overlap. */}
+ {isFocused && (
+ <CityFocusPanel
+ app={focusedApp}
+ notFound={focusNotFound}
+ agents={focusAgents}
+ onClose={onCloseFocus}
+ onOpenApp={onOpenApp}
+ isDesktop={false}
+ />
+ )}
+
{/* Disclosure sheet — one surface at a time, above the dock */}
- {activePane && (
+ {!isFocused && activePane && (
<div className="absolute inset-x-2 bottom-16 pointer-events-auto">
<div className="bg-black/90 backdrop-blur-md border border-cyan-500/35 rounded-lg flex flex-col max-h-[55vh] overflow-hidden">
<div className="flex items-center justify-between pl-3 pr-1 py-1.5 border-b border-cyan-500/20 shrink-0">
diff --git a/client/src/components/city/CityMiniMap.jsx b/client/src/components/city/CityMiniMap.jsx
index 0ae0ec077f..898cdaf7b0 100644
--- a/client/src/components/city/CityMiniMap.jsx
+++ b/client/src/components/city/CityMiniMap.jsx
@@ -20,7 +20,7 @@ import { computeMiniMap } from '../../utils/cityMiniMap';
// Map box size in px. Fixed so the projection has a stable target on desktop.
const MAP_SIZE = 132;
-export default function CityMiniMap({ apps, onSelectApp, alwaysShow = false }) {
+export default function CityMiniMap({ apps, onSelectApp, selectedAppId = null, alwaysShow = false }) {
// Status colors track the theme accent for 'online' (the rest stay semantic), so a
// dot matches its building exactly. Read from the palette the city page provides.
const { getBuildingColor } = useCityPalette();
@@ -80,7 +80,8 @@ export default function CityMiniMap({ apps, onSelectApp, alwaysShow = false }) {
backgroundColor: color,
boxShadow: `0 0 4px ${color}`,
};
- const title = `${dot.name} — ${dot.status.replace(/_/g, ' ')}`;
+ const isSelected = selectedAppId != null && dot.id === selectedAppId;
+ const title = `${dot.name} — ${dot.status.replace(/_/g, ' ')}${isSelected ? ' (focused)' : ''}`;
if (onSelectApp) {
return (
@@ -90,7 +91,10 @@ export default function CityMiniMap({ apps, onSelectApp, alwaysShow = false }) {
onClick={() => onSelectApp({ id: dot.id })}
title={title}
aria-label={title}
- className="absolute w-1.5 h-1.5 rounded-full -translate-x-1/2 -translate-y-1/2 hover:scale-[2] hover:z-10 transition-transform focus:outline-none focus:ring-1 focus:ring-cyan-400"
+ aria-current={isSelected ? 'true' : undefined}
+ className={`absolute w-1.5 h-1.5 rounded-full -translate-x-1/2 -translate-y-1/2 hover:scale-[2] hover:z-10 transition-transform focus:outline-none focus:ring-1 focus:ring-cyan-400 ${
+ isSelected ? 'ring-2 ring-cyan-200 scale-[1.8] z-10' : ''
+ }`}
style={dotStyle}
/>
);
diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsx
index b0304181c4..9e4e4f9f54 100644
--- a/client/src/components/city/CityScene.jsx
+++ b/client/src/components/city/CityScene.jsx
@@ -45,6 +45,7 @@ import CityTransitLoop from './CityTransitLoop';
import CityEnergyOverlay from './CityEnergyOverlay';
import PlayerController from './PlayerController';
import CameraTransition from './CameraTransition';
+import CityFocusCamera from './CityFocusCamera';
import CityPhotoCamera from './CityPhotoCamera';
import CityDepthOfField from './CityDepthOfField';
import { cityDayMix } from './cityConstants';
@@ -53,7 +54,7 @@ import ErrorBoundary from '../ErrorBoundary';
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, focusedAppId, hudSafe, background, palette }) {
const [positions, setPositions] = useState(null);
const [proximityApp, setProximityApp] = useState(null);
const [transitioning, setTransitioning] = useState(false);
@@ -266,6 +267,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCam
settings={renderSettings}
proximityAppId={proximityApp?.id}
dimmedAppIds={dimmedAppIds}
+ focusedAppId={focusedAppId}
playback={playback}
/>
<CityDataStreams positions={positions} apps={apps} agentMap={agentMap} />
@@ -323,6 +325,18 @@ export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCam
active={explorationMode}
onTransitionComplete={handleTransitionComplete}
/>
+ {/* URL-addressed building focus (issue #2593). Mounted only in the orbital overview (not
+ exploration/photo, which own the camera). Placed AFTER CameraTransition so its per-frame
+ camera write wins during any brief overlap on load. */}
+ {!explorationMode && !photoMode && (
+ <CityFocusCamera
+ focusedAppId={focusedAppId}
+ positions={positions}
+ orbitRef={orbitRef}
+ active={!explorationMode && !photoMode}
+ hudSafe={hudSafe}
+ />
+ )}
<CityPhotoCamera active={photoMode} presetId={photoPresetId} onReady={onPhotoCaptureReady} composerRef={photoComposerRef} />
{/* Depth-of-field is photo-mode-only: mounting it here (never in the live dashboard) keeps the
extra composer render targets off the always-on frameloop. It stays mounted for the whole
diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsx
index e4cc6eecc3..99928716e6 100644
--- a/client/src/pages/CyberCity.jsx
+++ b/client/src/pages/CyberCity.jsx
@@ -1,5 +1,5 @@
import { useCallback, useState, useEffect, useMemo, useRef } from 'react';
-import { useNavigate, useLocation } from 'react-router-dom';
+import { useNavigate, useLocation, useParams } from 'react-router-dom';
import { useCityData } from '../hooks/useCityData';
import { useCityPlayback } from '../hooks/useCityPlayback';
import useCityAudio from '../hooks/useCityAudio';
@@ -15,6 +15,8 @@ import CityPlaybackOverlay from '../components/city/CityPlaybackOverlay';
import { CitySettingsProvider, useCitySettingsContext } from '../components/city/CitySettingsContext';
import CitySettingsDrawer from '../components/city/CitySettingsDrawer';
import { computeFilterResult } from '../utils/cityFilter';
+import { resolveCityFocus } from '../utils/cityFocusState';
+import useCityViewport from '../hooks/useCityViewport';
import { DEFAULT_PRESET_ID, cyclePreset } from '../utils/cityPhotoMode';
import { computeSoundscape } from '../utils/citySoundscape';
import { CITY_COLORS, deriveCityPalette, resolveCityTimeOfDay } from '../components/city/cityConstants';
@@ -38,6 +40,22 @@ function CyberCityInner() {
const { playSfx } = useCityAudio(settings, soundscape);
const navigate = useNavigate();
const location = useLocation();
+ const { appId } = useParams();
+ const { isDesktop } = useCityViewport();
+
+ // URL-addressed building focus (issue #2593). The `/city/apps/:appId` route param is the single
+ // source of truth for "which borough is focused" — reload/back-forward/deep-link all restore it.
+ const { hasFocus, focusedApp, notFound: focusNotFound } = useMemo(
+ () => resolveCityFocus(appId, apps, { loading }),
+ [appId, apps, loading],
+ );
+ const focusAgents = useMemo(() => agentMap?.get?.(appId)?.agents || [], [agentMap, appId]);
+ // HUD safe area the focus camera frames around: the detail panel sits on the right (desktop) or
+ // as a bottom sheet (compact), so keep the borough clear of it.
+ const focusHudSafe = useMemo(
+ () => (isDesktop ? { right: 0.28, bottom: 0 } : { right: 0, bottom: 0.5 }),
+ [isDesktop],
+ );
// CyberCity follows the active PortOS theme: the HUD recolors via the
// `cybercity-themed` CSS scope (see index.css) and the 3D scene's brand colors
@@ -96,9 +114,17 @@ function CyberCityInner() {
const showSettings = location.pathname === '/city/settings';
+ // Mode precedence (issue #2593): entering exploration/photo/history while a borough is focused
+ // clears the focused route first, so the focus camera + detail panel stand down deterministically
+ // before the new mode takes the camera. `hasFocus` reads the URL, the single source of truth.
+ const clearFocusRoute = useCallback(() => {
+ if (hasFocus) navigate('/city');
+ }, [hasFocus, navigate]);
+
const handleToggleExploration = useCallback(() => {
+ clearFocusRoute();
updateSetting('explorationMode', !settings?.explorationMode);
- }, [updateSetting, settings?.explorationMode]);
+ }, [clearFocusRoute, updateSetting, settings?.explorationMode]);
// V (in exploration mode) swaps the follow-camera character view and first person.
const handleToggleCameraView = useCallback(() => {
@@ -125,19 +151,21 @@ function CyberCityInner() {
// Entering photo mode leaves exploration + playback; they're mutually exclusive modes.
const enterPhotoMode = useCallback(() => {
+ clearFocusRoute();
updateSetting('explorationMode', false);
playback.exit();
setPhotoPresetId(DEFAULT_PRESET_ID);
setPhotoMode(true);
- }, [updateSetting, playback]);
+ }, [clearFocusRoute, updateSetting, playback]);
const exitPhotoMode = useCallback(() => setPhotoMode(false), []);
// Entering playback leaves photo + exploration mode.
const enterPlayback = useCallback(() => {
+ clearFocusRoute();
setPhotoMode(false);
updateSetting('explorationMode', false);
playback.enter();
- }, [updateSetting, playback]);
+ }, [clearFocusRoute, updateSetting, playback]);
// Esc exits photo mode; ←/→ cycle the framing preset; D toggles depth-of-field. Bound only while
// photo mode is on so it doesn't shadow other shortcuts. Ignores key events while typing.
@@ -277,19 +305,24 @@ function CyberCityInner() {
{ enabled: jiraAppsKey.length > 0 },
);
+ // Selecting a building focuses it in-place (issue #2593) — the URL becomes /city/apps/:id and the
+ // camera flies to frame the borough WITHOUT leaving City. In street-level exploration the old
+ // behavior stands (walking up to a building and interacting opens the app page).
const handleBuildingClick = useCallback((app) => {
- if (app?.id) {
- navigate(`/apps/${app.id}`);
- } else {
- navigate('/apps');
- }
- }, [navigate]);
+ if (!app?.id) return;
+ if (settings?.explorationMode) navigate(`/apps/${app.id}`);
+ else navigate(`/city/apps/${app.id}`);
+ }, [navigate, settings?.explorationMode]);
const handleJumpToFirst = useCallback(() => {
const first = filterResult.matches[0];
- if (first?.id) navigate(`/apps/${first.id}`);
+ if (first?.id) navigate(`/city/apps/${first.id}`);
}, [filterResult.matches, navigate]);
+ // Close focus → back to the plain overview. Open app → the existing app detail page (explicit).
+ const handleCloseFocus = useCallback(() => navigate('/city'), [navigate]);
+ const handleOpenApp = useCallback((id) => { if (id) navigate(`/apps/${id}`); }, [navigate]);
+
// Headline numbers baked onto a captured city postcard. Derived from data the page already
// has — no extra fetch. buildPostcardStats (in the overlay) omits absent/zero fields.
const photoStats = useMemo(() => {
@@ -380,6 +413,8 @@ function CyberCityInner() {
playSfx={playSfx}
keysRef={keysRef}
dimmedAppIds={filterResult.dimmed}
+ focusedAppId={appId || null}
+ hudSafe={focusHudSafe}
/>
{/* The full HUD hides in photo + playback mode so the view is clean; each
mode's overlay replaces it. */}
@@ -406,6 +441,12 @@ function CyberCityInner() {
onSelectApp={handleBuildingClick}
onEnterPhotoMode={enterPhotoMode}
onEnterPlayback={enterPlayback}
+ focusedAppId={appId || null}
+ focusedApp={focusedApp}
+ focusNotFound={focusNotFound}
+ focusAgents={focusAgents}
+ onCloseFocus={handleCloseFocus}
+ onOpenApp={handleOpenApp}
/>
)}
<CityPhotoOverlay
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index d1e686f56a..63b7e3b84a 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -77,6 +77,8 @@ its tunable constants and placement helpers.
| `cityEasterEggs` | Unlockable easter eggs from context (date/character/goals) → placements (`computeEasterEggs`). |
| `cityFederation` | Sync-peer reachability horizon: status color/opacity, bridge state, peer placement (`computeFederationHorizon`). |
| `cityFilter` | Status-filter definitions and app-filtering result (`computeFilterResult`). |
+| `cityFocusCamera` | Pure camera-framing math for building focus mode: orbital `position`/`target` that frame one borough for a given aspect ratio + HUD safe area (`computeFocusCamera`). |
+| `cityFocusState` | Resolve the `/city/apps/:appId` route param + app list into `{ hasFocus, focusedApp, notFound }`, deferring the not-found flag until apps finish loading (`resolveCityFocus`). |
| `cityFlowLines` | Inter-building flow-line connections between active/agent nodes (`computeFlowConnections`). |
| `cityGoalMonuments` | Goal monuments & forest: stall detection, milestone segments, placement (`computeGoalMonuments`, `computeGoalForest`). |
| `cityHealthTower` | Health-metric tower segments from the latest health entry (`computeHealthTower`). |
diff --git a/client/src/utils/cityFocusCamera.js b/client/src/utils/cityFocusCamera.js
new file mode 100644
index 0000000000..b5a95fc960
--- /dev/null
+++ b/client/src/utils/cityFocusCamera.js
@@ -0,0 +1,87 @@
+// Pure camera-framing math for CyberCity's building focus mode (issue #2593). Given a single
+// borough's ground position + tower height, the current viewport aspect ratio, and the HUD safe
+// area, it computes an orbital camera `position` and look-at `target` that frame the WHOLE borough
+// without intersecting its geometry and without hiding it under the on-screen detail panel.
+//
+// No React / three.js imports so the topology stays unit-testable (mirrors cityMiniMap.js). Callers
+// (CityFocusCamera) convert the returned `[x, y, z]` tuples into THREE.Vector3 and animate toward
+// them.
+
+// Vertical field of view of the city camera (matches CityScene's <Canvas camera={{ fov: 50 }}>).
+export const CITY_CAMERA_FOV_DEG = 50;
+
+// Ground-footprint radius of a single borough: the process ring (BOROUGH_PARAMS.processRingRadius
+// = 3) plus a process building's half-footprint and a little breathing room. Buildings never spread
+// wider than this on the ground, so a sphere of this radius (grown by the tower height) bounds the
+// entire borough.
+export const BOROUGH_GROUND_RADIUS = 4.5;
+
+// Empty space left around the framed borough (1 = edge-to-edge, 1.35 = 35% margin).
+const FRAMING_MARGIN = 1.35;
+
+// How far above the horizon the focus camera sits (~40°). Keeps the shot looking slightly down onto
+// the borough like the overview, without going full top-down.
+const PITCH_RAD = (40 * Math.PI) / 180;
+
+// A HUD panel can never eat more than this fraction of an axis for framing purposes — a floor that
+// stops a degenerate viewport from pushing the camera to infinity.
+const MIN_USABLE_FRACTION = 0.35;
+
+const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
+const toRad = (deg) => (deg * Math.PI) / 180;
+const finiteOr = (v, fallback) => (Number.isFinite(v) ? v : fallback);
+
+// Compute the framing camera for one borough.
+// building — { x, z, height } layout entry (from computeCityLayout). Missing/invalid fields fall
+// back to sane defaults so a not-yet-resolved building can't produce NaNs.
+// aspect — viewport width / height (portrait < 1 needs the camera farther back).
+// fovDeg — vertical FOV in degrees (defaults to the city camera's 50).
+// hudSafe — { right, bottom } fractions (0..1) of the viewport occupied by the HUD, so the
+// borough frames in the CLEAR region rather than under the detail panel.
+// Returns { position:[x,y,z], target:[x,y,z], distance, radius }.
+export function computeFocusCamera({ building, aspect = 1, fovDeg = CITY_CAMERA_FOV_DEG, hudSafe } = {}) {
+ const bx = finiteOr(building?.x, 0);
+ const bz = finiteOr(building?.z, 0);
+ const heightRaw = finiteOr(building?.height, 4);
+ const height = heightRaw > 0 ? heightRaw : 4;
+
+ const safeAspect = Number.isFinite(aspect) && aspect > 0 ? aspect : 1;
+ const safeFov = Number.isFinite(fovDeg) && fovDeg > 0 ? fovDeg : CITY_CAMERA_FOV_DEG;
+
+ // Bounding radius: the wider of the borough's ground footprint and half its tower height, so both
+ // a tall skinny tower and a short wide cluster stay fully in frame.
+ const radius = Math.max(BOROUGH_GROUND_RADIUS, height * 0.6) * FRAMING_MARGIN;
+
+ // Usable viewport fraction once the HUD safe area is subtracted, clamped to a floor.
+ const right = clamp01(hudSafe?.right ?? 0);
+ const bottom = clamp01(hudSafe?.bottom ?? 0);
+ const usableW = Math.max(MIN_USABLE_FRACTION, 1 - right);
+ const usableH = Math.max(MIN_USABLE_FRACTION, 1 - bottom);
+
+ const halfV = Math.tan(toRad(safeFov) / 2);
+ const halfH = halfV * safeAspect;
+
+ // Distance so the bounding sphere fits both the (HUD-reduced) vertical and horizontal extents.
+ const distV = radius / (halfV * usableH);
+ const distH = radius / (halfH * usableW);
+ const distance = Math.max(distV, distH);
+
+ // Pan the framed region so the borough sits in the clear area: push it left of a right-edge panel
+ // and up above a bottom-edge panel. Panning moves camera + target by the same world delta.
+ const visHalfW = distance * halfH;
+ const visHalfH = distance * halfV;
+ const shiftX = right * visHalfW;
+ const shiftY = bottom * visHalfH;
+
+ const targetY = height * 0.45;
+ const target = [bx + shiftX, targetY - shiftY, bz];
+
+ // Camera above + on the +Z side (like the overview camera), pitched down by PITCH_RAD.
+ const position = [
+ target[0],
+ target[1] + distance * Math.sin(PITCH_RAD),
+ bz + distance * Math.cos(PITCH_RAD),
+ ];
+
+ return { position, target, distance, radius };
+}
diff --git a/client/src/utils/cityFocusCamera.test.js b/client/src/utils/cityFocusCamera.test.js
new file mode 100644
index 0000000000..9d491cbba4
--- /dev/null
+++ b/client/src/utils/cityFocusCamera.test.js
@@ -0,0 +1,69 @@
+import { describe, it, expect } from 'vitest';
+import { computeFocusCamera, BOROUGH_GROUND_RADIUS, CITY_CAMERA_FOV_DEG } from './cityFocusCamera';
+
+const building = { x: 12, z: -24, height: 6 };
+
+describe('computeFocusCamera', () => {
+ it('targets the borough centre (up the tower) with no HUD offset', () => {
+ const { target } = computeFocusCamera({ building, aspect: 1.6 });
+ expect(target[0]).toBeCloseTo(building.x, 6);
+ expect(target[2]).toBeCloseTo(building.z, 6);
+ expect(target[1]).toBeGreaterThan(0);
+ expect(target[1]).toBeLessThan(building.height);
+ });
+
+ it('places the camera above the tower and in front (+Z) so it never intersects geometry', () => {
+ const { position } = computeFocusCamera({ building, aspect: 1.6 });
+ expect(position[1]).toBeGreaterThan(building.height);
+ expect(position[2]).toBeGreaterThan(building.z);
+ });
+
+ it('pulls the camera farther back for a portrait (narrow) aspect than a landscape one', () => {
+ const portrait = computeFocusCamera({ building, aspect: 0.5 });
+ const landscape = computeFocusCamera({ building, aspect: 2.0 });
+ expect(portrait.distance).toBeGreaterThan(landscape.distance);
+ });
+
+ it('frames a taller tower from farther away', () => {
+ const shortB = computeFocusCamera({ building: { x: 0, z: 0, height: 3 }, aspect: 1.6 });
+ const tallB = computeFocusCamera({ building: { x: 0, z: 0, height: 40 }, aspect: 1.6 });
+ expect(tallB.distance).toBeGreaterThan(shortB.distance);
+ expect(tallB.radius).toBeGreaterThan(shortB.radius);
+ });
+
+ it('uses the borough ground radius floor for short buildings', () => {
+ const { radius } = computeFocusCamera({ building: { x: 0, z: 0, height: 1 }, aspect: 1.6 });
+ expect(radius).toBeGreaterThanOrEqual(BOROUGH_GROUND_RADIUS);
+ });
+
+ it('backs off and shifts the target when the HUD occupies the right edge', () => {
+ // A portrait-ish aspect makes the horizontal extent the binding constraint, so shrinking the
+ // usable width strictly increases the distance (in landscape a pan alone keeps it clear).
+ const bare = computeFocusCamera({ building, aspect: 0.6 });
+ const withPanel = computeFocusCamera({ building, aspect: 0.6, hudSafe: { right: 0.28 } });
+ expect(withPanel.distance).toBeGreaterThan(bare.distance);
+ // Target pans +x (borough shifts left, into the clear area beside the panel).
+ expect(withPanel.target[0]).toBeGreaterThan(bare.target[0]);
+ // Camera pans with the target so the view direction is preserved.
+ expect(withPanel.position[0]).toBeCloseTo(withPanel.target[0], 6);
+ });
+
+ it('raises the framed region above a bottom-edge HUD panel', () => {
+ const bare = computeFocusCamera({ building, aspect: 1.0 });
+ const withSheet = computeFocusCamera({ building, aspect: 1.0, hudSafe: { bottom: 0.45 } });
+ expect(withSheet.distance).toBeGreaterThan(bare.distance);
+ // Panning up moves the target down in world space (building rises on screen).
+ expect(withSheet.target[1]).toBeLessThan(bare.target[1]);
+ });
+
+ it('returns finite numbers for a missing/degenerate building', () => {
+ const { position, target, distance } = computeFocusCamera({ building: undefined, aspect: 0 });
+ [...position, ...target, distance].forEach((n) => expect(Number.isFinite(n)).toBe(true));
+ });
+
+ it('defaults to the city camera FOV', () => {
+ const a = computeFocusCamera({ building, aspect: 1.6 });
+ const b = computeFocusCamera({ building, aspect: 1.6, fovDeg: CITY_CAMERA_FOV_DEG });
+ expect(a.distance).toBeCloseTo(b.distance, 6);
+ });
+});
diff --git a/client/src/utils/cityFocusState.js b/client/src/utils/cityFocusState.js
new file mode 100644
index 0000000000..d82c67ab13
--- /dev/null
+++ b/client/src/utils/cityFocusState.js
@@ -0,0 +1,18 @@
+// Pure resolver for CyberCity's URL-addressed building focus (issue #2593). Maps the
+// `/city/apps/:appId` route param + the live app list into a concrete render state.
+//
+// The key subtlety: a valid deep link whose app list is still loading must NOT flash the
+// "building not found" fallback. So `notFound` is only true once the list has finished loading
+// AND the id still matches nothing (deleted/archived-away/never-existed id).
+
+export function resolveCityFocus(appId, apps, { loading = false } = {}) {
+ const hasFocus = typeof appId === 'string' && appId.length > 0;
+ if (!hasFocus) return { hasFocus: false, focusedApp: null, notFound: false };
+
+ const list = Array.isArray(apps) ? apps : [];
+ const focusedApp = list.find((a) => a?.id === appId) || null;
+ // Still loading → keep waiting (a valid id may resolve once apps arrive). Loaded + missing → 404.
+ const notFound = !focusedApp && !loading;
+
+ return { hasFocus: true, focusedApp, notFound };
+}
diff --git a/client/src/utils/cityFocusState.test.js b/client/src/utils/cityFocusState.test.js
new file mode 100644
index 0000000000..bf246ac391
--- /dev/null
+++ b/client/src/utils/cityFocusState.test.js
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest';
+import { resolveCityFocus } from './cityFocusState';
+
+const apps = [
+ { id: 'alpha', name: 'Alpha' },
+ { id: 'beta', name: 'Beta' },
+];
+
+describe('resolveCityFocus', () => {
+ it('reports no focus when there is no appId (overview)', () => {
+ expect(resolveCityFocus(null, apps)).toEqual({ hasFocus: false, focusedApp: null, notFound: false });
+ expect(resolveCityFocus('', apps)).toEqual({ hasFocus: false, focusedApp: null, notFound: false });
+ expect(resolveCityFocus(undefined, apps)).toEqual({ hasFocus: false, focusedApp: null, notFound: false });
+ });
+
+ it('resolves a valid id to its app', () => {
+ const res = resolveCityFocus('beta', apps);
+ expect(res.hasFocus).toBe(true);
+ expect(res.focusedApp).toBe(apps[1]);
+ expect(res.notFound).toBe(false);
+ });
+
+ it('does NOT flag not-found while the app list is still loading (deep link + reload)', () => {
+ const res = resolveCityFocus('beta', [], { loading: true });
+ expect(res.hasFocus).toBe(true);
+ expect(res.focusedApp).toBeNull();
+ expect(res.notFound).toBe(false);
+ });
+
+ it('flags not-found for a stale/deleted id once loading has finished', () => {
+ const res = resolveCityFocus('ghost', apps, { loading: false });
+ expect(res.hasFocus).toBe(true);
+ expect(res.focusedApp).toBeNull();
+ expect(res.notFound).toBe(true);
+ });
+
+ it('tolerates a non-array app list', () => {
+ expect(resolveCityFocus('alpha', null, { loading: false })).toEqual({
+ hasFocus: true,
+ focusedApp: null,
+ notFound: true,
+ });
+ });
+});
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 2951c80154..370d9f90e8 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -46,6 +46,8 @@ export * from './cityDistrictLayout.js';
export * from './cityEasterEggs.js';
export * from './cityFederation.js';
export * from './cityFilter.js';
+export * from './cityFocusCamera.js';
+export * from './cityFocusState.js';
export * from './cityFlowLines.js';
export * from './cityGoalMonuments.js';
export * from './cityHealthTower.js';