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: v2.25.0 release-review robustness follow-ups (#2047)
Adam Eivyda8495e75a79
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 08f0a5e257..76af9a04a6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -40,6 +40,7 @@## Internal+- Addressed the v2.25.0 release-review robustness follow-ups (#2047). Client: the Shell restart button's deferred `startSession()` now aborts if the user switches sessions within its 1s window (generation guard, matching the page's other deferred socket emits); MusicVideo auto-arrange snapshots the board and reverts on a mid-loop PATCH failure instead of leaving the optimistic full arrangement over a server-side partial; the video timeline editor re-derives the selected clip from its stable `clipId` after a refresh so a `CONFLICT` reload no longer collapses the inspector; and MemoryPractice's chunk-/sequence-exhausted fallbacks moved their `setState` + `submitMemoryPractice()` POSTs out of the render body into a terminal-transition effect. Server: `triggerReplenish` now guards its fire-and-forget `replenishType` promise like `requestCacheFill` (a drill-cache disk-write failure no longer surfaces as an unhandled rejection); the `/post/drill` schema accepts `memoryItemId` so it reaches `generateMemoryDrill` instead of being silently stripped; `applyProjectPatch` regresses a music-video project's status to `draft` on track change (the analysis it cleared must be redone); and ~20 dead imports left over from the #1830 peerSync split were removed from `peerSyncReceive.js`.- Deflaked the `UpdateTab reconcile flow` tests, which intermittently failed CI with "Unable to find role=button and name 'Restarting...'" (#2065). The component mirrors `updating` into `updatingRef` via a passive effect, and the disconnect handler's guard reads that ref synchronously; since `runUpdate()` calls `setUpdating(true)` outside any `act` (after awaiting the pre-update health check), the "Reconciling..." button could commit — satisfying the test's `waitFor` — a scheduler tick before the ref-sync effect ran, leaving the ref stale-false when `disconnect` fired so the confirmation timer never armed. The test now flushes pending effects (`await act(async () => {})`) before firing `disconnect`, syncing the ref to the state production always reaches over real network time. Test-only change; no product behavior touched.- Docs audit and reorganization: reclassified two non-feature docs out of `docs/features/` — the cross-domain insights design spike now lives at `docs/plans/2026-06-03-cross-domain-insights-engine.md` (it specs future work, it isn't feature documentation) and the OpenClaw pre-implementation extension-point audit at `docs/research/2026-03-31-openclaw-operator-chat-audit.md` (it's an explicitly-unmaintained investigation record). `docs/README.md` links updated. Also fixed `docs/PORTS.md` claiming the `PORTS` object is "re-exported at `server/lib/ports.js`" (it's a manually-synced mirror — the ESM server can't `require()` the CommonJS config), replaced a dead `#m7-app-templates` anchor in `docs/features/app-wizard.md` with a real pointer to `GET /api/scaffold/templates`, and refreshed the stale example model IDs in `docs/TROUBLESHOOTING.md`. The audit verified every other doc against the code: all 13 top-level guides are indexed and accurate, every feature doc's modules/routes/nav entries resolve, and plans/decisions/research/superpowers/themes/examples/media have zero orphans or broken links.- Consolidated five component-local duration/uptime/time-until formatters onto the shared `utils/formatters.js` helpers (`formatDurationMs`, `timeUntil`), per the "do not re-define formatters inside components" convention (#2028). `formatDurationMs` gained a day bucket (`2d 3h`) so long uptimes no longer render as an unbounded hours count; ProcessesTab, CityHud, Shell session ages, the CoS QuickSummary "next job" countdown, and the Loops interval label now all route through the shared helpers, and a `console.log` in `memoryClassifier.js` was collapsed to a single interpolated line.diff --git a/client/src/components/meatspace/post/MemoryPractice.jsx b/client/src/components/meatspace/post/MemoryPractice.jsxindex 83bbf7bcda..970e00a9d5 100644--- a/client/src/components/meatspace/post/MemoryPractice.jsx+++ b/client/src/components/meatspace/post/MemoryPractice.jsx@@ -55,6 +55,35 @@ export default function MemoryPractice({ item, onBack }) {}}, [mode, item.id]);+ // Drive terminal transitions from an effect, never during render. The render+ // fallbacks below (chunk exhausted, line exhausted, sequence exhausted) return null+ // for a frame while this effect saves results, advances the chunk, or marks the+ // session done — firing setState + an async submitMemoryPractice() POST inside the+ // render body is fragile under StrictMode/concurrent rendering. Normal per-answer+ // flow still runs through advanceSpaced / nextSequenceQuestion.+ useEffect(() => {+ if (done) return;+ if (mode === 'spaced') {+ if (!chunkMastery || chunkMastery.length === 0) return;+ const currentChunk = chunkMastery[spacedChunkIdx];+ if (!currentChunk) {+ savePractice('spaced', results);+ setDone(true);+ return;+ }+ const [chunkStart, chunkEnd] = currentChunk.lineRange;+ const chunkLines = lines.slice(chunkStart, chunkEnd + 1).filter(l => l.text.trim());+ if (!chunkLines[spacedLineIdx]) {+ setSpacedChunkIdx(prev => prev + 1);+ setSpacedLineIdx(0);+ setAnswer('');+ setShowResult(null);+ }+ } else if (mode === 'sequence' && !lines[currentIdx + 1]) {+ finishSequence();+ }+ }, [mode, chunkMastery, spacedChunkIdx, spacedLineIdx, currentIdx, done]);+if (!mode) {return (<div className="space-y-6 max-w-4xl">@@ -175,9 +204,7 @@ export default function MemoryPractice({ item, onBack }) {const currentChunk = chunkMastery[spacedChunkIdx];if (!currentChunk) {- // All chunks done- savePractice('spaced', results);- setDone(true);+ // All chunks done — the terminal-transition effect saves results and sets done.return null;}@@ -186,11 +213,7 @@ export default function MemoryPractice({ item, onBack }) {const currentLine = chunkLines[spacedLineIdx];if (!currentLine) {- // Move to next chunk- setSpacedChunkIdx(prev => prev + 1);- setSpacedLineIdx(0);- setAnswer('');- setShowResult(null);+ // Move to next chunk — handled by the terminal-transition effect.return null;}@@ -357,7 +380,7 @@ export default function MemoryPractice({ item, onBack }) {const expectedLine = lines[currentIdx + 1];if (!expectedLine) {- finishSequence();+ // Saved + marked done by the terminal-transition effect.return null;}diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 5eb0a9b275..e20f7b3a7d 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -289,6 +289,10 @@ export default function MusicVideo() {return;}const byId = new Map(arrangement.map((a) => [a.sceneId, a]));+ // Snapshot the pre-arrangement project so a mid-loop PATCH failure can roll the+ // optimistic board back to match the server-side partial state — otherwise the+ // local board shows the complete arrangement over a partial persist until reload.+ const snapshot = selected;replaceProject({...selected,scenes: scenes.map((s) => {@@ -308,7 +312,12 @@ export default function MusicVideo() {}})().then(() => toast.success(`Auto-arranged ${arrangement.length} scene${arrangement.length === 1 ? '' : 's'} by energy`))- .catch((err) => toast.error(err?.message || 'Auto-arrange failed'))+ .catch((err) => {+ // Revert the optimistic board to the snapshot so it doesn't show the full+ // arrangement over a server-side partial write.+ replaceProject(snapshot);+ toast.error(err?.message || 'Auto-arrange failed');+ }).finally(() => setArranging(false));};diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsxindex 74df56274b..5f834ccc3f 100644--- a/client/src/pages/Shell.jsx+++ b/client/src/pages/Shell.jsx@@ -480,6 +480,23 @@ export default function Shell() {}}, [socket, clearActiveSession, cancelPendingAttach]);+ // Restart = kill the current session, then start a fresh one after a short delay+ // (gives the server time to tear down the old PTY). The deferred startSession must+ // respect both staleness and unmount: stopSession() bumps the pending generation,+ // so capture it and abort the delayed start if the user switched sessions (which+ // bumps the generation again) or navigated away within the 1s window. Without the+ // generation guard, a tab click inside the window would fire startSession() and+ // clobber the in-flight switch.+ const restartSession = useCallback(() => {+ stopSession();+ const gen = pendingAttachRef.current.generation;+ setTimeout(() => {+ if (!mountedRef.current) return;+ if (pendingAttachRef.current.generation !== gen) return;+ startSession();+ }, 1000);+ }, [stopSession, startSession]);+const switchToSession = useCallback((sessionId, { fromUrl = false } = {}) => {// Compare against the in-flight attach target if there is one, falling back to the// currently-displayed session. Without this, a back→forward race (B→A while attach@@ -900,7 +917,7 @@ export default function Shell() {{/* Restart (kill + new shell) is meaningless for a TUI-run view. */}{connected && !isLiveRun && (<button- onClick={() => { stopSession(); setTimeout(() => { if (mountedRef.current) startSession(); }, 1000); }}+ onClick={restartSession}className="flex items-center gap-1.5 px-2.5 py-2 bg-port-card hover:bg-port-border text-gray-300 hover:text-white rounded-lg text-sm transition-colors border border-port-border min-h-[40px]"title="Restart session (kill + new)">diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsxindex a19e88b306..4e787bec02 100644--- a/client/src/pages/VideoTimelineEditor.jsx+++ b/client/src/pages/VideoTimelineEditor.jsx@@ -138,6 +138,11 @@ export default function VideoTimelineEditor() {// Local timeline (each clip gets a stable _key for dnd-kit identity)const [clips, setClips] = useState([]);const [selectedKey, setSelectedKey] = useState(null);+ // Track the current selection by its STABLE identity (clipId + position) so a+ // refresh — which regenerates every clip's random _key — can re-derive selectedKey+ // instead of collapsing the inspector to "Select a clip". Read from a ref so refresh+ // needn't depend on clips/selectedKey (which would re-trigger the load-on-mount loop).+ const selectionRef = useRef({ clipId: null, index: -1 });const [pxPerSec, setPxPerSec] = useState(60);const [t, setT] = useState(0); // project-time in secondsconst [playing, setPlaying] = useState(false);@@ -171,13 +176,34 @@ export default function VideoTimelineEditor() {api.listVideoHistory().catch(() => []),]);if (proj) {+ const newClips = (proj.clips || []).map((c, idx) => ({ ...c, _key: `${c.clipId}-${idx}-${Math.random().toString(36).slice(2, 8)}` }));setProject(proj);- setClips((proj.clips || []).map((c, idx) => ({ ...c, _key: `${c.clipId}-${idx}-${Math.random().toString(36).slice(2, 8)}` })));+ setClips(newClips);+ // Re-derive selection from the stable clipId (+ prior position) so a refresh —+ // e.g. a CONFLICT reload mid-edit — doesn't leave selectedKey pointing at a+ // now-regenerated _key and collapse the inspector. Prefer the same index; fall+ // back to the first clip with the same clipId; clear if the clip is gone.+ const { clipId: selId, index: selIdx } = selectionRef.current;+ if (selId != null) {+ const match = newClips[selIdx]?.clipId === selId+ ? newClips[selIdx]+ : newClips.find((c) => c.clipId === selId);+ setSelectedKey(match ? match._key : null);+ }}setHistory(hist);setLoading(false);}, [projectId]);+ // Keep the stable-identity mirror of the current selection current so refresh() can+ // reattach selectedKey after it regenerates clip _keys.+ useEffect(() => {+ const idx = clips.findIndex((c) => c._key === selectedKey);+ selectionRef.current = idx >= 0+ ? { clipId: clips[idx].clipId, index: idx }+ : { clipId: null, index: -1 };+ }, [selectedKey, clips]);+useEffect(() => { refresh(); }, [refresh]);// Sync the rename draft to the canonical name when the project (re)loadsdiff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsindex ee3464c9a9..f2e2770156 100644--- a/server/lib/postValidation.js+++ b/server/lib/postValidation.js@@ -77,6 +77,10 @@ const MORSE_DRILL_TYPES = ['morse-copy', 'morse-head-copy', 'morse-send'];const drillTypeConfigSchema = z.object({enabled: z.boolean().optional(),+ // Memory drills: the target memory item to drill (falls back to lowest-mastery+ // item when absent). The /post/drill route threads config.memoryItemId into+ // generateMemoryDrill, so it must survive validation rather than being stripped.+ memoryItemId: z.string().optional(),steps: z.number().int().min(1).max(50).optional(),subtrahend: z.number().int().min(1).max(100).optional(),startValue: z.number().int().min(1).optional(),diff --git a/server/services/meatspacePostDrillCache.js b/server/services/meatspacePostDrillCache.jsindex ce98e8c74c..caf9517c24 100644--- a/server/services/meatspacePostDrillCache.js+++ b/server/services/meatspacePostDrillCache.js@@ -155,7 +155,10 @@ function isCacheCold(type) {export function triggerReplenish(type, providerId, model) {if (!CACHEABLE_TYPES.includes(type)) return;if (isCacheCold(type)) return;- replenishType(type, providerId, model);+ // Fire-and-forget, but guard the returned promise like requestCacheFill does —+ // replenishType's inner saveCache() can reject on a disk-write failure, which+ // would otherwise surface as an unhandled rejection.+ replenishType(type, providerId, model).catch(err => console.error(`❌ POST cache: triggerReplenish failed: ${err.message}`));debouncedSave();}diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 164a9ec7a2..0280e0b18c 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -100,7 +100,15 @@ export function applyProjectPatch(project, patch) {|| ('uploadedAudioFilename' in patch && patch.uploadedAudioFilename !== project.uploadedAudioFilename);if (!trackChanged) return touch(project, patch);const scenes = (project.scenes || []).map((s) => (s.beatAligned ? { ...s, beatAligned: false } : s));- return touch(project, { ...patch, audioAnalysis: null, scenes });+ // Clearing audioAnalysis means the project must be re-analyzed before it can be+ // planned/arranged/rendered, so a status that implies analysis existed+ // (`analyzed`/`ready`/`rendering`/`complete`) is now stale. Regress it to `draft` —+ // the inverse of setAudioAnalysis's draft→analyzed flip — unless the caller set an+ // explicit status in this same patch. `draft`/`failed` already imply no usable+ // analysis, so leave those untouched.+ const regressStatus = !patch.status && !['draft', 'failed'].includes(project.status);+ const statusPatch = regressStatus ? { status: 'draft' } : {};+ return touch(project, { ...patch, ...statusPatch, audioAnalysis: null, scenes });}/**diff --git a/server/services/musicVideo/projectsLogic.test.js b/server/services/musicVideo/projectsLogic.test.jsindex 0bd14aa311..c458c403ae 100644--- a/server/services/musicVideo/projectsLogic.test.js+++ b/server/services/musicVideo/projectsLogic.test.js@@ -98,6 +98,29 @@ describe('applyProjectPatch', () => {expect(next.scenes[1]).toMatchObject({ beatAligned: false, startSec: 3, endSec: 4 });});+ it('regresses status to draft on track change since the cleared analysis must be redone', () => {+ const analyzed = setAudioAnalysis({ ...baseProject(), trackId: 't1', status: 'ready' }, {+ bpm: 120, beats: [0], downbeats: [0], sections: [{ label: 'S', startSec: 0, endSec: 1 }], durationSec: 1,+ });+ expect(analyzed.status).toBe('ready');+ const next = applyProjectPatch(analyzed, { trackId: 't2' });+ expect(next.status).toBe('draft');+ expect(next.audioAnalysis).toBeNull();+ });++ it('honors an explicit status in the same track-change patch instead of regressing', () => {+ const analyzed = setAudioAnalysis({ ...baseProject(), trackId: 't1', status: 'ready' }, {+ bpm: 120, beats: [0], downbeats: [0], sections: [{ label: 'S', startSec: 0, endSec: 1 }], durationSec: 1,+ });+ const next = applyProjectPatch(analyzed, { trackId: 't2', status: 'analyzed' });+ expect(next.status).toBe('analyzed');+ });++ it('leaves status untouched on a track change when the project is still a draft', () => {+ const next = applyProjectPatch({ ...baseProject(), trackId: 't1', status: 'draft' }, { trackId: 't2' });+ expect(next.status).toBe('draft');+ });+it('leaves scene beatAligned flags untouched when the track does not change', () => {const withScenes = {...baseProject(),diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex b44c1f74fe..0bdc5bc0d7 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -9,18 +9,8 @@** Split out of the former 4,004-line peerSync.js (#1830).*/-import { join } from 'path';-import { existsSync } from 'fs';-import { createHash } from 'crypto';-import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';import { isStr } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';-import { peerBaseUrl } from '../../lib/peerUrl.js';-import { peerFetch } from '../../lib/peerHttpClient.js';-import { getOrComputeImageSha256 } from '../../lib/assetHash.js';-import { generateThumbnail } from '../../lib/ffmpeg.js';-import { pullSidecarForImage } from './sidecarSync.js';-import { sanitizeAssetFilename } from './buckets.js';import {PORTOS_SCHEMA_VERSIONS,RECORD_KIND_SCHEMA_CATEGORIES,@@ -50,15 +40,11 @@ import {getExerciseForSync,mergeExercisesFromSync,} from '../writersRoom/sync.js';-import { WRITERS_ROOM_DRAFT_ASSET_KIND } from '../writersRoom/syncLogic.js';-import { WORK_ID_RE, DRAFT_ID_RE, wrWorkDir, wrDraftPath } from '../writersRoom/_shared.js';import {- initCursor,ackDeletesUpTo,} from './peerTombstoneCursors.js';import {diffAssetManifestAgainstLocal,- directoryForAssetKind,pullMissingAssetsFromPeer,pullMissingWorkBodies,} from './peerSyncAssets.js';