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

fix: VideoGen busy-retry timer cleanup and FeatureAgentDetail load race (#2542)

Adam Eivyf6e6ca9fd2a1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7a57f0b5a6..909fe8e78e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -55,4 +55,5 @@
- **[issue-2527] Route client localStorage and keyboard activation through the shared `safeStorage`/`a11yKeyboard` helpers.** Several client sites bypassed the guarded `safeStorage` helpers with raw `window.localStorage` + hand-rolled `try/catch` (or `typeof window` guards), and several non-`<button>` clickables reimplemented the Enter/Space `onKeyDown` handler inline. Storage reads/writes in `Security.jsx`, `PipelineManuscriptEditor.jsx`, `voiceVisibility.js`, `MortalLoomBanner.jsx`, `WhileAwayWidget.jsx`, and `ManuscriptReadAloud.jsx` now go through `safeReadStorage`/`safeReadJsonStorage`/`safeWriteStorage`/`safeRemoveStorage`; keyboard activation in `IngredientPicker.jsx`, `ManuscriptReadAloud.jsx`, `EditorialHealthPanel.jsx`, `TribeCircleMap.jsx`, and `GenomeTab.jsx` now spreads `clickableProps(handler)` (which supplies `role`/`tabIndex`/`onKeyDown` via the shared `onActivateKeyDown`). Behavior is preserved — same storage keys, same JSON-parse fallbacks and corrupt-entry cleanup, same Enter/Space activation.
- **[issue-2532] Extract the Universe Builder's page-level lightbox into a `useUniverseGallery` hook.** `UniverseBuilder.jsx` inlined ~160 lines of gallery/preview plumbing — the filename→image-sidecar metadata map, the `listImageGallery()` refetch effect (keyed on `runs.length` + a per-job-completion bump), the `previewItems` derivation across variations/composite sheets/style probes/canon+character-sheet refs (namespaced-key dedupe), and the `usePreviewRoute`/`useMediaPreviewActions`/`useMediaAnnotations` wiring. That cohesive concern now lives in `client/src/hooks/useUniverseGallery.js` (takes `{ draft, runsLength }`, returns `{ previewItems, preview, setPreview, previewActions, openPreviewByFilename, openVariationPreview, annotations, updateAnnotation, bumpGalleryRefresh }`), thinning the page shell toward the WritersRoom pattern. Pure structural refactor — behavior identical, no route-contract change; the UniverseBuilder page suite and hooks barrel test stay green. Further hook/panel extractions (draft/expand/canon/bulk-render for UniverseBuilder, `useShellSession` for Shell) remain.
- **[issue-2545] Add `aria-label`s to icon-only controls and fix Templates/MessageDetail form labels.** Several icon-only buttons exposed their purpose only via `title` (unreliable for screen readers): the MessageDetail toolbar (Reply, voice-mode toggle, AI Reply, Refresh, Archive, Delete), MusicVideo scene move-up/move-down/delete, MediaCard hide/delete, the MediaJobsQueue per-job cancel, Review's edit save/cancel, and DuplicateGroup rename now carry an `aria-label` matching their `title`. The MessageDetail reply `<textarea>` (previously placeholder-only) gains an `aria-label`, and the Templates "Target Directory" `<label>` is now wired to its input via `htmlFor`/`id` so click-to-focus and screen readers work. Accessibility attributes only — no behavior or styling change.
+- **[issue-2542] Fix VideoGen busy-retry timer cleanup and FeatureAgentDetail load race.** The VideoGen queue worker's BUSY-backoff `setTimeout` was a local `let busyRetryTimer` assigned inside an async `.catch`, so the effect's own cleanup (consumed on every `setQueue`/`setRunningQueueId` re-run before the timer was ever assigned) couldn't clear it — an unmount during the 1.5s backoff, or a newer dispatch, could still fire `setRunningQueueId` on a torn-down component or steal a slot a newer item owned. The timer now lives on a `useRef`, is cleared by a dedicated unmount cleanup, and every deferred `then`/`catch`/`finally` (and the timer callback) is gated by a per-dispatch generation token plus a `mountedRef` so stale callbacks bail. Separately, `FeatureAgentDetail`'s `getFeatureAgent(id)` load had no stale guard, so an A→B navigation whose A response resolved late could paint the wrong agent; the load is now sequence-tokened (late/stale results ignored) with a `mountedRef` guard, and an A→B switch clears to the spinner immediately instead of flashing the previous agent.
- **[issue-2533] Extract JIRA-ticket claim assembly out of the route into `buildJiraTicketTask` (next to `buildClaimWorkTask`).** `POST /api/cos/tasks/jira-ticket` (the sprint-board per-card play button) inlined its reviewer-CSV resolution (`resolveClaimReviewersCsv`), the target-ticket constraint block (`buildTargetTicketBlock`), and the `claim-issue-jira` prompt assembly directly in `server/routes/cosTaskRoutes.js`. That logic now lives in `server/services/cosTaskGenerator.js` as an exported `buildJiraTicketTask(app, ticketKey)` that returns `{ ticketKey, prompt, taskMetadata }` — beside `buildClaimWorkTask`, sharing the same reviewer/isolation conventions. The route stays thin: validate → JIRA-enabled gate → assemble → queue. Pure refactor — the queued task's context, description, and `useWorktree/openPR` posture are byte-for-byte unchanged; new unit tests cover the extracted assembly.
diff --git a/client/src/pages/FeatureAgentDetail.jsx b/client/src/pages/FeatureAgentDetail.jsx
index fcb3fcc61a..c49400e739 100644
--- a/client/src/pages/FeatureAgentDetail.jsx
+++ b/client/src/pages/FeatureAgentDetail.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { Wand2, ArrowLeft } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -23,19 +23,34 @@ export default function FeatureAgentDetail() {
const [loading, setLoading] = useState(!isCreate);
const [apps, setApps] = useState([]);
+ // Unmount guard — never reset to true so StrictMode's mount→cleanup→remount
+ // can't strand it false and swallow the post-unmount stale-result check.
+ const mountedRef = useRef(true);
+ useEffect(() => () => { mountedRef.current = false; }, []);
+ // Monotonic load token: an A→B navigation fires a fresh fetch and bumps this,
+ // so a slow response for A resolving after we've switched to B is ignored
+ // instead of overwriting the displayed agent with the wrong record.
+ const fetchSeqRef = useRef(0);
+
useEffect(() => {
- api.getApps().then(data => setApps((data || []).filter(a => !a.archived))).catch(() => {});
+ api.getApps().then(data => { if (mountedRef.current) setApps((data || []).filter(a => !a.archived)); }).catch(() => {});
}, []);
const fetchAgent = useCallback(() => {
if (isCreate) return;
+ const seq = ++fetchSeqRef.current;
+ const isCurrent = () => mountedRef.current && seq === fetchSeqRef.current;
api.getFeatureAgent(id).then(data => {
+ if (!isCurrent()) return;
setAgent(data);
setLoading(false);
- }).catch(() => setLoading(false));
+ }).catch(() => { if (isCurrent()) setLoading(false); });
}, [id, isCreate]);
useEffect(() => {
+ // On an A→B switch, drop A's record and show the spinner immediately so a
+ // stale agent never flashes under the new id while B is still loading.
+ if (!isCreate) { setAgent(null); setLoading(true); }
fetchAgent();
const handler = (data) => { if (data.id === id) fetchAgent(); };
socket.on('cos:feature-agent:status', handler);
@@ -44,7 +59,7 @@ export default function FeatureAgentDetail() {
socket.off('cos:feature-agent:status', handler);
socket.off('cos:feature-agent:run-complete', handler);
};
- }, [fetchAgent, id]);
+ }, [fetchAgent, id, isCreate]);
const handleStart = useCallback((agentId) => {
api.startFeatureAgent(agentId, { silent: true }).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Activated'); }).catch(err => toast.error(err.message || 'Action failed'));
diff --git a/client/src/pages/FeatureAgentDetail.test.jsx b/client/src/pages/FeatureAgentDetail.test.jsx
new file mode 100644
index 0000000000..83994ed5c4
--- /dev/null
+++ b/client/src/pages/FeatureAgentDetail.test.jsx
@@ -0,0 +1,107 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor, act } from '@testing-library/react';
+import { MemoryRouter, Routes, Route, useNavigate } from 'react-router-dom';
+
+// Deferred-promise registry so a test can resolve A's load *after* navigating
+// to B, reproducing the stale-result race the guard is meant to defeat.
+const deferreds = {};
+function makeDeferred(id) {
+ let resolve;
+ const promise = new Promise((r) => { resolve = r; });
+ deferreds[id] = { promise, resolve };
+ return promise;
+}
+
+vi.mock('../services/api', () => ({
+ getApps: vi.fn().mockResolvedValue([]),
+ getFeatureAgent: vi.fn((id) => makeDeferred(id)),
+ startFeatureAgent: vi.fn(),
+ pauseFeatureAgent: vi.fn(),
+ resumeFeatureAgent: vi.fn(),
+ stopFeatureAgent: vi.fn(),
+ triggerFeatureAgent: vi.fn(),
+}));
+
+vi.mock('../services/socket', () => ({
+ default: { on: vi.fn(), off: vi.fn() },
+}));
+
+// Keep the tab children inert — the header (which shows agent.name) is what we
+// assert on for "which agent is displayed."
+vi.mock('../components/feature-agents/OverviewTab', () => ({ default: () => null }));
+vi.mock('../components/feature-agents/ConfigTab', () => ({ default: () => null }));
+vi.mock('../components/feature-agents/RunsTab', () => ({ default: () => null }));
+vi.mock('../components/feature-agents/OutputTab', () => ({ default: () => null }));
+vi.mock('../components/feature-agents/GitTab', () => ({ default: () => null }));
+
+import * as api from '../services/api';
+import FeatureAgentDetail from './FeatureAgentDetail';
+
+function Harness() {
+ const navigate = useNavigate();
+ return (
+ <>
+ <button onClick={() => navigate('/feature-agents/agent-b/overview')}>go-b</button>
+ <Routes>
+ <Route path="/feature-agents/:id/:tab" element={<FeatureAgentDetail />} />
+ </Routes>
+ </>
+ );
+}
+
+describe('FeatureAgentDetail load race', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ for (const k of Object.keys(deferreds)) delete deferreds[k];
+ });
+
+ it('ignores a stale A response that resolves after navigating A→B', async () => {
+ render(
+ <MemoryRouter initialEntries={['/feature-agents/agent-a/overview']}>
+ <Harness />
+ </MemoryRouter>,
+ );
+
+ // A's fetch is in flight; spinner shown.
+ expect(api.getFeatureAgent).toHaveBeenCalledWith('agent-a');
+ expect(screen.getByText(/Loading agent/)).toBeInTheDocument();
+
+ // Navigate A→B before A resolves.
+ await act(async () => {
+ screen.getByText('go-b').click();
+ });
+ await waitFor(() => expect(api.getFeatureAgent).toHaveBeenCalledWith('agent-b'));
+
+ // Resolve A LATE — must be ignored (wrong agent must never show).
+ await act(async () => {
+ deferreds['agent-a'].resolve({ id: 'agent-a', name: 'Agent Alpha', appId: 'app1' });
+ });
+ expect(screen.queryByText('Agent Alpha')).not.toBeInTheDocument();
+
+ // Resolve B — the current record is what renders.
+ await act(async () => {
+ deferreds['agent-b'].resolve({ id: 'agent-b', name: 'Agent Beta', appId: 'app2' });
+ });
+ await waitFor(() => expect(screen.getByText('Agent Beta')).toBeInTheDocument());
+ expect(screen.queryByText('Agent Alpha')).not.toBeInTheDocument();
+ });
+
+ it('shows the spinner (not the stale agent) immediately on A→B switch', async () => {
+ render(
+ <MemoryRouter initialEntries={['/feature-agents/agent-a/overview']}>
+ <Harness />
+ </MemoryRouter>,
+ );
+ await act(async () => {
+ deferreds['agent-a'].resolve({ id: 'agent-a', name: 'Agent Alpha', appId: 'app1' });
+ });
+ await waitFor(() => expect(screen.getByText('Agent Alpha')).toBeInTheDocument());
+
+ await act(async () => {
+ screen.getByText('go-b').click();
+ });
+ // B is still loading — the old agent name must be gone, spinner up.
+ expect(screen.queryByText('Agent Alpha')).not.toBeInTheDocument();
+ expect(screen.getByText(/Loading agent/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 0d952d6999..1d5a775c1f 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -553,6 +553,27 @@ export default function VideoGen() {
// again on cancel; runGeneration captures the value at start and bails
// when the token has moved on (e.g. POST resolves after cancel).
const runTokenRef = useRef(0);
+ // BUSY-backoff retry timer for the queue worker, held on a ref so it can be
+ // cleared from a stable unmount cleanup regardless of how often the worker
+ // effect re-runs (setQueue/setRunningQueueId churn consumes the effect's own
+ // cleanup before the async .catch ever assigns the timer, so the effect
+ // cleanup alone can't be trusted to clear it).
+ const busyRetryTimerRef = useRef(null);
+ // Generation token for the queue-worker dispatch. Bumped only when a new item
+ // is actually dispatched; a stale async then/catch/finally (from a superseded
+ // dispatch or after unmount) sees a moved-on token and bails without touching
+ // state or re-releasing the running slot.
+ const queueWorkerGenRef = useRef(0);
+ // Unmount guard for the queue worker's deferred callbacks. Never reset to true
+ // so StrictMode's mount→cleanup→remount can't strand it false.
+ const mountedRef = useRef(true);
+ useEffect(() => () => {
+ mountedRef.current = false;
+ if (busyRetryTimerRef.current) {
+ clearTimeout(busyRetryTimerRef.current);
+ busyRetryTimerRef.current = null;
+ }
+ }, []);
// Batch queue. Each item snapshots the params at enqueue time so the user
// can keep editing the form while jobs are in flight without affecting the
@@ -1266,6 +1287,11 @@ export default function VideoGen() {
if (generating || runningQueueId) return;
const next = queue.find((item) => item.status === 'pending');
if (!next) return;
+ // Capture a generation token for this dispatch. Every deferred callback
+ // below re-checks it (via isCurrent) so a superseded dispatch or an
+ // unmount can't set state / re-release the running slot after teardown.
+ const myGen = ++queueWorkerGenRef.current;
+ const isCurrent = () => mountedRef.current && myGen === queueWorkerGenRef.current;
setRunningQueueId(next.id);
setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'running', startedAt: Date.now() } : item));
const payload = { ...next.params };
@@ -1273,17 +1299,24 @@ export default function VideoGen() {
if (next._blobs?.lastImage) payload.lastImage = next._blobs.lastImage;
if (next._blobs?.audioFile) payload.audioFile = next._blobs.audioFile;
let busyRetry = false;
- let busyRetryTimer = null;
runGeneration(payload).then((res) => {
+ if (!isCurrent()) return;
setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'complete', result: res } : item));
}).catch((err) => {
+ if (!isCurrent()) return;
const isBusy = /already in progress|VIDEO_GEN_BUSY|409/i.test(err?.message || '');
if (isBusy) {
// Bounce the item back to pending after a short delay so the worker
// re-tries once the server's previous child has finished cleaning up.
busyRetry = true;
setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'pending', startedAt: undefined } : item));
- busyRetryTimer = setTimeout(() => setRunningQueueId((curr) => (curr === next.id ? null : curr)), 1500);
+ busyRetryTimerRef.current = setTimeout(() => {
+ busyRetryTimerRef.current = null;
+ // Stale/unmounted: a fresh dispatch (or teardown) already owns the
+ // slot, so don't release it out from under whatever runs now.
+ if (!isCurrent()) return;
+ setRunningQueueId((curr) => (curr === next.id ? null : curr));
+ }, 1500);
return;
}
setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'error', error: err.message } : item));
@@ -1291,13 +1324,20 @@ export default function VideoGen() {
// For the BUSY branch the timeout above releases the slot — releasing
// it here too would let the worker immediately re-fire and hit the
// same 409 before the server's old child has exited.
- if (!busyRetry) setRunningQueueId(null);
+ if (isCurrent() && !busyRetry) setRunningQueueId(null);
});
- // Effect cleanup: cancel a pending BUSY-retry setTimeout when the
- // component unmounts (or before this effect re-runs). Without this, an
- // unmount during the 1.5s BUSY backoff would fire setRunningQueueId on
- // a torn-down component (React warning + leaked state).
- return () => { if (busyRetryTimer) clearTimeout(busyRetryTimer); };
+ // Effect cleanup: cancel a pending BUSY-retry setTimeout. This is a
+ // best-effort clear; because the worker effect re-runs on every
+ // setQueue/setRunningQueueId, this cleanup is usually consumed before the
+ // async .catch assigns the timer — the authoritative clear lives in the
+ // dedicated unmount effect above, and the isCurrent()/mountedRef guards in
+ // the timer callback prevent any stale setState.
+ return () => {
+ if (busyRetryTimerRef.current) {
+ clearTimeout(busyRetryTimerRef.current);
+ busyRetryTimerRef.current = null;
+ }
+ };
}, [queue, generating, runningQueueId]);
const handleCancel = async () => {
diff --git a/client/src/pages/VideoGen.queueWorker.test.js b/client/src/pages/VideoGen.queueWorker.test.js
new file mode 100644
index 0000000000..014ab46580
--- /dev/null
+++ b/client/src/pages/VideoGen.queueWorker.test.js
@@ -0,0 +1,113 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// Faithful model of VideoGen's queue-worker BUSY-retry guard (see the effect in
+// client/src/pages/VideoGen.jsx). VideoGen is a >1400-line component with heavy
+// imports and an internal runGeneration(), so per the repo convention for
+// hard-to-mock logic (server subAgentSpawner.test.js) we exercise the exact
+// staleness/unmount guard here rather than full-rendering the page.
+//
+// The regression this locks in: the BUSY-retry setTimeout used to be a local
+// `let busyRetryTimer` assigned inside an async .catch. The effect re-runs on
+// every setQueue/setRunningQueueId, so its cleanup was consumed before the
+// timer was ever assigned — leaving the timer to fire setRunningQueueId after
+// unmount / after a newer dispatch owned the slot. The fix: timer on a ref,
+// cleared by a dedicated unmount cleanup, plus a generation token + mountedRef
+// guard on every deferred callback.
+
+function makeWorker() {
+ const busyRetryTimerRef = { current: null };
+ const queueWorkerGenRef = { current: 0 };
+ const mountedRef = { current: true };
+ let runningQueueId = null;
+ const setRunningQueueId = (fnOrVal) => {
+ runningQueueId = typeof fnOrVal === 'function' ? fnOrVal(runningQueueId) : fnOrVal;
+ };
+
+ // Dispatch one item; runGeneration is injected so the test controls resolution.
+ function dispatch(itemId, runGeneration) {
+ const myGen = ++queueWorkerGenRef.current;
+ const isCurrent = () => mountedRef.current && myGen === queueWorkerGenRef.current;
+ setRunningQueueId(itemId);
+ let busyRetry = false;
+ return runGeneration().then(() => {
+ if (!isCurrent()) return;
+ }).catch((err) => {
+ if (!isCurrent()) return;
+ const isBusy = /already in progress|VIDEO_GEN_BUSY|409/i.test(err?.message || '');
+ if (isBusy) {
+ busyRetry = true;
+ busyRetryTimerRef.current = setTimeout(() => {
+ busyRetryTimerRef.current = null;
+ if (!isCurrent()) return;
+ setRunningQueueId((curr) => (curr === itemId ? null : curr));
+ }, 1500);
+ return;
+ }
+ }).finally(() => {
+ if (isCurrent() && !busyRetry) setRunningQueueId(null);
+ });
+ }
+
+ function unmount() {
+ mountedRef.current = false;
+ if (busyRetryTimerRef.current) {
+ clearTimeout(busyRetryTimerRef.current);
+ busyRetryTimerRef.current = null;
+ }
+ }
+
+ return {
+ dispatch,
+ unmount,
+ get runningQueueId() { return runningQueueId; },
+ get timer() { return busyRetryTimerRef.current; },
+ get gen() { return queueWorkerGenRef.current; },
+ };
+}
+
+describe('VideoGen queue-worker BUSY-retry guard', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('releases the slot after the BUSY backoff when still current', async () => {
+ const w = makeWorker();
+ await w.dispatch('a', () => Promise.reject(new Error('VIDEO_GEN_BUSY')));
+ expect(w.runningQueueId).toBe('a');
+ expect(w.timer).not.toBeNull();
+ vi.advanceTimersByTime(1500);
+ expect(w.runningQueueId).toBeNull();
+ expect(w.timer).toBeNull();
+ });
+
+ it('does NOT release the slot when unmounted during the backoff', async () => {
+ const w = makeWorker();
+ await w.dispatch('a', () => Promise.reject(new Error('409 already in progress')));
+ expect(w.timer).not.toBeNull();
+ w.unmount(); // teardown clears the ref timer
+ expect(w.timer).toBeNull();
+ vi.advanceTimersByTime(5000);
+ // Nothing to fire — and even a leaked fire would bail on mountedRef.
+ expect(w.runningQueueId).toBe('a');
+ });
+
+ it('a stale BUSY timer never releases a slot a newer dispatch now owns', async () => {
+ const w = makeWorker();
+ // Dispatch A → BUSY, timer scheduled for gen 1.
+ await w.dispatch('a', () => Promise.reject(new Error('VIDEO_GEN_BUSY')));
+ const genAfterA = w.gen;
+ // Before the timer fires, a newer dispatch (B) supersedes it.
+ await w.dispatch('b', () => Promise.resolve());
+ expect(w.gen).toBeGreaterThan(genAfterA);
+ // B resolved current and released, so slot is null; then A's stale timer fires.
+ vi.advanceTimersByTime(1500);
+ // The stale timer must NOT touch the slot (its isCurrent() is false).
+ expect(w.runningQueueId).toBeNull();
+ });
+
+ it('marks a non-BUSY failure as done and releases the slot immediately', async () => {
+ const w = makeWorker();
+ await w.dispatch('a', () => Promise.reject(new Error('boom')));
+ expect(w.timer).toBeNull();
+ expect(w.runningQueueId).toBeNull();
+ });
+});