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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: City scene GPU leaks, audio pops, and silent loss of unsaved writing
[._.]/ Adam Eivyde25e9184e79
diff --git a/client/src/components/city/Building.jsx b/client/src/components/city/Building.jsxindex 917db52a23..1c0e12aee6 100644--- a/client/src/components/city/Building.jsx+++ b/client/src/components/city/Building.jsx@@ -452,6 +452,17 @@ export default function Building({ app, position, agentCount, onClick, playSfx,const boxGeom = useMemo(() => new THREE.BoxGeometry(width, height, depth), [width, height, depth]);const edgesGeom = useMemo(() => new THREE.EdgesGeometry(boxGeom), [boxGeom]);+ useEffect(() => () => boxGeom.dispose(), [boxGeom]);+ useEffect(() => () => edgesGeom.dispose(), [edgesGeom]);++ // Night-only glow halo: memoized so re-renders don't force R3F to rebuild the+ // edges geometry (an inline `new THREE.BoxGeometry` in args changes identity+ // every render), and disposed on replace + unmount like the geometries above.+ const haloEdgesGeom = useMemo(+ () => new THREE.EdgesGeometry(new THREE.BoxGeometry(width + 0.15, height + 0.15, depth + 0.15)),+ [width, height, depth]+ );+ useEffect(() => () => haloEdgesGeom.dispose(), [haloEdgesGeom]);// Window texture with pixel art iconconst windowTexture = useMemo(@@ -609,8 +620,7 @@ export default function Building({ app, position, agentCount, onClick, playSfx,{/* Glow halo wireframe - slightly larger than building (night only) */}{!app.archived && !daytime && (- <lineSegments ref={haloRef} position={[0, height / 2, 0]}>- <edgesGeometry args={[new THREE.BoxGeometry(width + 0.15, height + 0.15, depth + 0.15)]} />+ <lineSegments ref={haloRef} position={[0, height / 2, 0]} geometry={haloEdgesGeom}><lineBasicMaterialcolor={accentColor}transparentdiff --git a/client/src/components/city/BuildingHologram.jsx b/client/src/components/city/BuildingHologram.jsxindex 3dc7b8feb8..e54b19fad8 100644--- a/client/src/components/city/BuildingHologram.jsx+++ b/client/src/components/city/BuildingHologram.jsx@@ -1,18 +1,43 @@-import { useRef, useMemo } from 'react';+import { useRef } from 'react';import { useFrame } from '@react-three/fiber';import * as THREE from 'three';const HOLOGRAM_TYPES = ['diamond', 'invertedPyramid', 'saturn', 'rings', 'cube', 'beacon'];+// Every Holo* shape's geometry below has fixed parameters — `color`/`seed` only+// drive material/animation, never geometry — so each is a module-scope singleton+// shared by every hologram instance, mirroring Building.jsx's ROOF_GEOMS pattern.+// A per-instance useMemo would otherwise allocate fresh, never-disposed GPU+// geometry on every mount, and holograms mount/unmount on every dim/undim.+const DIAMOND_GEOM = new THREE.OctahedronGeometry(0.5, 0);+const DIAMOND_EDGES = new THREE.EdgesGeometry(DIAMOND_GEOM);++const PYRAMID_GEOM = new THREE.ConeGeometry(0.5, 0.8, 4);+const PYRAMID_EDGES = new THREE.EdgesGeometry(PYRAMID_GEOM);++const SATURN_SPHERE_GEOM = new THREE.IcosahedronGeometry(0.25, 1);+const SATURN_RING_GEOM = new THREE.TorusGeometry(0.5, 0.025, 8, 32);+const SATURN_SPHERE_EDGES = new THREE.EdgesGeometry(SATURN_SPHERE_GEOM);++const RINGS_GEOMS = [+ new THREE.TorusGeometry(0.45, 0.02, 8, 24),+ new THREE.TorusGeometry(0.3, 0.02, 8, 24),+ new THREE.TorusGeometry(0.38, 0.02, 8, 24),+];++const CUBE_GEOM = new THREE.BoxGeometry(0.45, 0.45, 0.45);+const CUBE_EDGES = new THREE.EdgesGeometry(CUBE_GEOM);++const BEACON_CYL_GEOM = new THREE.CylinderGeometry(0.025, 0.025, 0.5, 6);+const BEACON_SPHERE_GEOM = new THREE.SphereGeometry(0.15, 8, 8);+function HoloDiamond({ color }) {- const geom = useMemo(() => new THREE.OctahedronGeometry(0.5, 0), []);- const edges = useMemo(() => new THREE.EdgesGeometry(geom), [geom]);return (<group>- <mesh geometry={geom}>+ <mesh geometry={DIAMOND_GEOM}><meshBasicMaterial color={color} transparent opacity={0.12} side={THREE.DoubleSide} /></mesh>- <lineSegments geometry={edges}>+ <lineSegments geometry={DIAMOND_EDGES}><lineBasicMaterial color={color} transparent opacity={0.85} /></lineSegments></group>@@ -20,14 +45,12 @@ function HoloDiamond({ color }) {}function HoloPyramid({ color }) {- const geom = useMemo(() => new THREE.ConeGeometry(0.5, 0.8, 4), []);- const edges = useMemo(() => new THREE.EdgesGeometry(geom), [geom]);return (<group rotation={[Math.PI, 0, Math.PI / 4]}>- <mesh geometry={geom}>+ <mesh geometry={PYRAMID_GEOM}><meshBasicMaterial color={color} transparent opacity={0.12} side={THREE.DoubleSide} /></mesh>- <lineSegments geometry={edges}>+ <lineSegments geometry={PYRAMID_EDGES}><lineBasicMaterial color={color} transparent opacity={0.85} /></lineSegments></group>@@ -35,18 +58,15 @@ function HoloPyramid({ color }) {}function HoloSaturn({ color }) {- const sphereGeom = useMemo(() => new THREE.IcosahedronGeometry(0.25, 1), []);- const ringGeom = useMemo(() => new THREE.TorusGeometry(0.5, 0.025, 8, 32), []);- const sphereEdges = useMemo(() => new THREE.EdgesGeometry(sphereGeom), [sphereGeom]);return (<group>- <mesh geometry={sphereGeom}>+ <mesh geometry={SATURN_SPHERE_GEOM}><meshBasicMaterial color={color} transparent opacity={0.15} /></mesh>- <lineSegments geometry={sphereEdges}>+ <lineSegments geometry={SATURN_SPHERE_EDGES}><lineBasicMaterial color={color} transparent opacity={0.7} /></lineSegments>- <mesh geometry={ringGeom} rotation={[Math.PI / 3, 0.3, 0]}>+ <mesh geometry={SATURN_RING_GEOM} rotation={[Math.PI / 3, 0.3, 0]}><meshBasicMaterial color={color} transparent opacity={0.35} side={THREE.DoubleSide} /></mesh></group>@@ -54,14 +74,9 @@ function HoloSaturn({ color }) {}function HoloRings({ color }) {- const geoms = useMemo(() => [- new THREE.TorusGeometry(0.45, 0.02, 8, 24),- new THREE.TorusGeometry(0.3, 0.02, 8, 24),- new THREE.TorusGeometry(0.38, 0.02, 8, 24),- ], []);return (<group>- {geoms.map((geom, i) => (+ {RINGS_GEOMS.map((geom, i) => (<mesh key={i} geometry={geom} position={[0, (i - 1) * 0.22, 0]} rotation={[Math.PI / 2, 0, 0]}><meshBasicMaterial color={color} transparent opacity={0.45 + i * 0.15} side={THREE.DoubleSide} /></mesh>@@ -71,14 +86,12 @@ function HoloRings({ color }) {}function HoloCube({ color }) {- const geom = useMemo(() => new THREE.BoxGeometry(0.45, 0.45, 0.45), []);- const edges = useMemo(() => new THREE.EdgesGeometry(geom), [geom]);return (<group rotation={[Math.PI / 6, Math.PI / 4, 0]}>- <mesh geometry={geom}>+ <mesh geometry={CUBE_GEOM}><meshBasicMaterial color={color} transparent opacity={0.08} /></mesh>- <lineSegments geometry={edges}>+ <lineSegments geometry={CUBE_EDGES}><lineBasicMaterial color={color} transparent opacity={0.85} /></lineSegments></group>@@ -86,14 +99,12 @@ function HoloCube({ color }) {}function HoloBeacon({ color }) {- const cylGeom = useMemo(() => new THREE.CylinderGeometry(0.025, 0.025, 0.5, 6), []);- const sphereGeom = useMemo(() => new THREE.SphereGeometry(0.15, 8, 8), []);return (<group>- <mesh geometry={cylGeom}>+ <mesh geometry={BEACON_CYL_GEOM}><meshBasicMaterial color={color} transparent opacity={0.5} /></mesh>- <mesh geometry={sphereGeom} position={[0, 0.32, 0]}>+ <mesh geometry={BEACON_SPHERE_GEOM} position={[0, 0.32, 0]}><meshBasicMaterial color={color} transparent opacity={0.75} /></mesh></group>diff --git a/client/src/components/city/CityBillboards.jsx b/client/src/components/city/CityBillboards.jsxindex e77a460853..debd97ba2b 100644--- a/client/src/components/city/CityBillboards.jsx+++ b/client/src/components/city/CityBillboards.jsx@@ -117,6 +117,8 @@ function Billboard({ position, rotation, messages, color, width = 3.5, height =return new THREE.ShapeGeometry(shape);}, [width, height]);+ useEffect(() => () => borderGeom.dispose(), [borderGeom]);+return (<group ref={groupRef} position={position} rotation={rotation}>{/* Billboard background panel (front face only) */}diff --git a/client/src/components/city/CityCelestial.jsx b/client/src/components/city/CityCelestial.jsxindex 451e9b5a78..fdc5167d9a 100644--- a/client/src/components/city/CityCelestial.jsx+++ b/client/src/components/city/CityCelestial.jsx@@ -1,4 +1,4 @@-import { useRef, useMemo } from 'react';+import { useRef, useMemo, useEffect } from 'react';import { useFrame } from '@react-three/fiber';import * as THREE from 'three';import { CITY_COLORS, getTimeOfDayPreset } from './cityConstants';@@ -20,6 +20,7 @@ function OrbitalRing({ radius, tilt, color, opacity = 0.15, nightFactorRef }) {}, [radius]);const geometry = useMemo(() => new THREE.BufferGeometry().setFromPoints(points), [points]);+ useEffect(() => () => geometry.dispose(), [geometry]);const matRef = useRef();useFrame(() => {diff --git a/client/src/components/city/CityDataRain.jsx b/client/src/components/city/CityDataRain.jsxindex 8d61afa0d5..22156b314a 100644--- a/client/src/components/city/CityDataRain.jsx+++ b/client/src/components/city/CityDataRain.jsx@@ -54,12 +54,15 @@ const DATA_RAIN_FRAG = `}`;-export default function CityDataRain() {+export default function CityDataRain({ settings }) {const pointsRef = useRef();const matRef = useRef();+ // Follow CityParticles' quality-dial pattern: scale column count down under the+ // adaptive-quality low tier instead of paying for a fixed 480-point system always.+ const density = settings?.particleDensity ?? 1;const { positions, charIndices, columnPhases, speeds, brightnesses, count } = useMemo(() => {- const columns = 40;+ const columns = Math.max(4, Math.round(40 * density));const charsPerColumn = 12;const total = columns * charsPerColumn;@@ -100,7 +103,7 @@ export default function CityDataRain() {brightnesses: bright,count: total,};- }, []);+ }, [density]);useFrame(({ clock }) => {if (matRef.current) {diff --git a/client/src/components/city/CityEmbers.jsx b/client/src/components/city/CityEmbers.jsxindex 59957b9cbf..944b353b5e 100644--- a/client/src/components/city/CityEmbers.jsx+++ b/client/src/components/city/CityEmbers.jsx@@ -51,12 +51,15 @@ const EMBER_FRAG = `}`;-export default function CityEmbers() {+export default function CityEmbers({ settings }) {const pointsRef = useRef();const matRef = useRef();+ // Follow CityParticles' quality-dial pattern: scale ember count down under the+ // adaptive-quality low tier instead of paying for a fixed 120-point system always.+ const density = settings?.particleDensity ?? 1;const { positions, sizes, speeds, phases, colors, count } = useMemo(() => {- const n = 120;+ const n = Math.max(8, Math.round(120 * density));const pos = new Float32Array(n * 3);const sz = new Float32Array(n);const spd = new Float32Array(n);@@ -88,7 +91,7 @@ export default function CityEmbers() {}return { positions: pos, sizes: sz, speeds: spd, phases: ph, colors: col, count: n };- }, []);+ }, [density]);useFrame(({ clock }) => {if (matRef.current) {diff --git a/client/src/components/city/CityScene.jsx b/client/src/components/city/CityScene.jsxindex bd6d7dc227..785166bdcf 100644--- a/client/src/components/city/CityScene.jsx+++ b/client/src/components/city/CityScene.jsx@@ -310,8 +310,8 @@ export default function CityScene({ apps, agentMap, onBuildingClick, onToggleCam<CityVolumetricLights positions={positions} settings={renderSettings} /><CityNeonSigns positions={positions} /><CityWeather stoppedCount={stoppedCount} totalCount={totalCount} playSfx={playSfx} />- <CityDataRain />- <CityEmbers />+ <CityDataRain settings={renderSettings} />+ <CityEmbers settings={renderSettings} /><CityParticles settings={renderSettings} />{explorationMode && (<PlayerControllerdiff --git a/client/src/components/city/CitySettingsContext.jsx b/client/src/components/city/CitySettingsContext.jsxindex d780f887a0..394b6c7349 100644--- a/client/src/components/city/CitySettingsContext.jsx+++ b/client/src/components/city/CitySettingsContext.jsx@@ -1,4 +1,4 @@-import { createContext, useContext } from 'react';+import { createContext, useContext, useMemo } from 'react';import useCitySettings from '../../hooks/useCitySettings';const CitySettingsContext = createContext(null);@@ -6,8 +6,13 @@ const CitySettingsContext = createContext(null);export function CitySettingsProvider({ children }) {const [settings, updateSetting, resetSettings, resetNonce] = useCitySettings();+ const value = useMemo(+ () => ({ settings, updateSetting, resetSettings, resetNonce }),+ [settings, updateSetting, resetSettings, resetNonce]+ );+return (- <CitySettingsContext.Provider value={{ settings, updateSetting, resetSettings, resetNonce }}>+ <CitySettingsContext.Provider value={value}>{children}</CitySettingsContext.Provider>);diff --git a/client/src/components/city/CityTubeLine.jsx b/client/src/components/city/CityTubeLine.jsxindex 2615613f90..bd536afaed 100644--- a/client/src/components/city/CityTubeLine.jsx+++ b/client/src/components/city/CityTubeLine.jsx@@ -1,4 +1,4 @@-import { useMemo } from 'react';+import { useMemo, useEffect } from 'react';import * as THREE from 'three';// A thin glowing connector rendered as a native-three tube along a curve through `points`.@@ -17,6 +17,8 @@ export default function CityTubeLine({ points, color, radius = 0.08, opacity = 0return new THREE.TubeGeometry(curve, Math.max(segments, pts.length * 8), radius, 6, false);}, [points, radius, segments]);+ useEffect(() => () => geometry?.dispose(), [geometry]);+if (!geometry) return null;return (diff --git a/client/src/components/city/CityVolumetricLights.jsx b/client/src/components/city/CityVolumetricLights.jsxindex 024aec6ebb..6b87939498 100644--- a/client/src/components/city/CityVolumetricLights.jsx+++ b/client/src/components/city/CityVolumetricLights.jsx@@ -47,6 +47,8 @@ function LightBeam({ position, color, height = 15, radius = 2, intensity = 1, phreturn geom;}, [radius, height]);+ useEffect(() => () => coneGeom.dispose(), [coneGeom]);+useFrame(({ clock }) => {if (!matRef.current) return;matRef.current.uniforms.uTime.value = clock.getElapsedTime() + phase;diff --git a/client/src/components/city/ProcessBuilding.jsx b/client/src/components/city/ProcessBuilding.jsxindex e86a5091d5..8c43847956 100644--- a/client/src/components/city/ProcessBuilding.jsx+++ b/client/src/components/city/ProcessBuilding.jsx@@ -1,4 +1,4 @@-import { useRef, useMemo } from 'react';+import { useRef, useMemo, useEffect } from 'react';import { useFrame } from '@react-three/fiber';import * as THREE from 'three';import { PROCESS_BUILDING_PARAMS, PIXEL_FONT_URL, mixHex } from './cityConstants';@@ -45,6 +45,18 @@ export default function ProcessBuilding({ process, pm2Status, position, seed, diconst boxGeom = useMemo(() => new THREE.BoxGeometry(width, height, depth), [width, height, depth]);const edgesGeom = useMemo(() => new THREE.EdgesGeometry(boxGeom), [boxGeom]);+ // edgesGeom is handed to <lineSegments> via a `geometry` prop, so R3F does not+ // manage its disposal the way it would a JSX <edgesGeometry> child. `height`+ // (and thus this geometry) is keyed on `status` — an online process is taller+ // than a stopped/errored one — so every status flip would otherwise strand the+ // previous geometry's GPU buffers, same leak class as Building.jsx's windowTexture.+ useEffect(() => {+ return () => {+ boxGeom.dispose();+ edgesGeom.dispose();+ };+ }, [boxGeom, edgesGeom]);+const displayName = useMemo(() => {return (process.name || '').replace(/[-_.]/g, ' ').toUpperCase();}, [process.name]);diff --git a/client/src/components/city/audio/cityAudioEngine.js b/client/src/components/city/audio/cityAudioEngine.jsindex cf99fdf9ca..e9ce7dccc4 100644--- a/client/src/components/city/audio/cityAudioEngine.js+++ b/client/src/components/city/audio/cityAudioEngine.js@@ -3,12 +3,19 @@ let audioCtx = null;let masterGain = null;let musicGain = null;let sfxGain = null;+let pendingCleanup = null;export const getAudioContext = () => audioCtx;export const getMusicGain = () => musicGain;export const getSfxGain = () => sfxGain;export const initAudio = () => {+ // A remount can re-init while a delayed close (scheduleCleanup) is pending;+ // cancel it so the shared context isn't yanked out from under the new mount.+ if (pendingCleanup) {+ clearTimeout(pendingCleanup);+ pendingCleanup = null;+ }if (audioCtx) return audioCtx;audioCtx = new (window.AudioContext || window.webkitAudioContext)();@@ -36,6 +43,10 @@ export const setSfxVolume = (v) => {};export const cleanup = () => {+ if (pendingCleanup) {+ clearTimeout(pendingCleanup);+ pendingCleanup = null;+ }if (audioCtx && audioCtx.state !== 'closed') {audioCtx.close();}@@ -44,3 +55,19 @@ export const cleanup = () => {musicGain = null;sfxGain = null;};++// Close after `delayMs` (e.g. once a stop-ramp settles) unless initAudio runs+// again first — an immediate close would cut the ramp short, but an+// uncancelled one would kill a remounted consumer's freshly built graph.+export const scheduleCleanup = (delayMs) => {+ if (pendingCleanup) clearTimeout(pendingCleanup);+ if (!delayMs || delayMs <= 0) {+ pendingCleanup = null;+ cleanup();+ return;+ }+ pendingCleanup = setTimeout(() => {+ pendingCleanup = null;+ cleanup();+ }, delayMs);+};diff --git a/client/src/components/city/audio/citySynthMusic.js b/client/src/components/city/audio/citySynthMusic.jsindex 228b4f14fb..118e748521 100644--- a/client/src/components/city/audio/citySynthMusic.js+++ b/client/src/components/city/audio/citySynthMusic.js@@ -20,6 +20,12 @@ let liveBassFilter = null;let livePadOscs = [];let liveArpPeak = 0.06; // peak gain the arp pluck opens to; raised/lowered by energy+// Layer gain nodes, captured in startMusic() so stopMusic() can ramp each audible+// layer to silence before the hard oscillator stop (see stopMusic() below).+let liveBassGain = null;+let livePadGain = null;+let liveArpGain = null;+// Arp note patterns (scale degrees relative to chord root)const ARP_PATTERN = [0, 2, 4, 7, 12, 7, 4, 2];@@ -183,23 +189,68 @@ export const startMusic = () => {// Expose the modulatable nodes so setSoundscape() can ramp them in real time.liveBassFilter = bassFilter;livePadOscs = padOscs;+ liveBassGain = bassGain;+ livePadGain = padGain;+ liveArpGain = arpGain;nodesCleanup.push(reverb, reverbGain, delay, delayFeedback, bassFilter, bassGain, padGain, arpFilter, arpGain);};+// Fade time constant for the pre-stop ramp (setTargetAtTime never truly reaches+// zero, so REST settles ~3 time-constants in — audibly silent well under 100ms).+const STOP_RAMP_TC = 0.02;+// Oscillators are hard-stopped this long after the ramp starts, once the layers+// have settled toward silence, instead of mid-waveform (the audible pop this fixes).+const STOP_SETTLE = 0.08;++// Stops the running music graph. Ramps each audible layer to silence first — an+// abrupt osc.stop() while a waveform is mid-cycle truncates it at a non-zero+// sample, which reads as an audible click/pop on mute toggle or CyberCity unmount.+// Mirrors citySoundEffects.js's envelope-before-stop pattern (setTargetAtTime /+// exponentialRampToValueAtTime before every osc.stop() there).+//+// Returns the settle time in milliseconds so a caller that needs to tear down the+// AudioContext right after (useCityAudio's unmount cleanup) can delay the close+// until the ramp has actually finished, instead of cutting it off immediately.export const stopMusic = () => {+ if (!isPlaying) return 0;isPlaying = false;- oscillators.forEach(osc => {- osc.stop();- osc.disconnect();+ const ctx = getAudioContext();+ const now = ctx ? ctx.currentTime : 0;++ if (ctx) {+ [liveBassGain, livePadGain, liveArpGain].forEach(gainNode => {+ if (gainNode) gainNode.gain.setTargetAtTime(0, now, STOP_RAMP_TC);+ });+ }++ const stopAt = ctx ? now + STOP_SETTLE : 0;+ const pendingOscillators = oscillators;+ const pendingNodes = nodesCleanup;+ pendingOscillators.forEach(osc => {+ if (ctx) osc.stop(stopAt);+ else osc.stop();});+oscillators = [];intervals.forEach(clearInterval);intervals = [];- nodesCleanup.forEach(node => node.disconnect());nodesCleanup = [];- // Drop references to the now-disconnected nodes so a stray setSoundscape() can't ramp a+ // Drop references to the now-stopping nodes so a stray setSoundscape() can't ramp a// dead graph. The next startMusic() re-captures fresh ones.liveBassFilter = null;livePadOscs = [];+ liveBassGain = null;+ livePadGain = null;+ liveArpGain = null;++ // Disconnect after the ramp/stop settles instead of instantly — an immediate+ // disconnect() would cut the fade above short, defeating the point of it.+ const settleMs = ctx ? (STOP_SETTLE + STOP_RAMP_TC) * 1000 : 0;+ setTimeout(() => {+ pendingOscillators.forEach(osc => osc.disconnect());+ pendingNodes.forEach(node => node.disconnect());+ }, settleMs);++ return settleMs;};diff --git a/client/src/components/city/audio/citySynthMusic.test.js b/client/src/components/city/audio/citySynthMusic.test.jsnew file mode 100644index 0000000000..b8fd1c925b--- /dev/null+++ b/client/src/components/city/audio/citySynthMusic.test.js@@ -0,0 +1,174 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// Minimal fake Web Audio graph for citySynthMusic.js. The module pulls its+// context/output gain from cityAudioEngine's getAudioContext()/getMusicGain()+// (module-level singleton getters, not a constructor call or a param it+// receives) and drives: a convolver reverb, a feedback delay, a lowpass bass+// filter, a bandpass arp filter, and several gain-ramped oscillators.+//+// Mirrors the connectable()/fakeParam() idiom from+// src/test/fakeAudioContext.js, extended with createConvolver/createDelay —+// nodes that shared fake doesn't cover but this module actually touches.+const fakeParam = (initial) => {+ const values = [];+ return {+ value: initial,+ values,+ // Records (v, when, timeConstant) so a test can assert the exact ramp the+ // source schedules, not just "some call happened".+ setTargetAtTime: (v, when, tc) => { values.push({ v, when, tc }); },+ };+};++const connectable = () => ({+ connections: [],+ connect(target) { this.connections.push(target); return target; },+ disconnect: vi.fn(),+});++const makeFakeContext = () => {+ const ctx = {+ now: 0,+ get currentTime() { return ctx.now; },+ sampleRate: 48000,+ oscillators: [],+ gains: [],+ createConvolver() {+ return { buffer: null, ...connectable() };+ },+ createBuffer(channels, length, rate) {+ const chans = Array.from({ length: channels }, () => new Float32Array(length));+ return { length, sampleRate: rate, getChannelData: (ch) => chans[ch] };+ },+ createGain() {+ const gain = { gain: fakeParam(1), ...connectable() };+ ctx.gains.push(gain);+ return gain;+ },+ createDelay() {+ return { delayTime: fakeParam(0), ...connectable() };+ },+ createBiquadFilter() {+ return { type: '', frequency: fakeParam(0), Q: { value: 1 }, ...connectable() };+ },+ createOscillator() {+ const osc = {+ type: '',+ frequency: fakeParam(0),+ detune: fakeParam(0),+ started: null,+ stopped: null,+ ...connectable(),+ start(t) { this.started = t; },+ stop: vi.fn(function stop(t) { this.stopped = t; }),+ };+ ctx.oscillators.push(osc);+ return osc;+ },+ };+ return ctx;+};++// Constants read straight from citySynthMusic.js (not exported, so pinned+// here as literals): STOP_RAMP_TC = 0.02 (gain fade time constant),+// STOP_SETTLE = 0.08 (delay before the hard oscillator stop).+const STOP_RAMP_TC = 0.02;+const STOP_SETTLE = 0.08;++let fakeCtx;+let fakeOutput;++vi.mock('./cityAudioEngine', () => ({+ getAudioContext: () => fakeCtx,+ getMusicGain: () => fakeOutput,+}));++let synth;++beforeEach(async () => {+ vi.resetModules();+ fakeCtx = makeFakeContext();+ fakeOutput = { ...connectable() };+ synth = await import('./citySynthMusic.js');+});++afterEach(() => {+ // citySynthMusic schedules real setInterval timers on startMusic(); stop+ // whatever's running so a test that never called stopMusic doesn't leak+ // intervals into later tests. stopMusic() is a documented no-op when+ // already stopped, so this is always safe to call.+ synth.stopMusic();+});++describe('citySynthMusic', () => {+ it('startMusic is a no-op when already playing', () => {+ synth.startMusic();+ const oscCount = fakeCtx.oscillators.length;+ const gainCount = fakeCtx.gains.length;+ expect(oscCount).toBeGreaterThan(0);++ synth.startMusic();+ // No new nodes created — the second call returns before building anything.+ expect(fakeCtx.oscillators.length).toBe(oscCount);+ expect(fakeCtx.gains.length).toBe(gainCount);+ });++ it('stopMusic ramps each audible layer gain to 0 with the settle time constant', () => {+ synth.startMusic();+ fakeCtx.now = 5;+ synth.stopMusic();++ // liveBassGain/livePadGain/liveArpGain are the three layer gains ramped+ // in stopMusic() — identify them by the ramp-to-0 call they each receive.+ const ramped = fakeCtx.gains.filter(g => g.gain.values.some(entry => entry.v === 0));+ expect(ramped).toHaveLength(3);+ for (const g of ramped) {+ expect(g.gain.values.at(-1)).toEqual({ v: 0, when: 5, tc: STOP_RAMP_TC });+ }+ });++ it('stopMusic schedules oscillator stop at a future time, not immediately', () => {+ synth.startMusic();+ fakeCtx.now = 10;+ synth.stopMusic();++ expect(fakeCtx.oscillators.length).toBeGreaterThan(0);+ for (const osc of fakeCtx.oscillators) {+ expect(osc.stop).toHaveBeenCalledTimes(1);+ // A fade-out, not an abrupt cut: stop lands STOP_SETTLE after "now".+ expect(osc.stopped).toBeCloseTo(10 + STOP_SETTLE, 10);+ expect(osc.stopped).toBeGreaterThan(10);+ }+ });++ it('stopMusic returns the settle/fade duration in ms', () => {+ synth.startMusic();+ const settleMs = synth.stopMusic();+ expect(settleMs).toBe((STOP_SETTLE + STOP_RAMP_TC) * 1000);+ });++ it('clears is-playing state so a later startMusic creates fresh nodes', () => {+ synth.startMusic();+ const firstOscCount = fakeCtx.oscillators.length;+ synth.stopMusic();++ synth.startMusic();+ // Not a no-op this time: a fresh set of oscillators was built.+ expect(fakeCtx.oscillators.length).toBe(firstOscCount * 2);+ });++ it('double-stop is safe: no throw and no double-schedule', () => {+ synth.startMusic();+ fakeCtx.now = 3;+ const first = synth.stopMusic();+ expect(first).toBeGreaterThan(0);+ const stopCallCounts = fakeCtx.oscillators.map(o => o.stop.mock.calls.length);++ // stopMusic() guards on `if (!isPlaying) return 0` — the second call is a+ // no-op, matching the guard actually present in the source.+ expect(() => { synth.stopMusic(); }).not.toThrow();+ const second = synth.stopMusic();+ expect(second).toBe(0);+ expect(fakeCtx.oscillators.map(o => o.stop.mock.calls.length)).toEqual(stopCallCounts);+ });+});diff --git a/client/src/components/music/ChiptunePanel.jsx b/client/src/components/music/ChiptunePanel.jsxindex 09c87e4a88..f47ad94271 100644--- a/client/src/components/music/ChiptunePanel.jsx+++ b/client/src/components/music/ChiptunePanel.jsx@@ -223,7 +223,11 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix }) {}};- const canGenerate = !!track?.id && !!prompt.trim() && !!selectedProviderId && !generating;+ // Generate/render/publish all mutate the same track record via RMW writes —+ // letting two fire concurrently races those writes, so gate all three on+ // any one being in flight rather than just their own flag.+ const busy = generating || rendering || publishing;+ const canGenerate = !!track?.id && !!prompt.trim() && !!selectedProviderId && !busy;return (<div className="space-y-2 border border-port-border rounded-lg p-3 bg-port-bg/40">@@ -291,7 +295,7 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix }) {<buttontype="button"onClick={handleRender}- disabled={rendering}+ disabled={busy}title="Render the loop to audio and add it to this track's renders"className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">@@ -301,7 +305,8 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix }) {<buttontype="button"onClick={openPublish}- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"+ disabled={busy}+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"><Gamepad2 size={14} /> Publish to app…</button>@@ -347,7 +352,7 @@ export default function ChiptunePanel({ track, onTrackUpdate, remix }) {<buttontype="button"onClick={handlePublish}- disabled={publishing || !publishAppId}+ disabled={busy || !publishAppId}className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50">{publishing ? <Loader2 size={14} className="animate-spin" /> : <Gamepad2 size={14} />}diff --git a/client/src/components/music/ChiptunePanel.test.jsx b/client/src/components/music/ChiptunePanel.test.jsxnew file mode 100644index 0000000000..e94c133b7b--- /dev/null+++ b/client/src/components/music/ChiptunePanel.test.jsx@@ -0,0 +1,131 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import ChiptunePanel from './ChiptunePanel';+import * as api from '../../services/api';++vi.mock('../../services/api', () => ({+ generateTrackChiptune: vi.fn(),+ renderTrackChiptune: vi.fn(),+ publishTrackChiptune: vi.fn(),+ getApps: vi.fn(),+ getSettings: vi.fn(),+ updateSettings: vi.fn(),+}));++vi.mock('../../hooks/useProviderModels', () => ({+ default: () => ({+ providers: [{ id: 'anthropic', name: 'Anthropic', models: ['claude'], defaultModel: 'claude' }],+ selectedProviderId: 'anthropic',+ selectedModel: 'claude',+ availableModels: ['claude'],+ setSelectedProviderId: vi.fn(),+ setSelectedModel: vi.fn(),+ loading: false,+ }),+}));++const SCORE = {+ title: 'Test Loop',+ bpm: 120,+ stepsPerBeat: 4,+ beatsPerBar: 4,+ channels: [{ id: 'lead', wave: 'square' }],+ patterns: { a: { bars: 1, notes: { lead: [] } } },+ order: ['a'],+};++const TRACK = { id: 'track-1', title: 'My Test Song', chiptunePrompt: 'Bouncy 8-bit theme', chiptuneScore: SCORE };++const GAME_APP = { id: 'game-app', name: 'Game App', repoPath: '/repo/game', archived: false };++// Never-resolving promise, for pinning "in flight" UI states.+const pending = () => new Promise(() => {});++describe('ChiptunePanel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getSettings.mockResolvedValue({ music: {} });+ api.getApps.mockResolvedValue([GAME_APP]);+ api.updateSettings.mockResolvedValue({});+ });++ it('baseline: enables Generate, Render, and Publish when nothing is in flight', async () => {+ render(<ChiptunePanel track={TRACK} onTrackUpdate={vi.fn()} />);++ const generateBtn = await screen.findByRole('button', { name: /revise score/i });+ const renderBtn = screen.getByRole('button', { name: /render take/i });+ const publishBtn = screen.getByRole('button', { name: /publish to app/i });++ expect(generateBtn).not.toBeDisabled();+ expect(renderBtn).not.toBeDisabled();+ expect(publishBtn).not.toBeDisabled();+ });++ it('disables Generate and Publish while a render is in flight', async () => {+ api.renderTrackChiptune.mockReturnValue(pending());+ render(<ChiptunePanel track={TRACK} onTrackUpdate={vi.fn()} />);++ const renderBtn = await screen.findByRole('button', { name: /render take/i });+ fireEvent.click(renderBtn);++ await waitFor(() => expect(screen.getByRole('button', { name: /rendering/i })).toBeInTheDocument());+ expect(screen.getByRole('button', { name: /revise score/i })).toBeDisabled();+ expect(screen.getByRole('button', { name: /publish to app/i })).toBeDisabled();+ });++ it('disables Render while a generate is in flight', async () => {+ api.generateTrackChiptune.mockReturnValue(pending());+ render(<ChiptunePanel track={TRACK} onTrackUpdate={vi.fn()} />);++ const generateBtn = await screen.findByRole('button', { name: /revise score/i });+ fireEvent.click(generateBtn);++ await waitFor(() => expect(screen.getByRole('button', { name: /composing/i })).toBeInTheDocument());+ expect(screen.getByRole('button', { name: /render take/i })).toBeDisabled();+ });++ describe('stale publish-target guard', () => {+ it('clears a saved publish target that no longer appears in the fresh apps list', async () => {+ // The saved prefs point at an app that has since been deleted/archived —+ // getApps() no longer returns it.+ api.getSettings.mockResolvedValue({ music: { chiptune: { publishAppId: 'ghost-app' } } });+ render(<ChiptunePanel track={TRACK} onTrackUpdate={vi.fn()} />);++ const publishToggle = await screen.findByRole('button', { name: /publish to app/i });+ await act(async () => { fireEvent.click(publishToggle); });++ await waitFor(() => expect(api.getApps).toHaveBeenCalled());+ const select = await screen.findByLabelText(/target app/i);+ // The stale id is gone; the select falls back to the empty placeholder.+ expect(select).toHaveValue('');+ expect(screen.getByRole('button', { name: /^publish loop$/i })).toBeDisabled();++ fireEvent.click(screen.getByRole('button', { name: /^publish loop$/i }));+ expect(api.publishTrackChiptune).not.toHaveBeenCalled();+ });++ it('keeps a saved publish target that is still valid and publishes with it', async () => {+ api.getSettings.mockResolvedValue({ music: { chiptune: { publishAppId: 'game-app', publishSubdir: 'game/assets/music' } } });+ api.publishTrackChiptune.mockResolvedValue({ appName: 'Game App', files: ['loop.ogg'], note: 'done' });+ render(<ChiptunePanel track={TRACK} onTrackUpdate={vi.fn()} />);++ const publishToggle = await screen.findByRole('button', { name: /publish to app/i });+ await act(async () => { fireEvent.click(publishToggle); });++ await waitFor(() => expect(api.getApps).toHaveBeenCalled());+ const select = await screen.findByLabelText(/target app/i);+ expect(select).toHaveValue('game-app');++ const publishBtn = screen.getByRole('button', { name: /^publish loop$/i });+ expect(publishBtn).not.toBeDisabled();+ fireEvent.click(publishBtn);++ await waitFor(() => expect(api.publishTrackChiptune).toHaveBeenCalledTimes(1));+ expect(api.publishTrackChiptune).toHaveBeenCalledWith(+ 'track-1',+ { appId: 'game-app', subdir: 'game/assets/music', slug: 'my-test-song' },+ { silent: true },+ );+ });+ });+});diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsxindex 56de5b33e5..797c91dc7b 100644--- a/client/src/components/pipeline/stages/TextStagePanel.jsx+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx@@ -156,8 +156,8 @@ export default function TextStagePanel({<buttontype="button"onClick={handleGenerate}- disabled={generating || actionsGated}- title={actionsGated ? 'Saving settings…' : undefined}+ disabled={generating || actionsGated || dirty}+ title={actionsGated ? 'Saving settings…' : (dirty ? 'Save or discard your edits first' : undefined)}className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50">{generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} />}diff --git a/client/src/components/pipeline/stages/TextStagePanel.test.jsx b/client/src/components/pipeline/stages/TextStagePanel.test.jsxnew file mode 100644index 0000000000..5c968193cf--- /dev/null+++ b/client/src/components/pipeline/stages/TextStagePanel.test.jsx@@ -0,0 +1,184 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++vi.mock('../../../services/api', () => ({+ generatePipelineStage: vi.fn(),+ updatePipelineIssue: vi.fn(),+ restorePipelineStageVersion: vi.fn(),+ PIPELINE_STAGE_LABELS: { idea: 'Idea', prose: 'Prose', comicScript: 'Comic', teleplay: 'Teleplay' },+ PIPELINE_TEXT_STAGES: ['idea', 'prose', 'comicScript', 'teleplay'],+ PIPELINE_DEFAULT_FORWARD_SOURCE: { prose: ['idea'], comicScript: ['prose'], teleplay: ['prose'] },+ PIPELINE_STAGE_STATUS_LABEL: { empty: 'Not started', generating: 'Generating…', ready: 'Ready', edited: 'Edited' },+ PIPELINE_STAGE_STATUS_COLOR: {},+}));++vi.mock('../../ui/Toast', () => ({+ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },+}));++import TextStagePanel from './TextStagePanel';+import toast from '../../ui/Toast';+import { generatePipelineStage, updatePipelineIssue } from '../../../services/api';++const makeIssue = (ideaOverrides = {}) => ({+ id: 'iss-1',+ stages: {+ idea: { status: 'empty', input: '', output: '', runHistory: [], ...ideaOverrides },+ },+});++const renderPanel = (issue, extra = {}) => render(+ <TextStagePanel+ issue={issue}+ stageId="idea"+ seedPlaceholder="seed…"+ outputPlaceholder="output…"+ onStageUpdate={() => {}}+ {...extra}+ />,+);++describe('TextStagePanel', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('Generate success: calls the generate API with the right shape and reflects the new content once the parent lifts it', async () => {+ const stage = { status: 'ready', input: '', output: 'Generated idea text.', runHistory: [] };+ generatePipelineStage.mockResolvedValue({ stage });+ const onStageUpdate = vi.fn();+ const issue = makeIssue();++ const { rerender } = renderPanel(issue, { onStageUpdate });++ await userEvent.click(screen.getByRole('button', { name: 'Generate' }));++ await waitFor(() => expect(generatePipelineStage).toHaveBeenCalledWith(+ 'iss-1',+ 'idea',+ { seedInput: '', providerId: undefined, model: undefined },+ { silent: true },+ ));+ expect(onStageUpdate).toHaveBeenCalledWith('idea', stage);+ expect(toast.success).toHaveBeenCalledWith('Idea generated');++ // The panel itself doesn't self-update its draft on generate — it relies+ // on the parent lifting `onStageUpdate` back into the `issue` prop.+ rerender(+ <TextStagePanel+ issue={{ ...issue, stages: { idea: stage } }}+ stageId="idea"+ seedPlaceholder="seed…"+ outputPlaceholder="output…"+ onStageUpdate={onStageUpdate}+ />,+ );+ expect(screen.getByPlaceholderText('output…')).toHaveValue('Generated idea text.');+ });++ it('Generate failure: toasts the error and leaves no stale-success state behind', async () => {+ generatePipelineStage.mockRejectedValue(new Error('LLM unavailable'));+ const onStageUpdate = vi.fn();+ renderPanel(makeIssue(), { onStageUpdate });++ await userEvent.click(screen.getByRole('button', { name: 'Generate' }));++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('LLM unavailable'));+ expect(onStageUpdate).not.toHaveBeenCalled();+ expect(toast.success).not.toHaveBeenCalled();+ expect(screen.getByPlaceholderText('output…')).toHaveValue('');+ });++ it('Save: persists the draft with the right shape and clears the dirty gate once the parent lifts the saved stage', async () => {+ const issue = makeIssue();+ const updatedStage = { status: 'edited', input: '', output: 'New content' };+ const updatedIssue = { ...issue, stages: { idea: updatedStage } };+ updatePipelineIssue.mockResolvedValue(updatedIssue);+ const onStageUpdate = vi.fn();++ const { rerender } = renderPanel(issue, { onStageUpdate });++ await userEvent.type(screen.getByPlaceholderText('output…'), 'New content');+ await userEvent.click(screen.getByRole('button', { name: /Save edits/i }));++ await waitFor(() => expect(updatePipelineIssue).toHaveBeenCalledWith('iss-1', {+ stages: { idea: { status: 'edited', input: '', output: 'New content' } },+ }));+ expect(onStageUpdate).toHaveBeenCalledWith('idea', updatedStage, updatedIssue);+ expect(toast.success).toHaveBeenCalledWith('Idea saved');++ rerender(+ <TextStagePanel+ issue={updatedIssue}+ stageId="idea"+ seedPlaceholder="seed…"+ outputPlaceholder="output…"+ onStageUpdate={onStageUpdate}+ />,+ );+ expect(screen.getByRole('button', { name: /Save edits/i })).toBeDisabled();+ });++ it('resume-on-mount: mounting with server-side "generating" status keeps Generate disabled without starting a fresh run', () => {+ const issue = makeIssue({ status: 'generating' });+ renderPanel(issue);++ expect(screen.getByRole('button', { name: 'Generate' })).toBeDisabled();+ expect(generatePipelineStage).not.toHaveBeenCalled();+ });++ it('resume-on-mount: re-enables once the server-pushed status leaves generating', () => {+ const issue = makeIssue({ status: 'generating' });+ const { rerender } = renderPanel(issue);+ expect(screen.getByRole('button', { name: 'Generate' })).toBeDisabled();++ const done = { ...issue, stages: { idea: { status: 'ready', input: '', output: 'done', runHistory: [] } } };+ rerender(+ <TextStagePanel+ issue={done}+ stageId="idea"+ seedPlaceholder="seed…"+ outputPlaceholder="output…"+ onStageUpdate={() => {}}+ />,+ );+ expect(screen.getByRole('button', { name: 'Generate' })).not.toBeDisabled();+ });++ it('dirty-gate: disables Generate with the "Save or discard" title once the draft diverges, and re-enables once the saved stage is lifted back in', async () => {+ const issue = makeIssue({ status: 'ready', output: 'Saved idea text.' });+ const savedStage = { status: 'edited', input: '', output: 'Edited idea text.' };+ const savedIssue = { ...issue, stages: { idea: savedStage } };+ updatePipelineIssue.mockResolvedValue(savedIssue);++ const { rerender } = renderPanel(issue);+ const generateBtn = screen.getByRole('button', { name: 'Generate' });+ expect(generateBtn).not.toBeDisabled();+ expect(generateBtn).not.toHaveAttribute('title', 'Save or discard your edits first');++ const output = screen.getByPlaceholderText('output…');+ await userEvent.clear(output);+ await userEvent.type(output, 'Edited idea text.');++ expect(generateBtn).toBeDisabled();+ expect(generateBtn).toHaveAttribute('title', 'Save or discard your edits first');++ await userEvent.click(screen.getByRole('button', { name: /Save edits/i }));+ await waitFor(() => expect(updatePipelineIssue).toHaveBeenCalled());++ // Saving alone doesn't clear the gate — the panel compares the draft+ // against the `issue` prop's stage, which only updates once the parent+ // lifts `onStageUpdate`'s result back down.+ rerender(+ <TextStagePanel+ issue={savedIssue}+ stageId="idea"+ seedPlaceholder="seed…"+ outputPlaceholder="output…"+ onStageUpdate={() => {}}+ />,+ );+ expect(generateBtn).not.toBeDisabled();+ });+});diff --git a/client/src/components/writers-room/StoryboardBoardsBanners.jsx b/client/src/components/writers-room/StoryboardBoardsBanners.jsxindex 5b0423a5b5..d84722c4fb 100644--- a/client/src/components/writers-room/StoryboardBoardsBanners.jsx+++ b/client/src/components/writers-room/StoryboardBoardsBanners.jsx@@ -16,6 +16,7 @@ export function StoryboardSetup({onRunAdapt,onRunFullPipeline,runningKind,+ dirty = false,}) {const isRunning = !!runningKind;const charDone = charactersCount > 0;@@ -23,6 +24,10 @@ export function StoryboardSetup({const Step = ({ n, kind, done, label, sublabel, hint, onClick, primary = false }) => {const running = runningKind === kind;+ // Every step runs server-side against the persisted draft body (the+ // character/place extractions consume the same getWorkWithBody corpus as+ // Adapt), so unsaved edits would be silently skipped — block until saved.+ const blockedByDirty = dirty;const Icon = done ? Check : kind === 'characters' ? Users : kind === 'places' ? MapPinIcon : Clapperboard;return (<div className={`flex items-start gap-2.5 p-2.5 border rounded ${@@ -49,7 +54,8 @@ export function StoryboardSetup({<buttontype="button"onClick={onClick}- disabled={isRunning || !onClick}+ disabled={isRunning || !onClick || blockedByDirty}+ title={blockedByDirty ? 'Save first' : undefined}className={`mt-1.5 inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded disabled:opacity-50 ${primary? 'bg-port-accent text-white hover:bg-port-accent/80'@@ -108,9 +114,9 @@ export function StoryboardSetup({<buttontype="button"onClick={onRunFullPipeline}- disabled={isRunning || !onRunFullPipeline}+ disabled={isRunning || !onRunFullPipeline || dirty}className="w-full flex items-center justify-center gap-1.5 px-3 py-2 bg-port-accent text-white text-[11px] rounded hover:bg-port-accent/80 disabled:opacity-50"- title="Runs all three steps sequentially: characters → settings → Adapt. Skip if you want to run them individually."+ title={dirty ? 'Save first' : 'Runs all three steps sequentially: characters → settings → Adapt. Skip if you want to run them individually.'}>{isRunning ? <Loader2 size={12} className="animate-spin" /> : <ArrowRight size={12} />}{isRunning ? `Running ${runningKind}…` : 'Run all in order →'}@@ -125,7 +131,7 @@ export function StoryboardSetup({);}-export function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenConfig, hasPriorScript }) {+export function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenConfig, hasPriorScript, dirty = false }) {const error = failure?.error || 'Adapt failed for an unknown reason';const isTimeout = /timed out/i.test(error);return (@@ -157,7 +163,8 @@ export function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenCon</button><buttononClick={onRunAdapt}- disabled={runningAdapt || !onRunAdapt}+ disabled={runningAdapt || !onRunAdapt || dirty}+ title={dirty ? 'Save first' : undefined}className="flex items-center gap-1 px-2 py-1 bg-port-error/20 border border-port-error/40 text-port-error rounded text-[10px] hover:bg-port-error/30 disabled:opacity-50">{runningAdapt ? <Loader2 size={10} className="animate-spin" /> : <RefreshCcw size={10} />}@@ -173,7 +180,7 @@ export function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenCon// the user gets visual drift across scenes. Inline run buttons let them// fix it without leaving the panel; re-running Adapt afterwards picks up// the populated bibles.-export function BiblesMissingNotice({ charactersMissing, placesMissing, onRunCharacters, onRunPlaces, runningKind }) {+export function BiblesMissingNotice({ charactersMissing, placesMissing, onRunCharacters, onRunPlaces, runningKind, dirty = false }) {const isRunning = !!runningKind;const missing = [charactersMissing && 'character bible',@@ -193,7 +200,8 @@ export function BiblesMissingNotice({ charactersMissing, placesMissing, onRunCha{charactersMissing && (<buttononClick={onRunCharacters}- disabled={isRunning || !onRunCharacters}+ disabled={isRunning || !onRunCharacters || dirty}+ title={dirty ? 'Save first' : undefined}className="flex items-center gap-1 px-2 py-1 border border-port-border text-gray-300 rounded text-[10px] hover:bg-port-border/40 disabled:opacity-50">{runningKind === 'characters' ? <Loader2 size={10} className="animate-spin" /> : <Users size={10} />}@@ -203,7 +211,8 @@ export function BiblesMissingNotice({ charactersMissing, placesMissing, onRunCha{placesMissing && (<buttononClick={onRunPlaces}- disabled={isRunning || !onRunPlaces}+ disabled={isRunning || !onRunPlaces || dirty}+ title={dirty ? 'Save first' : undefined}className="flex items-center gap-1 px-2 py-1 border border-port-border text-gray-300 rounded text-[10px] hover:bg-port-border/40 disabled:opacity-50">{runningKind === 'places' ? <Loader2 size={10} className="animate-spin" /> : <MapPinIcon size={10} />}@@ -216,7 +225,7 @@ export function BiblesMissingNotice({ charactersMissing, placesMissing, onRunCha);}-export function StaleBanner({ onRunAdapt, runningAdapt }) {+export function StaleBanner({ onRunAdapt, runningAdapt, dirty = false }) {return (<div className="flex items-start gap-2 p-2 mb-1 border border-port-warning/40 bg-port-warning/5 rounded text-[11px]"><AlertTriangle size={12} className="text-port-warning mt-0.5 shrink-0" />@@ -226,7 +235,8 @@ export function StaleBanner({ onRunAdapt, runningAdapt }) {</div><buttononClick={onRunAdapt}- disabled={runningAdapt || !onRunAdapt}+ disabled={runningAdapt || !onRunAdapt || dirty}+ title={dirty ? 'Save first' : undefined}className="flex items-center gap-1 px-2 py-1 bg-port-warning/20 border border-port-warning/40 text-port-warning rounded text-[10px] hover:bg-port-warning/30 disabled:opacity-50">{runningAdapt ? <Loader2 size={10} className="animate-spin" /> : <RefreshCcw size={10} />}diff --git a/client/src/components/writers-room/StoryboardBoardsTab.jsx b/client/src/components/writers-room/StoryboardBoardsTab.jsxindex e3a94f1efb..3beec93ac7 100644--- a/client/src/components/writers-room/StoryboardBoardsTab.jsx+++ b/client/src/components/writers-room/StoryboardBoardsTab.jsx@@ -47,6 +47,7 @@ export default function StoryboardBoardsTab({hotRef = null,onSceneHover,onSceneRenderStart,+ dirty = false,}) {return (<div className="px-3 py-3 space-y-2">@@ -81,6 +82,7 @@ export default function StoryboardBoardsTab({runningAdapt={runningAdapt}onOpenConfig={onOpenConfig}hasPriorScript={!!latestScript}+ dirty={dirty}/>)}@@ -93,11 +95,12 @@ export default function StoryboardBoardsTab({onRunAdapt={onRunAdapt}onRunFullPipeline={onRunFullPipeline}runningKind={runningKind}+ dirty={dirty}/>)}{!loading && latestScript && isStale && !latestFailure && (- <StaleBanner onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} />+ <StaleBanner onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} dirty={dirty} />)}{!loading && latestScript && !isStale && !latestFailure && (charactersCount === 0 || placesCount === 0) && (@@ -107,6 +110,7 @@ export default function StoryboardBoardsTab({onRunCharacters={onRunCharacters}onRunPlaces={onRunPlaces}runningKind={runningKind}+ dirty={dirty}/>)}diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsxindex 3b3d4901e6..703568add6 100644--- a/client/src/components/writers-room/StoryboardPanel.jsx+++ b/client/src/components/writers-room/StoryboardPanel.jsx@@ -71,6 +71,7 @@ export default function StoryboardPanel({onSceneRenderStart,tab,onTabChange,+ dirty = false,}) {const setTab = onTabChange;const [searchParams, setSearchParams] = useSearchParams();@@ -386,6 +387,7 @@ export default function StoryboardPanel({hotRef={hotRef}onSceneHover={onSceneHover}onSceneRenderStart={onSceneRenderStart}+ dirty={dirty}/>)}{tab === TAB.CONFIG && (diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 718f48e68b..9cd4017635 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -421,6 +421,15 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOreturn () => window.removeEventListener('keydown', onKey);}, []);+ // Warn on tab close/navigation away while there are unsaved draft edits —+ // otherwise the body reset in the effect above silently discards them.+ useEffect(() => {+ if (!dirty) return undefined;+ const onBeforeUnload = (e) => { e.preventDefault(); };+ window.addEventListener('beforeunload', onBeforeUnload);+ return () => window.removeEventListener('beforeunload', onBeforeUnload);+ }, [dirty]);+useClickOutside(overflowRef, overflowOpen, () => setOverflowOpen(false));const handleSnapshot = async () => {@@ -914,11 +923,11 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO{overflowOpen && (<div className="absolute right-0 top-full mt-1 z-30 w-60 rounded-md border border-port-border bg-port-card shadow-xl py-1 text-xs"><MenuSection label="AI">- <MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === ANALYSIS_KIND.SCRIPT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SCRIPT))} />- <MenuItem icon={Users} label="Refresh characters" running={runningKind === ANALYSIS_KIND.CHARACTERS} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.CHARACTERS))} />- <MenuItem icon={MapPin} label="Refresh places" running={runningKind === ANALYSIS_KIND.PLACES} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.PLACES))} />- <MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} />- <MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} />+ <MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === ANALYSIS_KIND.SCRIPT} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SCRIPT))} />+ <MenuItem icon={Users} label="Refresh characters" running={runningKind === ANALYSIS_KIND.CHARACTERS} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.CHARACTERS))} />+ <MenuItem icon={MapPin} label="Refresh places" running={runningKind === ANALYSIS_KIND.PLACES} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.PLACES))} />+ <MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} />+ <MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} disabled={dirty} title={dirty ? 'Save first' : undefined} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} /><MenuItem icon={Wand2} label="Polish (cut → revise)" onClick={closeOverflowAnd(() => setDrawer(DRAWER.POLISH))} /><MenuItem icon={Quote} label="Voice exemplars" onClick={closeOverflowAnd(() => setDrawer(DRAWER.VOICE))} /><MenuItem icon={Zap} label={liveEnabled ? 'Disable live director' : 'Enable live director'} active={liveEnabled} onClick={closeOverflowAnd(toggleLiveMode)} />@@ -1112,6 +1121,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOonSceneRenderStart={queueRegister}tab={sidebarTab}onTabChange={setSidebarTab}+ dirty={dirty}/></aside>)}@@ -1197,12 +1207,13 @@ function MenuSection({ label, children }) {);}-function MenuItem({ icon: Icon, label, onClick, running = false, active = false, badge = null }) {+function MenuItem({ icon: Icon, label, onClick, running = false, active = false, badge = null, disabled = false, title }) {return (<buttontype="button"onClick={onClick}- disabled={running}+ disabled={running || disabled}+ title={title}className={`w-full flex items-center gap-2 px-3 py-1.5 text-left text-[11px] hover:bg-port-bg disabled:opacity-50 ${active ? 'text-port-accent' : 'text-gray-300'}`}@@ -1264,7 +1275,7 @@ function MobileTab({ active, onClick, icon: Icon, label }) {return (<buttononClick={onClick}- className={`flex-1 flex items-center justify-center gap-1.5 py-2 text-[12px] border-b-2 ${+ className={`flex-1 flex items-center justify-center gap-1.5 py-2 min-h-[44px] text-[12px] border-b-2 ${active ? 'border-port-accent text-white' : 'border-transparent text-gray-500 hover:text-gray-300'}`}>diff --git a/client/src/hooks/useCityAudio.js b/client/src/hooks/useCityAudio.jsindex 569862b528..063e3b4f5c 100644--- a/client/src/hooks/useCityAudio.js+++ b/client/src/hooks/useCityAudio.js@@ -1,5 +1,5 @@import { useState, useEffect, useCallback, useRef } from 'react';-import { initAudio, setMusicVolume, setSfxVolume, cleanup as cleanupAudio } from '../components/city/audio/cityAudioEngine';+import { initAudio, setMusicVolume, setSfxVolume, scheduleCleanup as scheduleAudioCleanup } from '../components/city/audio/cityAudioEngine';import { startMusic, stopMusic, setSoundscape } from '../components/city/audio/citySynthMusic';import { playSfx as playSfxFn } from '../components/city/audio/citySoundEffects';@@ -82,11 +82,13 @@ export default function useCityAudio(settings, soundscape) {setSfxVolume(sfxVolume);}, [isAudioReady, sfxVolume]);- // Cleanup on unmount+ // Cleanup on unmount. stopMusic() ramps the music layers to silence and returns+ // how long that ramp takes (ms) — closing the AudioContext immediately would cut+ // the ramp short and reintroduce the pop it exists to avoid, so delay the close+ // until the ramp has actually settled.useEffect(() => {return () => {- stopMusic();- cleanupAudio();+ scheduleAudioCleanup(stopMusic());};}, []);diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsxindex ea88c307b5..56720382cc 100644--- a/client/src/pages/PipelineManuscriptEditor.jsx+++ b/client/src/pages/PipelineManuscriptEditor.jsx@@ -127,6 +127,21 @@ export default function PipelineManuscriptEditor() {liveSectionsRef.current = sections;const liveContentFor = (issueId) => liveSectionsRef.current.find((s) => s.issueId === issueId)?.content ?? '';+ // Sections only persist onBlur, so a tab close/navigation right after typing+ // (before the field blurs) would silently drop the edit. Warn on unload+ // whenever any section's live content has drifted from its saved baseline.+ useEffect(() => {+ const onBeforeUnload = (e) => {+ const dirty = liveSectionsRef.current.some((s) => {+ const key = `${s.issueId}:${s.stageId}`;+ return baselineRef.current.get(key) !== s.content;+ });+ if (dirty) e.preventDefault();+ };+ window.addEventListener('beforeunload', onBeforeUnload);+ return () => window.removeEventListener('beforeunload', onBeforeUnload);+ }, []);+useEffect(() => {safeWriteStorage(VIEW_MODE_KEY, viewMode);}, [viewMode]);diff --git a/server/services/creativeDirector/planAdvance.js b/server/services/creativeDirector/planAdvance.jsindex ab72c81c98..ff0c9d1ceb 100644--- a/server/services/creativeDirector/planAdvance.js+++ b/server/services/creativeDirector/planAdvance.js@@ -457,6 +457,10 @@ async function handlePlanStepFailure(projectId, step) {// Register a one-shot listener that settles a long-running plan step when its// media job reaches a terminal state. Idempotent teardown; closes the race where// the job already settled between dispatch returning and the listener attaching.+// No local backstop timer needed here (unlike armAutopilotListener below): every+// media job carries its own per-job idle watchdog (mediaJobQueue/index.js) that+// unconditionally forces a 'completed'/'failed'/'canceled' emit within a bounded+// window regardless of job kind, so this listener can never wait forever.function armPlanJobListener(projectId, stepId, jobId, runId) {const key = `${projectId}:${stepId}`;let fired = false;@@ -563,6 +567,20 @@ async function readAutopilotMarker(seriesId) {return null; // 'running' or unknown — not terminal.}+// Backstop for an autopilot run that goes fully silent after this listener+// attaches — a bug in a step runner, an unbounded internal await, or an+// event-bus mismatch would otherwise leave this listener (and the plan step)+// wedged in `running` forever, since unlike armPlanJobListener's media job+// (always terminated by mediaJobQueue's own per-job idle watchdog,+// server/services/mediaJobQueue/index.js) a whole autopilot run has no+// underlying watchdog of its own. Modeled as IDLE time, not a fixed wall-clock+// cap (mirrors mediaJobQueue's own idle-vs-wall-time choice) because a healthy+// run can legitimately drive many steps for hours — every step:start/+// step:complete/note frame the orchestrator broadcasts (seriesAutopilot/+// orchestrator.js) counts as activity and re-arms the window; only a run that+// stops emitting anything at all trips it.+const AUTOPILOT_LISTENER_IDLE_MS = 45 * 60 * 1000;+// Attach a listener to the in-process autopilot event bus for `seriesId`, settling// the plan step on the first terminal frame. Idempotent teardown (reuses the// shared planJobCleanups map so __resetPlanInflightState drops it too). Closes the@@ -570,12 +588,36 @@ async function readAutopilotMarker(seriesId) {function armAutopilotListener(projectId, stepId, seriesId, runId, apResult) {const key = `${projectId}:${stepId}`;let fired = false;+ let idleTimer;const teardown = () => {autopilotEvents.off(seriesId, handler);+ clearTimeout(idleTimer);planJobCleanups.delete(key);};+ const armIdleTimer = () => {+ clearTimeout(idleTimer);+ idleTimer = setTimeout(() => {+ if (fired) return;+ fired = true;+ teardown();+ console.log(`⏱️ CD plan ${projectId}: step "${stepId}" autopilot run for series ${String(seriesId).slice(0, 8)} went silent for ${AUTOPILOT_LISTENER_IDLE_MS}ms — settling failed`);+ // Runs outside the request lifecycle (in-process event bus) — never throw out.+ (async () => {+ await finishRun(projectId, runId, 'failed', `autopilot run stalled — no activity for ${Math.round(AUTOPILOT_LISTENER_IDLE_MS / 60000)}m`);+ await updatePlanStep(projectId, stepId, { status: 'failed', result: { error: 'autopilot run stalled (idle backstop)' } });+ await handlePlanStepFailure(projectId, { stepId, toolName: '(series autopilot)', retryCount: 0 });+ })().catch((e) => console.log(`⚠️ CD plan ${projectId} autopilot idle-backstop settle for ${stepId} failed: ${e.message}`));+ }, AUTOPILOT_LISTENER_IDLE_MS);+ idleTimer.unref?.();+ };function handler(payload) {- if (fired || !payload || !AUTOPILOT_TERMINAL_TYPES.has(payload.type)) return;+ if (fired || !payload) return;+ if (!AUTOPILOT_TERMINAL_TYPES.has(payload.type)) {+ // Non-terminal frame (step:start, step:complete, note, …) — the run is+ // alive and making progress; re-arm the idle window rather than settling.+ armIdleTimer();+ return;+ }fired = true;teardown();settleAutopilotStep(projectId, stepId, runId, payload)@@ -583,6 +625,7 @@ function armAutopilotListener(projectId, stepId, seriesId, runId, apResult) {}autopilotEvents.on(seriesId, handler);planJobCleanups.set(key, teardown);+ armIdleTimer();console.log(`⏳ CD plan ${projectId}: step "${stepId}" attached to autopilot run for series ${String(seriesId).slice(0, 8)}${apResult?.alreadyRunning ? ' (already running)' : ''}`);// The run may already have reached a terminal state (settled between dispatch// returning and this attach) — its event fired and won't repeat. Re-check viadiff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex db94e53240..340112db65 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -19,7 +19,7 @@ import { getStage } from '../promptService.js';import { getSeries } from './series.js';import { extractCanonFromProse, summarizeCanonExtraction } from '../universeCanon.js';import { getIssue, listIssues, updateStage, assertStageUnlocked, TEXT_STAGE_IDS } from './issues.js';-import { getSeriesCanon } from './seriesCanon.js';+import { pickCanon } from './seriesCanon.js';import { getUniverse } from '../universeBuilder.js';import { compareIssuesByPosition, NO_LINKED_UNIVERSE_PLACEHOLDER } from './arcPlanner.js';import { computeIssueTargets, assessSynopsisScope } from '../../lib/issueLength.js';@@ -854,11 +854,11 @@ export async function generateStage(issueId, stageId, options = {}) {const series = await getSeries(issue.seriesId);// Universe canon is best-effort — an orphaned series (no universeId) or a// missing universe record just skips the entities summary instead of- // failing the run.- const [canon, world] = await Promise.all([- getSeriesCanon(series),- series.universeId ? getUniverse(series.universeId).catch(() => null) : Promise.resolve(null),- ]);+ // failing the run. Single fetch (mirrors visualStageHelpers.loadBibleContext)+ // — canon is derived from the same `world` read rather than re-fetching the+ // universe a second time via getSeriesCanon.+ const world = series.universeId ? await getUniverse(series.universeId).catch(() => null) : null;+ const canon = pickCanon(world);// Per-stage editorial lock — refuse before touching the stage record so a// locked stage doesn't get bumped to 'generating' status only to be reset.