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([issue-967]): CyberCity timeline scrubber (playback mode)

Adam Eivy4ef4d06984eb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dc6f79e97e..c18895c9c9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,6 +16,7 @@
- **[issue-952] Cinematic depth-of-field in City photo mode** — Photo mode now blurs the background for a cinematic look: whatever the current framing points at stays sharp while the rest of the city falls off softly, and each preset focuses on its own subject (the low-angle shot uses a shallower, more dramatic focus). It's on by default; toggle it with the "Depth" button in the photo bar or the D key, and your captured postcard matches what you see. Depth-of-field only runs while you're in photo mode, so the live dashboard is unaffected.
- **[issue-912] Regenerate gallery images to defeat SynthID watermarks** — Generated images gain a "Regenerate" action in the lightbox, next to "Clean", whenever a local FLUX image generator is installed. The existing Clean only strips embedded provenance metadata and can't touch SynthID — Google's invisible per-pixel watermark — which survives by design. Regenerate is the honest defeat path: it round-trips the picture through a local FLUX model so the watermark signal is overwritten by fresh sampling, while keeping the change to the image as small as possible — it uses no prompt and a low denoise, so the result is a near-faithful copy of the original rather than a reinterpretation. It runs entirely on-device, is never applied automatically, and saves the result as a new variant beside the original (which is kept); the lightbox's variant switch lets you toggle between them. Very large source images (e.g. 4K) are handled by regenerating at a model-friendly resolution and scaling the clean result back up to the original size, so a big image no longer stalls the pass. The Regenerate button opens an inline panel with a strength slider (lower = more faithful) and an optional prompt field, so you can dial in how much the pass changes the image — or paste a prompt for a creative re-roll — right from the lightbox.
- **[issue-877] City records its history for a future timeline scrubber** — The City now quietly snapshots its own state on a schedule (every 5 minutes by default), capturing which apps are online, how many agents are working, system health, and the other landmark readouts. These frames accumulate locally — never synced to peers — so an upcoming timeline view can let you scrub back and watch the city change over time. There's nothing to interact with yet; this is the recording groundwork. You can tune the capture interval, set how many frames to keep, or turn it off in settings.
+- **[issue-967] Scrub back through City history** — A new "History" button on the City opens a playback timeline: drag the slider to any past moment, or hit play to watch your city evolve at 1×/2×/4× (←/→ step a frame, Esc exits). As you move through time, buildings rise in (construction) when an app first appeared, scale away (teardown) when one was gone, and recolor as their status changed — and the health, backup, task, agent, and federation readouts follow each recorded moment. Districts the snapshots don't capture (memory, goals, Jira, activity) keep showing live data and are flagged as such, so a historical view never quietly passes off "now" as "then."
## Changed
diff --git a/client/src/components/city/Borough.jsx b/client/src/components/city/Borough.jsx
index 711505ffc0..20e6eb2795 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 }) {
+export default function Borough({ app, position, agentMap, onBuildingClick, playSfx, neonBrightness, isProximity, 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,9 @@ export default function Borough({ app, position, agentMap, onBuildingClick, play
isProximity={isProximity}
dimmed={dimmed}
dayMix={dayMix}
+ playback={playback}
+ transitionState={transitionState}
+ onExited={onExited}
/>
{/* Process buildings in ring around main building */}
diff --git a/client/src/components/city/Building.jsx b/client/src/components/city/Building.jsx
index 5cfd2f8ab3..ff495d77f6 100644
--- a/client/src/components/city/Building.jsx
+++ b/client/src/components/city/Building.jsx
@@ -341,12 +341,25 @@ 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 }) {
+export default function Building({ app, position, agentCount, onClick, playSfx, neonBrightness = 1.2, isProximity = false, dimmed = false, dayMix = 0, playback = false, transitionState = null, onExited }) {
const meshRef = useRef();
const glowRef = useRef();
const haloRef = useRef();
+ const groupRef = useRef();
const [hovered, setHovered] = useState(false);
+ // Construction/teardown animation state (playback/scrubber only — issue #967).
+ // In live mode buildings appear/disappear instantly as today; during playback a
+ // newly-present building scales in from 0 (construction) and a departing one
+ // scales out to 0 (teardown) before the cluster unmounts it.
+ const exiting = transitionState === 'exiting';
+ // Start small only when entering under playback; otherwise full size.
+ const initialScale = playback && !exiting ? 0.001 : 1;
+ const exitedFiredRef = useRef(false);
+ // Smoothly-lerped status color so a status change recolors over a beat rather
+ // than snapping. Seeded to the current color; the target is recomputed below.
+ const displayedColorRef = useRef(null);
+
const height = getBuildingHeight(app);
const edgeColor = getBuildingColor(app.overallStatus, app.archived);
const accentColor = getAccentColor(app);
@@ -394,10 +407,36 @@ export default function Building({ app, position, agentCount, onClick, playSfx,
return (app.name || '').replace(/[-_.]/g, ' ').toUpperCase();
}, [app.name]);
- useFrame(({ clock }) => {
+ useFrame(({ clock }, delta) => {
+ // Construction/teardown scale animation (playback only). damp() eases the
+ // group scale toward 1 (entering) or 0 (exiting); reaching ~0 on exit fires
+ // onExited so the cluster can drop the building from the tree.
+ if (groupRef.current && playback) {
+ const target = exiting ? 0 : 1;
+ const cur = groupRef.current.scale.x;
+ const next = THREE.MathUtils.damp(cur, target, 6, delta || 0.016);
+ groupRef.current.scale.setScalar(next);
+ if (exiting && next < 0.02 && !exitedFiredRef.current) {
+ exitedFiredRef.current = true;
+ onExited?.(app.id);
+ }
+ } else if (groupRef.current && groupRef.current.scale.x !== 1) {
+ // Live mode (or after entering completes): ensure full size.
+ groupRef.current.scale.setScalar(1);
+ }
+
if (!meshRef.current) return;
const t = clock.getElapsedTime();
+ // Status recolor: ease the body emissive toward the current status color so a
+ // scrub that flips online→stopped fades cyan→red rather than snapping.
+ const mat = meshRef.current.material;
+ if (mat?.emissive) {
+ if (!displayedColorRef.current) displayedColorRef.current = new THREE.Color(edgeColor);
+ displayedColorRef.current.lerp(new THREE.Color(edgeColor), Math.min(1, (delta || 0.016) * 6));
+ mat.emissive.copy(displayedColorRef.current);
+ }
+
const nb = neonBrightness;
const baseIntensity = (isOnline ? 0.5 : isStopped ? 0.35 : 0.2) * nb;
const pulse = isOnline
@@ -423,7 +462,7 @@ export default function Building({ app, position, agentCount, onClick, playSfx,
});
return (
- <group position={[position.x, 0, position.z]}>
+ <group ref={groupRef} position={[position.x, 0, position.z]} scale={initialScale}>
{/* Building body with window texture + pixel art icon */}
<mesh
ref={meshRef}
diff --git a/client/src/components/city/BuildingCluster.jsx b/client/src/components/city/BuildingCluster.jsx
index e28125470e..b72c9eefb3 100644
--- a/client/src/components/city/BuildingCluster.jsx
+++ b/client/src/components/city/BuildingCluster.jsx
@@ -1,10 +1,10 @@
-import { useMemo, useEffect } from 'react';
+import { useMemo, useEffect, useRef, useState, useCallback } from 'react';
import { computeCityLayout } from './cityLayout';
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 }) {
+export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPositionsReady, playSfx, settings, proximityAppId, dimmedAppIds, playback = false }) {
const positions = useMemo(() => computeCityLayout(apps), [apps]);
const dayMix = cityDayMix(settings);
@@ -13,6 +13,41 @@ export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPos
onPositionsReady?.(positions);
}, [positions, onPositionsReady]);
+ // Teardown lifecycle (playback/scrubber only — issue #967). When an app id
+ // disappears between frames, React would unmount its building instantly. To
+ // animate the teardown, retain the departed app (with its last-known position)
+ // in `exiting` and render it with transitionState='exiting' until the
+ // building's scale-out completes and fires onExited. In live mode this stays
+ // empty so behavior is unchanged.
+ const prevRef = useRef(new Map()); // id → app (previous render)
+ const prevPositionsRef = useRef(new Map()); // id → pos (previous render)
+ const [exiting, setExiting] = useState([]);
+ useEffect(() => {
+ const current = new Map(apps.map(a => [a.id, a]));
+ if (playback) {
+ const departed = [];
+ for (const [id, app] of prevRef.current) {
+ if (current.has(id)) continue;
+ const prevPos = prevPositionsRef.current.get(id);
+ if (prevPos) departed.push({ app, pos: prevPos });
+ }
+ setExiting(prev => {
+ // Drop anything that came back this frame, then add newly-departed ids.
+ const kept = prev.filter(e => !current.has(e.app.id));
+ const have = new Set(kept.map(e => e.app.id));
+ return [...kept, ...departed.filter(d => !have.has(d.app.id))];
+ });
+ } else if (exiting.length > 0) {
+ setExiting([]); // leaving playback: clear any in-flight teardowns
+ }
+ prevRef.current = current;
+ prevPositionsRef.current = positions;
+ }, [apps, positions, playback]);
+
+ const handleExited = useCallback((id) => {
+ setExiting(prev => prev.filter(e => e.app.id !== id));
+ }, []);
+
const hasArchived = apps.some(a => a.archived);
const warehouseMinZ = useMemo(() => {
@@ -41,10 +76,31 @@ export default function BuildingCluster({ apps, agentMap, onBuildingClick, onPos
isProximity={proximityAppId === app.id}
dimmed={dimmedAppIds?.has?.(app.id) || false}
settings={settings}
+ playback={playback}
+ transitionState="entering"
/>
);
})}
+ {/* Departed buildings animating out (playback teardown) */}
+ {exiting.map(({ app, pos }) => (
+ <Borough
+ key={`exit-${app.id}`}
+ app={app}
+ position={pos}
+ agentMap={agentMap}
+ onBuildingClick={onBuildingClick}
+ playSfx={playSfx}
+ neonBrightness={settings?.neonBrightness ?? 1.2}
+ isProximity={false}
+ dimmed={dimmedAppIds?.has?.(app.id) || false}
+ settings={settings}
+ playback={playback}
+ transitionState="exiting"
+ onExited={handleExited}
+ />
+ ))}
+
{/* Warehouse district label - pixel font (dark ink + halo by day) */}
{hasArchived && (
<CityLabel
diff --git a/client/src/components/city/CityHud.jsx b/client/src/components/city/CityHud.jsx
index 19dee153db..44384bc18a 100644
--- a/client/src/components/city/CityHud.jsx
+++ b/client/src/components/city/CityHud.jsx
@@ -125,7 +125,7 @@ function HealthBar({ value, max, color }) {
);
}
-export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, connected, apps, reviewCounts, instances, productivityData, systemHealth, notificationCounts, character, filter, onFilterChange, onJumpToFirst, matchCount, onToggleExploration, explorationMode, onSelectApp, onEnterPhotoMode }) {
+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 }) {
const navigate = useNavigate();
const location = useLocation();
const [time, setTime] = useState(new Date());
@@ -457,6 +457,23 @@ export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, con
</button>
)}
+ {/* History / playback mode — scrub recorded city-state snapshots */}
+ {onEnterPlayback && (
+ <button
+ onClick={onEnterPlayback}
+ className="pointer-events-auto mb-2 relative bg-black/85 backdrop-blur-sm border border-cyan-500/30 rounded-lg w-10 h-10 flex items-center justify-center hover:border-cyan-400/60 hover:bg-cyan-500/10 transition-all group"
+ title="History — scrub back through past city states"
+ >
+ <HudCorner position="tl" />
+ <HudCorner position="br" />
+ <svg className="w-4.5 h-4.5 text-cyan-500/70 group-hover:text-cyan-400 transition-colors" style={{ filter: 'drop-shadow(0 0 6px rgba(6,182,212,0.4))' }} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3 3v5h5" />
+ <path strokeLinecap="round" strokeLinejoin="round" d="M3.05 13A9 9 0 106 5.3L3 8" />
+ <path strokeLinecap="round" strokeLinejoin="round" d="M12 7v5l3 2" />
+ </svg>
+ </button>
+ )}
+
<button
onClick={() => navigate(location.pathname === '/city/settings' ? '/city' : '/city/settings')}
className="pointer-events-auto mb-2 relative bg-black/85 backdrop-blur-sm border border-cyan-500/30 rounded-lg w-10 h-10 flex items-center justify-center hover:border-cyan-400/60 hover:bg-cyan-500/10 transition-all group"
diff --git a/client/src/components/city/CityPlaybackOverlay.jsx b/client/src/components/city/CityPlaybackOverlay.jsx
new file mode 100644
index 0000000000..b1a0a1bea2
--- /dev/null
+++ b/client/src/components/city/CityPlaybackOverlay.jsx
@@ -0,0 +1,124 @@
+import { formatDateTime, timeAgo } from '../../utils/formatters';
+
+// Timeline-scrubber HUD overlay (roadmap 3.6, issue #967). When playback mode is
+// active it draws a bottom transport bar: play/pause, speed, a draggable timeline
+// slider, frame-step buttons, the current frame's timestamp, and a note that the
+// landmarks the snapshot can't replay are showing LIVE data (frozen during scrub).
+// Mirrors CityPhotoOverlay's bottom-bar styling. All transport logic lives in the
+// useCityPlayback hook; this is presentation only.
+
+export default function CityPlaybackOverlay({
+ active,
+ loading,
+ snapshots = [],
+ frameIndex,
+ currentFrame,
+ playing,
+ speed,
+ onSeek,
+ onStep,
+ onTogglePlay,
+ onCycleSpeed,
+ onExit,
+}) {
+ if (!active) return null;
+
+ const frameCount = snapshots.length;
+ const hasFrames = frameCount > 0;
+ const ts = currentFrame?.ts;
+
+ return (
+ <div className="absolute inset-0 z-30 pointer-events-none cybercity-themed">
+ {/* Top-right: title + exit */}
+ <div className="absolute top-0 left-0 right-0 flex items-center justify-between px-6 py-4">
+ <div className="font-pixel text-[11px] text-cyan-400 tracking-widest" style={{ textShadow: '0 0 10px rgba(6,182,212,0.5)' }}>
+ ⟲ CITY HISTORY {hasFrames ? `— ${frameIndex + 1}/${frameCount}` : ''}
+ </div>
+ <button
+ type="button"
+ onClick={onExit}
+ className="font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-3 py-1.5 hover:bg-cyan-500/10 transition-all pointer-events-auto"
+ title="Exit playback (Esc)"
+ >
+ [ EXIT ]
+ </button>
+ </div>
+
+ {/* Bottom transport bar */}
+ <div className="absolute bottom-0 left-0 right-0 px-6 pb-5 pt-3 bg-gradient-to-t from-black/70 to-transparent">
+ {loading && (
+ <div className="font-pixel text-[10px] text-cyan-500/70 tracking-wider text-center pb-2">LOADING HISTORY…</div>
+ )}
+
+ {!loading && !hasFrames && (
+ <div className="font-pixel text-[10px] text-cyan-500/70 tracking-wider text-center pb-2">
+ NO SNAPSHOTS YET — the city records its state every few minutes. Check back later.
+ </div>
+ )}
+
+ {!loading && hasFrames && (
+ <div className="flex flex-col gap-2">
+ {/* Timestamp + live-data note */}
+ <div className="flex items-center justify-between font-pixel text-[10px] text-cyan-300/90 tracking-wider">
+ <span title={ts ? formatDateTime(ts) : ''}>{ts ? formatDateTime(ts) : '—'}</span>
+ <span className="text-amber-400/80" title="Buildings, agents, health, backup, tasks & counts are historical. Memory, goals, Jira & activity show current live data.">
+ ⚠ some districts show LIVE data
+ </span>
+ <span className="text-cyan-500/60">{ts ? timeAgo(ts) : ''}</span>
+ </div>
+
+ {/* Timeline slider */}
+ <input
+ type="range"
+ min={0}
+ max={frameCount - 1}
+ step={1}
+ value={frameIndex}
+ onChange={(e) => onSeek?.(Number(e.target.value))}
+ aria-label="Timeline position"
+ className="w-full accent-cyan-400 pointer-events-auto cursor-pointer"
+ />
+
+ {/* Transport controls */}
+ <div className="flex items-center justify-center gap-4">
+ <button
+ type="button"
+ onClick={() => onStep?.(-1)}
+ disabled={frameIndex <= 0}
+ className="font-pixel text-cyan-400 text-lg px-2 hover:text-cyan-300 transition-colors pointer-events-auto disabled:opacity-30"
+ title="Previous frame (←)"
+ >
+ ◀
+ </button>
+ <button
+ type="button"
+ onClick={onTogglePlay}
+ className="font-pixel text-[11px] text-black bg-cyan-400 tracking-wider rounded px-4 py-2 hover:bg-cyan-300 transition-all pointer-events-auto"
+ title="Play / pause (Space)"
+ >
+ {playing ? '❚❚ PAUSE' : '▶ PLAY'}
+ </button>
+ <button
+ type="button"
+ onClick={() => onStep?.(1)}
+ disabled={frameIndex >= frameCount - 1}
+ className="font-pixel text-cyan-400 text-lg px-2 hover:text-cyan-300 transition-colors pointer-events-auto disabled:opacity-30"
+ title="Next frame (→)"
+ >
+ ▶
+ </button>
+ <button
+ type="button"
+ onClick={onCycleSpeed}
+ className="font-pixel text-[10px] text-cyan-400 tracking-wider border border-cyan-500/40 rounded px-3 py-1.5 hover:bg-cyan-500/10 transition-all pointer-events-auto"
+ title="Playback speed"
+ >
+ {speed}×
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsx
index 72d9820922..5e55f34d08 100644
--- a/client/src/components/city/CityScene.jsx
+++ b/client/src/components/city/CityScene.jsx
@@ -45,7 +45,7 @@ import CityDepthOfField from './CityDepthOfField';
import { cityDayMix } from './cityConstants';
import ErrorBoundary from '../ErrorBoundary';
-export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, activityCalendar, goals, character, chronotype, memoryGraph, inboxDepth, jiraTickets, photoMode, photoPresetId, photoDof, onPhotoCaptureReady, settings, playSfx, keysRef, dimmedAppIds, background }) {
+export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus, reviewCounts, instances, backupStatus, cosTasks, healthMetrics, voiceState, aiActivity, productivityData, activityCalendar, goals, character, chronotype, memoryGraph, inboxDepth, jiraTickets, playback = false, photoMode, photoPresetId, photoDof, onPhotoCaptureReady, settings, playSfx, keysRef, dimmedAppIds, background }) {
const [positions, setPositions] = useState(null);
const [proximityApp, setProximityApp] = useState(null);
const [transitioning, setTransitioning] = useState(false);
@@ -224,6 +224,7 @@ export default function CityScene({ apps, agentMap, onBuildingClick, cosStatus,
settings={settings}
proximityAppId={proximityApp?.id}
dimmedAppIds={dimmedAppIds}
+ playback={playback}
/>
<CityDataStreams positions={positions} apps={apps} agentMap={agentMap} />
<CityTraffic positions={positions} />
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index e0f947ff33..62ee82869f 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -110,6 +110,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useCanonPatch` | Optimistic canon-entry patch: rebuild the kind list with one entry mutated, apply locally, PATCH the universe, re-apply the server copy. Targets + staleness-guards on the loaded record's `universe.id` so a mid-flight universe swap can't cross-PATCH or resurrect stale state. `apply` is `setUniverse` or `onUniverseChange`. | Inline canon-field edits on a universe (UniverseCanonSection, NounsStage). Don't re-roll the optimistic-then-confirm dance. |
| `useCityAudio` | CyberCity ambient audio. | CyberCity only. |
| `useCityData` | CyberCity environment data + physics. | CyberCity only. |
+| `useCityPlayback` | Timeline-scrubber transport: loads the snapshot series, steps a frame index, play/pause/speed. | CyberCity playback (history) mode only. |
| `useCitySettings` | CyberCity quality presets + persistence. | CyberCity only. |
| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. |
| `useCatalogTypes` | Catalog ingredient type registry (system + user-defined) merged with the static fallback via a Provider/hook pair; synchronous fallback to the built-in six so first render never blanks. | Catalog list/picker/editor; anywhere the catalog type list/lookup is needed. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 685989818a..493b960053 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -95,6 +95,7 @@ export * from './useAppDeploy.js';
export * from './useAppOperation.js';
export * from './useCanonPatch.js';
export * from './useCityData.js';
+export * from './useCityPlayback.js';
export * from './useDeathClock.js';
export * from './useGoalDetail.js';
export * from './usePostSession.js';
diff --git a/client/src/hooks/useCityPlayback.js b/client/src/hooks/useCityPlayback.js
new file mode 100644
index 0000000000..3a5909fcd0
--- /dev/null
+++ b/client/src/hooks/useCityPlayback.js
@@ -0,0 +1,97 @@
+import { useState, useRef, useCallback, useEffect } from 'react';
+import { getCitySnapshots } from '../services/apiCity.js';
+import { isPlayableFrame } from '../lib/cityPlaybackFrame.js';
+
+// Transport state for the CyberCity timeline scrubber (issue #967). Owns the
+// snapshot series, the current frame index, and play/pause/speed so CyberCity.jsx
+// stays lean. Pure-UI: it reads the snapshot API and steps an index; the page
+// turns the current frame into scene props via lib/cityPlaybackFrame.js.
+
+export const PLAYBACK_SPEEDS = [1, 2, 4]; // × frames/sec
+const BASE_INTERVAL_MS = 1000; // 1×: advance one frame per second
+
+export function useCityPlayback() {
+ const [active, setActive] = useState(false);
+ const [snapshots, setSnapshots] = useState([]);
+ const [frameIndex, setFrameIndex] = useState(0);
+ const [playing, setPlaying] = useState(false);
+ const [speed, setSpeed] = useState(PLAYBACK_SPEEDS[0]);
+ const [loading, setLoading] = useState(false);
+
+ // Guards a deferred/interval callback against firing after unmount (CLAUDE.md
+ // deferred-work rule). Never reset to true — handles dev double-mount cleanly.
+ const mountedRef = useRef(true);
+ useEffect(() => () => { mountedRef.current = false; }, []);
+
+ const enter = useCallback(async () => {
+ setActive(true);
+ setLoading(true);
+ setPlaying(false);
+ const res = await getCitySnapshots({ silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
+ // Only keep frames this scrubber can render (schemaVersion gate); a future
+ // bump leaves older/newer frames out rather than mis-rendering them.
+ const frames = (res?.snapshots || []).filter(isPlayableFrame);
+ setSnapshots(frames);
+ setFrameIndex(frames.length > 0 ? frames.length - 1 : 0); // start at "now"
+ setLoading(false);
+ }, []);
+
+ const exit = useCallback(() => {
+ setActive(false);
+ setPlaying(false);
+ }, []);
+
+ const togglePlay = useCallback(() => {
+ // At the last frame, play restarts from the beginning.
+ setPlaying((p) => {
+ if (!p) setFrameIndex((i) => (i >= snapshots.length - 1 ? 0 : i));
+ return !p;
+ });
+ }, [snapshots.length]);
+
+ const cycleSpeed = useCallback(() => {
+ setSpeed((s) => {
+ const idx = PLAYBACK_SPEEDS.indexOf(s);
+ return PLAYBACK_SPEEDS[(idx + 1) % PLAYBACK_SPEEDS.length];
+ });
+ }, []);
+
+ // Clamped step; pauses if a manual step is taken while playing.
+ const step = useCallback((delta) => {
+ setPlaying(false);
+ setFrameIndex((i) => Math.max(0, Math.min(snapshots.length - 1, i + delta)));
+ }, [snapshots.length]);
+
+ const seek = useCallback((index) => {
+ setFrameIndex(() => Math.max(0, Math.min(snapshots.length - 1, index)));
+ }, [snapshots.length]);
+
+ // Auto-advance timer. Stops at the last frame. Guarded by mountedRef and torn
+ // down on pause/exit/speed-change/unmount so it never fires into the void.
+ useEffect(() => {
+ if (!active || !playing || snapshots.length === 0) return undefined;
+ const id = setInterval(() => {
+ if (!mountedRef.current) return;
+ setFrameIndex((i) => {
+ if (i >= snapshots.length - 1) {
+ setPlaying(false);
+ return i;
+ }
+ return i + 1;
+ });
+ }, BASE_INTERVAL_MS / speed);
+ return () => clearInterval(id);
+ }, [active, playing, speed, snapshots.length]);
+
+ const currentFrame = snapshots[frameIndex] || null;
+
+ return {
+ active, enter, exit,
+ snapshots, frameIndex, currentFrame, seek, step,
+ playing, togglePlay,
+ speed, cycleSpeed,
+ loading,
+ frameCount: snapshots.length,
+ };
+}
diff --git a/client/src/hooks/useCityPlayback.test.jsx b/client/src/hooks/useCityPlayback.test.jsx
new file mode 100644
index 0000000000..2f0f91cf13
--- /dev/null
+++ b/client/src/hooks/useCityPlayback.test.jsx
@@ -0,0 +1,100 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook, act, waitFor } from '@testing-library/react';
+
+const getCitySnapshots = vi.fn();
+vi.mock('../services/apiCity.js', () => ({
+ getCitySnapshots: (...a) => getCitySnapshots(...a),
+}));
+
+import { useCityPlayback, PLAYBACK_SPEEDS } from './useCityPlayback.js';
+
+const mkFrames = (n) => Array.from({ length: n }, (_, i) => ({
+ ts: `2026-06-05T0${i}:00:00.000Z`,
+ schemaVersion: 1,
+ apps: [],
+ counts: {},
+}));
+
+describe('useCityPlayback', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getCitySnapshots.mockResolvedValue({ total: 3, snapshots: mkFrames(3) });
+ });
+
+ it('loads the series on enter and starts at the most recent frame', async () => {
+ const { result } = renderHook(() => useCityPlayback());
+ await act(async () => { await result.current.enter(); });
+ expect(result.current.active).toBe(true);
+ expect(result.current.frameCount).toBe(3);
+ expect(result.current.frameIndex).toBe(2); // newest
+ expect(result.current.currentFrame.ts).toBe('2026-06-05T02:00:00.000Z');
+ });
+
+ it('filters out frames with an unsupported schemaVersion', async () => {
+ getCitySnapshots.mockResolvedValue({
+ snapshots: [...mkFrames(2), { ts: 'x', schemaVersion: 99, apps: [] }],
+ });
+ const { result } = renderHook(() => useCityPlayback());
+ await act(async () => { await result.current.enter(); });
+ expect(result.current.frameCount).toBe(2);
+ });
+
+ it('step clamps at both ends and pauses', async () => {
+ const { result } = renderHook(() => useCityPlayback());
+ await act(async () => { await result.current.enter(); });
+ act(() => result.current.step(1)); // already at last → clamps
+ expect(result.current.frameIndex).toBe(2);
+ act(() => result.current.seek(0));
+ act(() => result.current.step(-1)); // at first → clamps
+ expect(result.current.frameIndex).toBe(0);
+ });
+
+ it('cycleSpeed walks the speed presets', async () => {
+ const { result } = renderHook(() => useCityPlayback());
+ await act(async () => { await result.current.enter(); });
+ expect(result.current.speed).toBe(PLAYBACK_SPEEDS[0]);
+ act(() => result.current.cycleSpeed());
+ expect(result.current.speed).toBe(PLAYBACK_SPEEDS[1]);
+ });
+
+ it('exit clears active + playing', async () => {
+ const { result } = renderHook(() => useCityPlayback());
+ await act(async () => { await result.current.enter(); });
+ act(() => result.current.exit());
+ expect(result.current.active).toBe(false);
+ expect(result.current.playing).toBe(false);
+ });
+
+ describe('autoplay timer', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('advances frames while playing and stops at the end', async () => {
+ const { result } = renderHook(() => useCityPlayback());
+ await act(async () => { await result.current.enter(); });
+ // seek to start, then play
+ act(() => result.current.seek(0));
+ act(() => result.current.togglePlay());
+ expect(result.current.playing).toBe(true);
+
+ act(() => vi.advanceTimersByTime(1000)); // 1× → +1 frame
+ expect(result.current.frameIndex).toBe(1);
+ act(() => vi.advanceTimersByTime(1000));
+ expect(result.current.frameIndex).toBe(2);
+ // at last frame → auto-pauses, no further advance
+ act(() => vi.advanceTimersByTime(2000));
+ expect(result.current.frameIndex).toBe(2);
+ expect(result.current.playing).toBe(false);
+ });
+
+ it('does not advance after exit (timer torn down)', async () => {
+ const { result } = renderHook(() => useCityPlayback());
+ await act(async () => { await result.current.enter(); });
+ act(() => result.current.seek(0));
+ act(() => result.current.togglePlay());
+ act(() => result.current.exit());
+ act(() => vi.advanceTimersByTime(5000));
+ expect(result.current.frameIndex).toBe(0);
+ });
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 69fac5cd83..d6d10c501c 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -82,6 +82,7 @@ grep -i "what you want to do" client/src/lib/README.md
| Module | Purpose |
|---|---|
+| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. |
| `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
| `writingGuide.js` | Canonical Writers Room reference data + craft principles rendered by the Guide page (`/writers-room/guide`): `WRITING_LENGTH_TARGETS` (microfiction→novel word/char bands), `BOOK_LENGTH_ESTIMATES` (page-based), `WRITING_PRINCIPLES`, `PLANNED_ANALYSES` (e.g. the emotional-roadmap evaluator), and `classifyByWordCount(n)` for labelling a draft's length. Future word-count gauges / length checks read from here so targets don't drift from the docs. |
diff --git a/client/src/lib/cityPlaybackFrame.js b/client/src/lib/cityPlaybackFrame.js
new file mode 100644
index 0000000000..c9192a2b06
--- /dev/null
+++ b/client/src/lib/cityPlaybackFrame.js
@@ -0,0 +1,121 @@
+// Pure mappers that turn a recorded CyberCity snapshot frame (issue #877 capture
+// pipeline) into the prop shape CityScene consumes, for the timeline scrubber
+// (issue #967). No React, no I/O — unit-tested in cityPlaybackFrame.test.js.
+//
+// A snapshot frame is compact: per-app { id, name, status }, agent assignments,
+// and counts/health/cos/backup/character. It does NOT carry the rich landmark
+// inputs (memory graph, goals, jira, activity, productivity), so playback drives
+// only what the frame can feed and the page leaves the rest at their live values
+// ("freeze unfed landmarks at live").
+//
+// Sentinel discipline mirrors the capture side: a `null` field means "source
+// unavailable at capture time" — never fabricate a 0/empty in its place. A null
+// apps/assignments array falls back to the live value rather than emptying the
+// city.
+
+// The snapshot shape this scrubber understands. A frame whose schemaVersion
+// differs should be skipped/flagged by the caller rather than mis-rendered.
+export const SUPPORTED_SNAPSHOT_SCHEMA_VERSION = 1;
+
+export const isPlayableFrame = (frame) =>
+ !!frame && frame.schemaVersion === SUPPORTED_SNAPSHOT_SCHEMA_VERSION;
+
+// Build the apps array CityScene renders from a frame, recovering render-only
+// fields (processes, repoPath, type, archived) from the matching live app and
+// overriding overallStatus with the frame's recorded status. Apps in the live
+// set but absent from the frame are dropped (they teardown-animate out). Apps in
+// the frame but no longer live render from the compact fields with safe defaults.
+export function buildPlaybackApps(frame, liveApps = []) {
+ // Failed capture → fall back to live apps rather than emptying the city.
+ if (!Array.isArray(frame?.apps)) return liveApps;
+ const liveById = new Map((liveApps || []).map((a) => [a.id, a]));
+ return frame.apps.map((snap) => {
+ const live = liveById.get(snap.id);
+ if (live) {
+ return { ...live, overallStatus: snap.status };
+ }
+ // App no longer exists live — render a minimal building from the frame.
+ return {
+ id: snap.id,
+ name: snap.name,
+ overallStatus: snap.status,
+ archived: false,
+ processes: [],
+ };
+ });
+}
+
+// Rebuild the agentMap (Map<appId, { app, agents }>) from the frame's compact
+// assignment list. Only running assignments are captured. A null assignments
+// array (failed capture) yields an empty map — playback shows no agent entities
+// rather than fabricating them.
+export function buildPlaybackAgentMap(frame, playbackApps = []) {
+ const map = new Map();
+ if (!Array.isArray(frame?.assignments)) return map;
+ const appById = new Map((playbackApps || []).map((a) => [a.id, a]));
+ for (const asn of frame.assignments) {
+ if (!asn?.appId) continue;
+ const app = appById.get(asn.appId);
+ if (!app) continue;
+ const existing = map.get(asn.appId) || { app, agents: [] };
+ existing.agents.push({ agentId: asn.agentId, status: asn.status });
+ map.set(asn.appId, existing);
+ }
+ return map;
+}
+
+// Derive the count-driven scene props from a frame. Each value is null when the
+// frame recorded null (source unavailable) so the consuming component shows its
+// empty state rather than a fabricated zero.
+function deriveCountProps(frame) {
+ const c = frame?.counts || {};
+ return {
+ cosStatus: frame?.cos == null ? null : {
+ running: frame.cos.running ?? false,
+ paused: frame.cos.paused ?? false,
+ activeAgents: c.agentsActive ?? null,
+ pausedAgents: c.agentsPaused ?? null,
+ stats: { tasksCompleted: c.tasksCompleted ?? null },
+ },
+ backupStatus: frame?.backup == null ? null : {
+ status: frame.backup.status ?? null,
+ lastRun: frame.backup.lastRun ?? null,
+ },
+ // systemHealth shape mirrors what useCityData exposes (percent fields).
+ systemHealth: (frame?.health && (frame.health.cpuPercent != null || frame.health.memPercent != null || frame.health.diskPercent != null))
+ ? {
+ system: {
+ cpu: { usagePercent: frame.health.cpuPercent },
+ memory: { usagePercent: frame.health.memPercent },
+ disk: { usagePercent: frame.health.diskPercent },
+ },
+ }
+ : null,
+ character: frame?.character == null ? null : { level: frame.character.level ?? null },
+ instances: frame?.instance == null ? null : {
+ self: { instanceId: frame.instance.id, name: frame.instance.name },
+ peers: [],
+ syncStatus: null,
+ },
+ reviewCounts: c.reviewTotal == null ? null : { total: c.reviewTotal },
+ notificationCounts: c.notificationsUnread == null ? null : { unread: c.notificationsUnread },
+ };
+}
+
+// The full set of CityScene/CityHud props a snapshot frame can drive. The page
+// spreads these OVER the live props, so any prop NOT returned here (memoryGraph,
+// goals, jiraTickets, activityCalendar, productivityData, chronotype, etc.) keeps
+// its live value — the deliberate "freeze unfed landmarks at live" behavior.
+//
+// Returns null when the frame isn't playable (wrong/absent schemaVersion) so the
+// caller can keep showing live data and flag the frame.
+export function mergeFrameIntoCityProps(frame, live = {}) {
+ if (!isPlayableFrame(frame)) return null;
+ const apps = buildPlaybackApps(frame, live.apps);
+ const agentMap = buildPlaybackAgentMap(frame, apps);
+ return {
+ apps,
+ agentMap,
+ ...deriveCountProps(frame),
+ };
+}
diff --git a/client/src/lib/cityPlaybackFrame.test.js b/client/src/lib/cityPlaybackFrame.test.js
new file mode 100644
index 0000000000..7594e7f490
--- /dev/null
+++ b/client/src/lib/cityPlaybackFrame.test.js
@@ -0,0 +1,126 @@
+import { describe, it, expect } from 'vitest';
+import {
+ isPlayableFrame,
+ buildPlaybackApps,
+ buildPlaybackAgentMap,
+ mergeFrameIntoCityProps,
+ SUPPORTED_SNAPSHOT_SCHEMA_VERSION,
+} from './cityPlaybackFrame.js';
+
+const liveApps = [
+ { id: 'a1', name: 'App One', overallStatus: 'online', archived: false, processes: [{ name: 'api' }], repoPath: '/repos/a1', type: 'express' },
+ { id: 'a2', name: 'App Two', overallStatus: 'online', archived: false, processes: [], repoPath: '/repos/a2', type: 'express' },
+];
+
+const frame = (over = {}) => ({
+ ts: '2026-06-05T12:00:00.000Z',
+ schemaVersion: SUPPORTED_SNAPSHOT_SCHEMA_VERSION,
+ apps: [
+ { id: 'a1', name: 'App One', status: 'stopped' },
+ { id: 'a2', name: 'App Two', status: 'online' },
+ ],
+ assignments: [{ agentId: 'agent-1', appId: 'a1', status: 'running' }],
+ counts: {
+ appsOnline: 1, appsTotal: 2, agentsActive: 1, agentsPaused: 0,
+ tasksCompleted: 7, tasksPending: 2, tasksInProgress: 1,
+ peersOnline: 1, peersTotal: 2, notificationsUnread: 3, reviewTotal: 4,
+ },
+ cos: { running: true, paused: false },
+ backup: { status: 'success', lastRun: '2026-06-05T00:00:00.000Z' },
+ health: { cpuPercent: 12, memPercent: 40, diskPercent: 55 },
+ character: { level: 4 },
+ instance: { id: 'inst-1', name: 'void' },
+ ...over,
+});
+
+describe('isPlayableFrame', () => {
+ it('accepts a frame on the supported schema version', () => {
+ expect(isPlayableFrame(frame())).toBe(true);
+ });
+ it('rejects a frame with a mismatched or absent schemaVersion', () => {
+ expect(isPlayableFrame(frame({ schemaVersion: 99 }))).toBe(false);
+ expect(isPlayableFrame({ ...frame(), schemaVersion: undefined })).toBe(false);
+ expect(isPlayableFrame(null)).toBe(false);
+ });
+});
+
+describe('buildPlaybackApps', () => {
+ it('overrides live overallStatus with the frame status, keeping render-only fields', () => {
+ const apps = buildPlaybackApps(frame(), liveApps);
+ expect(apps).toHaveLength(2);
+ const a1 = apps.find(a => a.id === 'a1');
+ expect(a1.overallStatus).toBe('stopped'); // overridden from frame
+ expect(a1.processes).toEqual([{ name: 'api' }]); // recovered from live
+ expect(a1.repoPath).toBe('/repos/a1');
+ });
+
+ it('drops live apps absent from the frame (teardown)', () => {
+ const f = frame({ apps: [{ id: 'a1', name: 'App One', status: 'online' }] });
+ const apps = buildPlaybackApps(f, liveApps);
+ expect(apps.map(a => a.id)).toEqual(['a1']);
+ });
+
+ it('renders a minimal building for a frame app no longer live', () => {
+ const f = frame({ apps: [{ id: 'gone', name: 'Ghost', status: 'stopped' }] });
+ const apps = buildPlaybackApps(f, liveApps);
+ expect(apps).toEqual([{ id: 'gone', name: 'Ghost', overallStatus: 'stopped', archived: false, processes: [] }]);
+ });
+
+ it('falls back to live apps when the frame apps array is null (failed capture)', () => {
+ const f = frame({ apps: null });
+ expect(buildPlaybackApps(f, liveApps)).toBe(liveApps);
+ });
+});
+
+describe('buildPlaybackAgentMap', () => {
+ it('rebuilds the agentMap keyed by appId from assignments', () => {
+ const apps = buildPlaybackApps(frame(), liveApps);
+ const map = buildPlaybackAgentMap(frame(), apps);
+ expect(map.get('a1').agents).toEqual([{ agentId: 'agent-1', status: 'running' }]);
+ expect(map.has('a2')).toBe(false);
+ });
+
+ it('returns an empty map when assignments are null', () => {
+ const apps = buildPlaybackApps(frame(), liveApps);
+ const map = buildPlaybackAgentMap(frame({ assignments: null }), apps);
+ expect(map.size).toBe(0);
+ });
+});
+
+describe('mergeFrameIntoCityProps', () => {
+ it('returns null for an unplayable frame so the page keeps live data', () => {
+ expect(mergeFrameIntoCityProps(frame({ schemaVersion: 99 }), { apps: liveApps })).toBeNull();
+ });
+
+ it('maps counts/health/cos/backup/character into scene props', () => {
+ const props = mergeFrameIntoCityProps(frame(), { apps: liveApps });
+ expect(props.cosStatus).toMatchObject({ running: true, activeAgents: 1, stats: { tasksCompleted: 7 } });
+ expect(props.backupStatus).toEqual({ status: 'success', lastRun: '2026-06-05T00:00:00.000Z' });
+ expect(props.systemHealth.system.cpu.usagePercent).toBe(12);
+ expect(props.systemHealth.system.disk.usagePercent).toBe(55);
+ expect(props.character).toEqual({ level: 4 });
+ expect(props.reviewCounts).toEqual({ total: 4 });
+ expect(props.notificationCounts).toEqual({ unread: 3 });
+ expect(props.instances.self).toEqual({ instanceId: 'inst-1', name: 'void' });
+ });
+
+ it('passes null (not a fabricated 0) when a frame field was unavailable at capture', () => {
+ const props = mergeFrameIntoCityProps(
+ frame({ cos: null, backup: null, character: null, health: { cpuPercent: null, memPercent: null, diskPercent: null }, counts: { reviewTotal: null, notificationsUnread: null } }),
+ { apps: liveApps },
+ );
+ expect(props.cosStatus).toBeNull();
+ expect(props.backupStatus).toBeNull();
+ expect(props.character).toBeNull();
+ expect(props.systemHealth).toBeNull();
+ expect(props.reviewCounts).toBeNull();
+ expect(props.notificationCounts).toBeNull();
+ });
+
+ it('does NOT return unfed landmark props, so the page leaves them at live values', () => {
+ const props = mergeFrameIntoCityProps(frame(), { apps: liveApps });
+ for (const key of ['memoryGraph', 'goals', 'jiraTickets', 'activityCalendar', 'productivityData', 'chronotype']) {
+ expect(props).not.toHaveProperty(key);
+ }
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index ea94f2b4f7..eeb365614f 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -50,6 +50,7 @@ export * from './upsertByIdPrepend.js';
export * from './voiceLabel.js';
// === Page-scoped pure helpers ===
+export * from './cityPlaybackFrame.js';
export * from './universeBuilderExpand.js';
export * from './wrSceneCursor.js';
export * from './writingGuide.js';
diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsx
index e9bfdf7c14..b8417184cb 100644
--- a/client/src/pages/CyberCity.jsx
+++ b/client/src/pages/CyberCity.jsx
@@ -1,14 +1,17 @@
import { useCallback, useState, useEffect, useMemo, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useCityData } from '../hooks/useCityData';
+import { useCityPlayback } from '../hooks/useCityPlayback';
import useCityAudio from '../hooks/useCityAudio';
import useKeyboardControls from '../hooks/useKeyboardControls';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { mergeFrameIntoCityProps } from '../lib/cityPlaybackFrame';
import * as api from '../services/api';
import CityScene from '../components/city/CityScene';
import CityHud from '../components/city/CityHud';
import CityScanlines from '../components/city/CityScanlines';
import CityPhotoOverlay from '../components/city/CityPhotoOverlay';
+import CityPlaybackOverlay from '../components/city/CityPlaybackOverlay';
import { CitySettingsProvider, useCitySettingsContext } from '../components/city/CitySettingsContext';
import CitySettingsPanel from '../components/city/CitySettingsPanel';
import { computeFilterResult } from '../utils/cityFilter';
@@ -113,14 +116,27 @@ function CyberCityInner() {
const captureFnRef = useRef(null);
const handlePhotoCaptureReady = useCallback((fn) => { captureFnRef.current = fn; }, []);
- // Entering photo mode leaves exploration; they're mutually exclusive camera modes.
+ // Playback / "history" mode (roadmap 3.6): scrub recorded city-state snapshots.
+ // Transport state lives in the hook; the page swaps the current frame's data
+ // into the scene props below. Mutually exclusive with photo mode.
+ const playback = useCityPlayback();
+
+ // Entering photo mode leaves exploration + playback; they're mutually exclusive modes.
const enterPhotoMode = useCallback(() => {
updateSetting('explorationMode', false);
+ playback.exit();
setPhotoPresetId(DEFAULT_PRESET_ID);
setPhotoMode(true);
- }, [updateSetting]);
+ }, [updateSetting, playback]);
const exitPhotoMode = useCallback(() => setPhotoMode(false), []);
+ // Entering playback leaves photo + exploration mode.
+ const enterPlayback = useCallback(() => {
+ setPhotoMode(false);
+ updateSetting('explorationMode', false);
+ playback.enter();
+ }, [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.
useEffect(() => {
@@ -137,6 +153,22 @@ function CyberCityInner() {
return () => window.removeEventListener('keydown', onKey);
}, [photoMode]);
+ // Playback keyboard transport: Esc exits, Space play/pause, ←/→ step a frame.
+ // Bound only while playback is active. Ignores key events while typing.
+ useEffect(() => {
+ if (!playback.active) return;
+ const onKey = (e) => {
+ const tag = e.target?.tagName;
+ if (tag === 'INPUT' || tag === 'TEXTAREA') return;
+ if (e.key === 'Escape') playback.exit();
+ else if (e.key === ' ') { e.preventDefault(); playback.togglePlay(); }
+ else if (e.key === 'ArrowLeft') playback.step(-1);
+ else if (e.key === 'ArrowRight') playback.step(1);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [playback.active, playback]);
+
// Task-complete chime (roadmap 3.4): when a CoS task transitions to completed, play a reward
// chime. Track the set of completed ids across socket updates and chime on each newly-seen one.
// Seeded on first populated render (completedSeenRef === null) so a fresh page load doesn't
@@ -257,6 +289,19 @@ function CyberCityInner() {
};
}, [apps, cosAgents, instances, character, productivityData]);
+ // In playback mode, overlay the current snapshot frame's data onto the props
+ // the scene + HUD consume. mergeFrameIntoCityProps returns ONLY the
+ // snapshot-backed props (apps, agentMap, counts, health, cos, backup,
+ // character, instances), so anything it omits (memoryGraph, goals, jira,
+ // activity, productivity) keeps its live value — the "freeze unfed landmarks
+ // at live" behavior. Returns null for an unplayable frame → keep live.
+ const playbackProps = useMemo(() => {
+ if (!playback.active || !playback.currentFrame) return null;
+ return mergeFrameIntoCityProps(playback.currentFrame, { apps });
+ }, [playback.active, playback.currentFrame, apps]);
+
+ const v = useCallback((key, live) => (playbackProps && key in playbackProps ? playbackProps[key] : live), [playbackProps]);
+
if (loading) {
return (
<div className="flex flex-col items-center justify-center h-full gap-4 cybercity-themed" style={{ background: cityPalette.background }}>
@@ -278,13 +323,13 @@ function CyberCityInner() {
<CityScene
key={cityPalette.themeId}
background={sceneBackground}
- apps={apps}
- agentMap={agentMap}
+ apps={v('apps', apps)}
+ agentMap={v('agentMap', agentMap)}
onBuildingClick={handleBuildingClick}
- cosStatus={cosStatus}
- reviewCounts={reviewCounts}
- instances={instances}
- backupStatus={backupStatus}
+ cosStatus={v('cosStatus', cosStatus)}
+ reviewCounts={v('reviewCounts', reviewCounts)}
+ instances={v('instances', instances)}
+ backupStatus={v('backupStatus', backupStatus)}
cosTasks={cosTasks}
healthMetrics={healthMetrics}
voiceState={voiceState}
@@ -292,11 +337,12 @@ function CyberCityInner() {
productivityData={productivityData}
activityCalendar={activityCalendar}
goals={goalsData}
- character={character}
+ character={v('character', character)}
chronotype={chronotypeData}
memoryGraph={memoryGraph}
inboxDepth={inboxData?.counts?.needs_review ?? 0}
jiraTickets={jiraTickets}
+ playback={playback.active}
photoMode={photoMode}
photoPresetId={photoPresetId}
photoDof={photoDof}
@@ -306,8 +352,9 @@ function CyberCityInner() {
keysRef={keysRef}
dimmedAppIds={filterResult.dimmed}
/>
- {/* The full HUD hides in photo mode so captures are clean; the photo overlay replaces it. */}
- {!photoMode && (
+ {/* The full HUD hides in photo + playback mode so the view is clean; each
+ mode's overlay replaces it. */}
+ {!photoMode && !playback.active && (
<CityHud
cosStatus={cosStatus}
cosAgents={cosAgents}
@@ -329,6 +376,7 @@ function CyberCityInner() {
explorationMode={settings?.explorationMode}
onSelectApp={handleBuildingClick}
onEnterPhotoMode={enterPhotoMode}
+ onEnterPlayback={enterPlayback}
/>
)}
<CityPhotoOverlay
@@ -341,6 +389,20 @@ function CyberCityInner() {
dofEnabled={photoDof}
onToggleDof={() => setPhotoDof(v => !v)}
/>
+ <CityPlaybackOverlay
+ active={playback.active}
+ loading={playback.loading}
+ snapshots={playback.snapshots}
+ frameIndex={playback.frameIndex}
+ currentFrame={playback.currentFrame}
+ playing={playback.playing}
+ speed={playback.speed}
+ onSeek={playback.seek}
+ onStep={playback.step}
+ onTogglePlay={playback.togglePlay}
+ onCycleSpeed={playback.cycleSpeed}
+ onExit={playback.exit}
+ />
<CityScanlines settings={settings} crt={cityPalette.crt} />
{showSettings && <CitySettingsPanel />}
</div>
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 1bbcd68498..afa86c6aaf 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -101,6 +101,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiOpenClaw.js` | File browser / picker backend. |
| `apiPalette.js` | Command-palette manifest + action dispatch. |
| `apiVoice.js` | Voice synthesis / processing. |
+| `apiCity.js` | CyberCity snapshots — historical city-state series for the timeline scrubber (GET /snapshots, GET /config, POST /capture). |
## Browser-facing (DOM, voice, build) — not pure API wrappers
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 5ecf14332c..79c4efd5ea 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -53,6 +53,7 @@ export * from './apiImporter.js';
export * from './apiStoryBuilder.js';
export * from './apiVoice.js';
export * from './apiAuth.js';
+export * from './apiCity.js';
// Default export for simplified imports (get/post/put/delete helpers)
export { default } from './apiCore.js';
diff --git a/client/src/services/apiCity.js b/client/src/services/apiCity.js
new file mode 100644
index 0000000000..b268badeef
--- /dev/null
+++ b/client/src/services/apiCity.js
@@ -0,0 +1,23 @@
+import { request } from './apiCore.js';
+
+// CyberCity snapshots — historical city-state series for the timeline scrubber.
+// The capture pipeline (issue #877) records frames server-side; these read them.
+
+// GET /api/city/snapshots — the recorded series, oldest-first.
+// options: { since?: ISO string, limit?: number, silent?: boolean }
+export const getCitySnapshots = (options = {}) => {
+ const { since, limit, ...rest } = options;
+ const params = new URLSearchParams();
+ if (since) params.set('since', since);
+ if (limit != null) params.set('limit', limit);
+ const qs = params.toString();
+ return request(`/city/snapshots${qs ? `?${qs}` : ''}`, rest);
+};
+
+// GET /api/city/snapshots/config — effective capture config + next run time.
+export const getCitySnapshotConfig = (options = {}) =>
+ request('/city/snapshots/config', options);
+
+// POST /api/city/snapshots/capture — capture a frame on demand.
+export const captureCitySnapshot = (options = {}) =>
+ request('/city/snapshots/capture', { method: 'POST', ...options });
diff --git a/docs/plans/2026-06-05-issue-967.md b/docs/plans/2026-06-05-issue-967.md
new file mode 100644
index 0000000000..7503650515
--- /dev/null
+++ b/docs/plans/2026-06-05-issue-967.md
@@ -0,0 +1,164 @@
+# Plan — CyberCity timeline scrubber (playback mode) — issue #967
+
+## Context
+
+Follow-up to #877. The snapshot-capture pipeline shipped (PR #966): the City records a
+compact state frame every ~5 min to a rolling capped store, readable via
+`GET /api/city/snapshots`. This issue is the **scrubber slice** — the 3D HUD that *replays*
+that history: a playback mode on `/city` where dragging a timeline drives the scene from a
+past frame instead of live data, with buildings appearing/disappearing via construction/
+teardown animations and recoloring on status change (roadmap 3.6).
+
+**Scope decided with the user:**
+- **Landmark data:** playback drives everything the snapshot *can* feed (buildings, agent
+ assignments, counts/HUD, health tower, backup vault, task queue, federation, character).
+ Landmarks the snapshot can't feed (memory district, goal monuments, jira, activity heatmap,
+ productivity) keep their **live** data, visually static during scrub — the scrubber HUD
+ notes which readouts are time-accurate vs. live.
+- **Animations:** buildings **scale-in from 0** on appear (construction), **scale-out to 0**
+ on disappear (teardown), and **recolor** with a brief transition on status change.
+- **Control:** full transport — draggable timeline, **play/pause**, **speed** (1×/2×/4×),
+ ←/→ step, Esc exit. Mirrors the existing photo-mode overlay pattern.
+
+This completes roadmap 3.6 and closes #967.
+
+## Approach
+
+Mirror the **photoMode** structure in `CyberCity.jsx` (an established "special mode" with a
+toggle, keyboard handling, and an overlay rendered alongside `CityHud`). In playback mode the
+page **substitutes a derived snapshot frame** for the live props it passes to `CityScene`,
+leaving the live data hook untouched. Buildings gain a small scale-animation layer keyed off a
+per-app transition signal. The snapshot series is fetched once via a new client API wrapper.
+
+### New files
+
+- **`client/src/services/apiCity.js`** — wrappers over the shipped endpoints:
+ `getCitySnapshots({ since, limit, silent })` → `GET /api/city/snapshots`,
+ `getCitySnapshotConfig(opts)` → `GET /api/city/snapshots/config`,
+ `captureCitySnapshot(opts)` → `POST /api/city/snapshots/capture`. Use the `request()` helper
+ from `apiCore.js` with an `options` param (silent-capable), per the services convention.
+ **Maintenance rule:** re-export from `client/src/services/api.js` barrel + add a row to
+ `client/src/services/README.md` (enforced by the services barrel test).
+
+- **`client/src/hooks/useCityPlayback.js`** — owns playback state + transport, so `CyberCity.jsx`
+ stays lean. Returns `{ active, enter, exit, snapshots, frameIndex, currentFrame, setFrameIndex,
+ playing, togglePlay, speed, cycleSpeed, loading, frameTimestamps }`. Fetches the series on
+ `enter()` via `apiCity.getCitySnapshots({ limit: <cap> })` (reuse `useAutoRefetch` for the
+ fetch + last-good semantics, or a one-shot fetch in `enter`). Auto-advance uses a
+ `setInterval` driven by `speed`, guarded by a `mountedRef` + cleared on pause/exit/unmount
+ (per CLAUDE.md deferred-work rule). `useCityPlayback.js` → barrel + README row in
+ `client/src/hooks/` (enforced).
+
+- **`client/src/lib/cityPlaybackFrame.js`** — pure helper `mergeFrameIntoCityProps(frame, live)`
+ that maps a snapshot frame onto the prop shape `CityScene` consumes:
+ - `apps`: take each `frame.apps[]` `{id,name,status}`, look up the live app by id to recover
+ render-only fields (`processes`, `repoPath`, `type`, `archived`), and **override
+ `overallStatus`** with the frame's status. Apps absent from the frame are dropped (they'll
+ teardown-animate out); apps present in the frame but not live render from the compact fields
+ with sane defaults. Honor `frame.apps === null` (source failed) → fall back to live `apps`,
+ not an empty city.
+ - `agentMap`: rebuild from `frame.assignments[]` (`{agentId, appId, status}`) as
+ `Map<appId, { app, agents: [{agentId, status}] }>`. `null` assignments → empty map.
+ - `cosStatus`/`backupStatus`/counts-derived HUD values/`character`/health: map from
+ `frame.cos`, `frame.backup`, `frame.counts`, `frame.character`, `frame.health`. A `null`
+ field means "unavailable at capture" → pass `null`/omit so the component shows its empty
+ state, never a fabricated zero.
+ - Returns ONLY the snapshot-backed props; the page spreads these over the live ones, so
+ unfed landmark props (memoryGraph, goals, jira, activityCalendar, productivityData) pass
+ through live untouched (the "freeze at live" decision).
+ - Pure + unit-tested → `client/src/lib/` barrel + README row (enforced).
+
+- **`client/src/components/city/CityPlaybackOverlay.jsx`** — the transport HUD, mirroring
+ `CityPhotoOverlay.jsx`'s bottom control bar. A bottom strip with: play/pause button, speed
+ cycle (1×/2×/4×), a range-input timeline slider bound to `frameIndex`, ←/→ step buttons, the
+ current frame's timestamp (`formatDateTime`) + `timeAgo`, a small legend noting which
+ readouts are historical vs. live (frozen), and an `[ EXIT ]` button. Uses the same
+ `font-pixel` / cyan token styling. `active` prop gates render (like the photo overlay).
+
+### Modified files
+
+- **`client/src/pages/CyberCity.jsx`** — add playback alongside photoMode:
+ - `const playback = useCityPlayback();`
+ - Compute the scene props once: when `playback.active && playback.currentFrame`, derive
+ `mergeFrameIntoCityProps(currentFrame, liveProps)` and spread over the live values passed to
+ `CityScene`; otherwise pass live as today. Pass a `playbackFrame`/`transitionSignal` so the
+ scene/buildings can animate (see below).
+ - Render `{!photoMode && !playback.active && <CityHud … onEnterPlayback={playback.enter} />}`
+ and `<CityPlaybackOverlay active={playback.active} … />` next to `CityPhotoOverlay`.
+ - Keyboard handler mirroring photo mode (Esc exit, Space play/pause, ←/→ step) bound only
+ while `playback.active`, ignoring INPUT/TEXTAREA.
+ - Photo mode and playback are mutually exclusive (entering one exits the other).
+
+- **`client/src/components/city/CityHud.jsx`** — add an entry button in the existing
+ bottom-left control stack (next to the photo-mode button), `onEnterPlayback` prop, e.g.
+ "⟲ HISTORY". Gate it out when no snapshots exist yet (optional: always show; overlay shows an
+ empty-state).
+
+- **`client/src/components/city/Building.jsx`** — add the construction/teardown + recolor
+ animation layer on the existing outer `<group>` (it already runs a `useFrame`):
+ - Track a `mountScaleRef` that lerps `group.scale` 0→1 on mount (construction) using the
+ existing clock-driven `useFrame` (damp toward target). This makes any newly-appearing
+ building rise in during scrub, with no per-frame React churn.
+ - Teardown: a building leaving the `apps` array unmounts immediately in React today. To
+ animate *out*, the cluster must keep it mounted briefly — handle teardown in
+ `BuildingCluster.jsx` (below) by retaining "exiting" apps for one animation beat with a
+ `transitionState: 'exiting'` prop; `Building` lerps scale→0 then signals removal.
+ - Status recolor: `getBuildingColor` is currently computed once; lerp the body/edge material
+ color toward the new status color when `app.overallStatus` changes (damp in `useFrame`),
+ rather than snapping. Keep it cheap — reuse `THREE.MathUtils.damp`/`Color.lerp`.
+
+- **`client/src/components/city/BuildingCluster.jsx`** — own the enter/exit lifecycle so
+ teardown can animate: track previous app id set; when an app id disappears between frames,
+ keep rendering its `Borough` with `transitionState='exiting'` for one beat (a short timer or
+ an `onExited` callback from `Building`), then drop it. New ids render with
+ `transitionState='entering'`. This is the only place that needs the diff; `Borough` just
+ forwards the flag to `Building`. Keep keyed by `app.id` so React reuse still holds.
+
+### Reuse (don't re-implement)
+
+- `request` (`client/src/services/apiCore.js`) — API wrappers; `{ silent: true }` to suppress toasts.
+- `useAutoRefetch` (`client/src/hooks/useAutoRefetch.js`) — series fetch with last-good semantics.
+- `formatDateTime` / `formatClockTime` / `timeAgo` (`client/src/utils/formatters.js`) — timeline labels.
+- Photo-mode structure in `CyberCity.jsx` + `CityPhotoOverlay.jsx` — the overlay/keyboard template.
+- `cityDayMix`, `getBuildingColor`, `getBuildingHeight`, `getAccentColor` (`cityConstants.js`) — reuse for recolor lerp targets.
+- The `dimmed`/`isProximity` per-app prop-forwarding path (`BuildingCluster`→`Borough`→`Building`) — the exact seam for the new `transitionState` prop.
+
+### Animation strategy note (kept contained)
+
+All animation rides the **existing `useFrame` clock loop** in `Building.jsx` — no new
+animation library, no React re-render per frame. Scrubbing changes the `apps` array (React
+diff handles enter/recolor); teardown is the one case needing a retain-for-one-beat in the
+cluster. Scene stays on `frameloop='always'` so the slider feels live (photo mode's `'demand'`
+freeze does NOT apply here).
+
+## Migration / compat / changelog obligations
+
+- **No NAV_COMMANDS entry** — playback lives inside the existing `/city` route (no new page),
+ per the issue. (Confirmed: photo mode added none either.)
+- **No server change, no migration** — read-only consumer of the shipped `GET /api/city/snapshots`.
+ Honor `schemaVersion` on each frame: if `frame.schemaVersion !== SNAPSHOT_SCHEMA_VERSION`, skip/
+ flag that frame in the overlay rather than mis-rendering (forward-compat for a future bump).
+- **Barrel + README** — every new `apiCity.js` / `useCityPlayback.js` / `cityPlaybackFrame.js`
+ gets its barrel re-export + README row (server/client barrel tests enforce this; boot/test
+ fails loudly otherwise).
+- **Changelog** — one user-facing entry under `[issue-967]` in `.changelog/NEXT.md`.
+
+## Verification
+
+1. **Unit tests:**
+ - `client/src/lib/cityPlaybackFrame.test.js` — frame→props mapping: status override, agentMap
+ rebuild from assignments, `null`-field fallthrough (failed source → live, not fabricated 0),
+ apps added/removed between frames, `schemaVersion` mismatch handling.
+ - `client/src/services/api.test.*` / hooks test — apiCity wrappers hit the right paths with
+ `since`/`limit`; `useCityPlayback` transport (enter loads series, step clamps at ends,
+ play advances + pauses, exit clears the timer).
+2. **Suite:** `cd client && npm test` (Vitest/jsdom) green; `cd server && npm test` still green
+ (no server change, but the barrel/README enforcement tests run there too — confirm clean).
+ `npm run build --prefix client` succeeds (lint + bundle).
+3. **Manual end-to-end:** start the app, open `/city`, click "⟲ HISTORY". Confirm: the slider
+ scrubs through frames; buildings appear/teardown and recolor as status changes between
+ frames; play/pause auto-advances at the selected speed; ←/→ step; Esc exits back to live;
+ frozen landmarks are labeled as live. Seed history quickly by lowering `intervalMinutes` (or
+ `POST /api/city/snapshots/capture` a few times) so there are several frames to scrub.
+4. **Review:** `/simplify`, then the claude+codex dual-review loop (per the `--review-with` flag),
+ converge to mutual CLEAN before merge.