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([codex5-polling-consolidation]): address codex review — key-change refetch, drop mount-time double fetch, doc the null sentinel
[._.]/ Adam Eivyad3b64c5a86a
diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsxindex 98bd33c3bf..2c51062741 100644--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx@@ -37,15 +37,9 @@ export default function EpisodeVideoStage({ issue, series, onStageUpdate }) {const [aspectRatio, setAspectRatio] = useState(stage.aspectRatio || '16:9');const [quality, setQuality] = useState(stage.quality || 'standard');- // Clear the displayed project when the cdProjectId itself goes away- // (stage reset). Fresh project ids flow in via the poll below.- useEffect(() => {- if (!cdProjectId) setCdProject(null);- }, [cdProjectId]);-// Poll while the project could still mutate. Pauses on hidden tab via// useAutoRefetch's visibility short-circuit and stops once status is terminal.- useAutoRefetch(+ const { refetch: refetchCdProject } = useAutoRefetch(async () => {const p = await getCreativeDirectorProject(cdProjectId, { slim: true }).catch((err) => {console.log(`pipeline:episode poll error ${err.message}`);@@ -63,6 +57,14 @@ export default function EpisodeVideoStage({ issue, series, onStageUpdate }) {{ enabled: !!cdProjectId && !isTerminalProjectStatus(cdProject?.status) },);+ // Clear the displayed project on stage reset; refetch immediately on id+ // change so a project swap doesn't strand the previous project on screen+ // until the next interval tick.+ useEffect(() => {+ if (!cdProjectId) setCdProject(null);+ else refetchCdProject();+ }, [cdProjectId, refetchCdProject]);+const [runSubmit, submitting] = useAsyncAction(async ({ force }) => {const payload = { aspectRatio, quality };diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.jsindex 315e8f25d9..18fdd4d588 100644--- a/client/src/hooks/useAutoRefetch.js+++ b/client/src/hooks/useAutoRefetch.js@@ -5,19 +5,22 @@ import { useState, useEffect, useRef, useCallback } from 'react';* once when it becomes visible again. Replaces the per-component* useEffect + setInterval pattern for data-fetch polling.*- * fetchFn should handle its own errors and return either the new data or- * `null` (the documented "no change / use prior" sentinel — returning- * `undefined` would set data to undefined and lose prior state).- * Side-effect-only callers that manage their own state should `return null`.+ * fetchFn should handle its own errors. Side-effect-only callers that manage+ * their own state via setStates inside fetchFn typically `return null` and+ * ignore the hook's `data` return; that's fine, but be aware the hook will+ * still set `data = null` on each tick.*- * @param {Function} fetchFn - async, returns the new data or null+ * @param {Function} fetchFn - async, returns the new data* @param {number} intervalMs - poll cadence; changing restarts the interval* @param {Object} [options]* @param {boolean} [options.enabled=true] - when false, no interval and no fetch+ * @param {boolean} [options.immediate=true] - when false, skip the on-mount fetch+ * and wait `intervalMs` before the first fetch. Use when the caller already+ * performs a one-shot fetch via another path (e.g. `useCityData.fetchAll`).* @returns {{ data: any, loading: boolean, refetch: Function }}*/export function useAutoRefetch(fetchFn, intervalMs, options = {}) {- const { enabled = true } = options;+ const { enabled = true, immediate = true } = options;const [data, setData] = useState(null);const [loading, setLoading] = useState(true);const fetchRef = useRef(fetchFn);@@ -27,7 +30,8 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {}, [fetchFn]);// Stable, unconditional refetch for callers (Refresh buttons, post-mutation- // refresh paths). Bypasses the visibility short-circuit — when a user+ // refresh paths, and key-change effects that need an immediate fetch with+ // the new closure). Bypasses the visibility short-circuit — when a user// clicks Refresh the tab is by definition visible.const refetch = useCallback(async () => {try {@@ -64,7 +68,7 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {if (document.visibilityState === 'visible') loadData();};- loadData();+ if (immediate) loadData();const interval = setInterval(loadData, intervalMs);if (typeof document !== 'undefined') {document.addEventListener('visibilitychange', handleVisibilityChange);@@ -77,7 +81,7 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {document.removeEventListener('visibilitychange', handleVisibilityChange);}};- }, [intervalMs, enabled]);+ }, [intervalMs, enabled, immediate]);return { data, loading, refetch };}diff --git a/client/src/hooks/useAutoRefetch.test.jsx b/client/src/hooks/useAutoRefetch.test.jsxindex caf1a00815..6fe2e4984e 100644--- a/client/src/hooks/useAutoRefetch.test.jsx+++ b/client/src/hooks/useAutoRefetch.test.jsx@@ -83,6 +83,18 @@ describe('useAutoRefetch', () => {warn.mockRestore();});+ it('skips the on-mount fetch when immediate is false', async () => {+ const fetchFn = vi.fn().mockResolvedValue('x');+ renderHook(() => useAutoRefetch(fetchFn, 60, { immediate: false }));++ // Give the effect a chance to run; no fetch should fire yet.+ await new Promise((r) => setTimeout(r, 20));+ expect(fetchFn).not.toHaveBeenCalled();++ // The interval still ticks after `intervalMs`.+ await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1), { timeout: 500 });+ });+it('exposes a refetch handle that fetches on demand and updates data', async () => {const fetchFn = vi.fn().mockResolvedValueOnce('first')diff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.jsindex 988c3e4350..578ce58241 100644--- a/client/src/hooks/useCityData.js+++ b/client/src/hooks/useCityData.js@@ -76,8 +76,12 @@ export const useCityData = () => {return null;}, []);- useAutoRefetch(fetchRunningAgents, 10_000);- useAutoRefetch(fetchHealth, 15_000);+ // `immediate: false` — `fetchAll()` (run from the socket-setup effect below+ // and from agent socket events) already covers the initial fetch for both+ // running agents and system health; the hook then takes over the polling+ // cadence without double-fetching at mount.+ useAutoRefetch(fetchRunningAgents, 10_000, { immediate: false });+ useAutoRefetch(fetchHealth, 15_000, { immediate: false });const agentMap = useMemo(() => {const map = new Map();diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxindex a244f893e9..4a1571eb3e 100644--- a/client/src/pages/CreativeDirectorDetail.jsx+++ b/client/src/pages/CreativeDirectorDetail.jsx@@ -42,16 +42,6 @@ export default function CreativeDirectorDetail() {return null;}, [id]);- // Reset state ONLY when the route id changes, so navigating between- // projects (or hitting an error fetch) clears the prior project — but- // the 5s poll interval below doesn't keep nulling-and-re-setting the- // same project (which previously coupled with the `project?.status`- // dep on the polling effect to produce a tight refetch loop).- useEffect(() => {- setLoading(true);- setProject(null);- }, [id]);-// Poll CoS agents in parallel so the Segments tab can flag the scene that's// currently being worked on, even before the agent PATCHes its status.// Filter by `taskId` prefix `cd-<projectId>-` (agentBridge's id scheme).@@ -70,7 +60,20 @@ export default function CreativeDirectorDetail() {await Promise.all([fetchProject(), fetchAgents()]);return null;}, [fetchProject, fetchAgents]);- useAutoRefetch(poll, 5000, { enabled: pollEnabled });+ const { refetch: refetchPoll } = useAutoRefetch(poll, 5000, { enabled: pollEnabled });++ // Reset state ONLY when the route id changes, so navigating between+ // projects (or hitting an error fetch) clears the prior project — but+ // the 5s poll interval below doesn't keep nulling-and-re-setting the+ // same project (which previously coupled with the `project?.status`+ // dep on the polling effect to produce a tight refetch loop). Refetch+ // immediately on id change so a project swap doesn't leave the previous+ // project on screen for up to one tick.+ useEffect(() => {+ setLoading(true);+ setProject(null);+ refetchPoll();+ }, [id, refetchPoll]);const handleAction = async (kind) => {// Map action → past-tense label and optimistic status up-front.