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

refactor(client): route eleven hand-rolled polling intervals through useAutoRefetch (#5697)

[._.]/ Adam Eivy428d557900aa
diff --git a/client/src/AGENTS.md b/client/src/AGENTS.md
index a311c8c221..28e3a915e8 100644
--- a/client/src/AGENTS.md
+++ b/client/src/AGENTS.md
@@ -15,6 +15,7 @@ These apply to React/Vite client code. Universal constraints (functional program
- **OpenWorld's internal names match the user-facing area.** The scene tree lives under `components/openworld/`, its pure helpers are `utils/openWorld*.js`, its hooks are `useOpenWorld*.js`, and its CSS scope is `.openworld-themed`. The legacy OpenWorld command ids remain deliberately frozen because they are opaque values persisted in ⌘K history. Keep the persisted `portos-city-settings` key unchanged when adding settings migrations.
- **Space is an app-global hotkey** - the voice widget binds Space for push-to-talk. A surface that owns Space itself (a timed drill, a keyer, a transport control) must claim it with `useKeyCapture` (capture phase + `stopImmediatePropagation`), or the mic opens on every press. Conversely, a global single-key handler stands down when the browser is about to activate a focused button. All three global key paths — `useKeyCapture`, `useKeyboardShortcuts`, and the voice widget's own hotkey listener — decide that through the one shared `shouldIgnoreGlobalKey(event, opts)` predicate in `lib/a11yKeyboard.js`, so a new guard goes THERE, never at one caller (that drift is what let `useKeyCapture` swallow button activation, #4748). The corollary: a surface that OWNS a key spreads `noPointerFocusSurfaceProps` on its ROOT — a mouse click that parks focus on any button inside silently takes that key over, because the global handler correctly stands down for native activation. Put it on the root, not on each button, so controls added later are covered without anyone having to remember.
- **Web Storage goes through `lib/safeStorage.js`** - `localStorage`/`sessionStorage` **throw** rather than returning null in Safari private browsing, with cookies disabled, in a sandboxed iframe, and at quota — and in several of those the object still exists, so `typeof sessionStorage === 'undefined'` is not a guard and neither is `?.` (it only covers a null base, not a throwing `getItem`). Use `safeReadStorage` / `safeWriteStorage` / `safeRemoveStorage` and their `Json` and `*Session` variants. This is not a lost-preference nit: a raw read in a **render body** is a render-phase exception that unmounts the whole route, and a raw write in an effect kills the flow mid-session (#5689). Enforced tree-wide by `client/src/storageConventions.test.js`.
+- **Interval polling goes through `useAutoRefetch`** - a view that re-fetches on a timer uses `useAutoRefetch(fetchFn, intervalMs, { enabled, pollOnly: true })` (`hooks/useAutoRefetch.js`), never a hand-rolled `useEffect` + `setInterval`. The hook skips its tick while `document.visibilityState === 'hidden'` and re-fires once on the way back; a raw interval keeps hammering the server from a background tab, and PortOS is routinely left open on a second machine over the tailnet (#5697). Keep the site's existing gate as `enabled` rather than an early `return`, and pass `immediate: false` when another effect already owns the first fetch. Enforced tree-wide by `client/src/pollingConventions.test.js`, which allowlists the local timers that are not polls (clock ticks, frame advances, a bounded self-cancelling poll).
- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback
## API errors and save gating
diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsx
index 867bdd4bf1..4c3ab29274 100644
--- a/client/src/components/apps/AppDetailView.jsx
+++ b/client/src/components/apps/AppDetailView.jsx
@@ -10,6 +10,7 @@ import * as api from '../../services/api';
import { getLaunchUrls } from '../../services/appUrls';
import socket from '../../services/socket';
import { APP_DETAIL_TABS, NON_PM2_TYPES, getAppTypeLabel, isAppFeatureEnabled, resolveLaunchPanelProcess } from './constants';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';
import { useInstanceFeatures } from '../../hooks/useInstanceFeatures.js';
import DesktopLaunchProgress from './DesktopLaunchProgress';
import OverviewTab from './tabs/OverviewTab';
@@ -126,29 +127,22 @@ export default function AppDetailView() {
// Native launch status is independent of the web app's overall PM2 state.
// Poll only while its live-output panel is open so closing the game moves the
// panel from Running to Exited without disturbing the standard web controls.
- useEffect(() => {
- if (!launchProcess || launchProcess !== app?.nativeLaunch?.processName) return;
- let cancelled = false;
- const refresh = () => {
- api.getNativeLaunchStatus(appId, { silent: true })
- .then(result => {
- if (cancelled) return;
- if (['online', 'launching'].includes(result?.status)) {
- setNativeLaunchOnline(true);
- } else if (['stopped', 'errored', 'not_found', 'not_started'].includes(result?.status)) {
- setNativeLaunchOnline(false);
- }
- })
- // A failed status read is unknown, not evidence that the game exited.
- .catch(() => {});
- };
- refresh();
- const timer = setInterval(refresh, 1500);
- return () => {
- cancelled = true;
- clearInterval(timer);
- };
- }, [appId, app?.nativeLaunch?.processName, launchProcess]);
+ const refreshNativeLaunchStatus = useCallback(() => (
+ api.getNativeLaunchStatus(appId, { silent: true })
+ .then(result => {
+ if (['online', 'launching'].includes(result?.status)) {
+ setNativeLaunchOnline(true);
+ } else if (['stopped', 'errored', 'not_found', 'not_started'].includes(result?.status)) {
+ setNativeLaunchOnline(false);
+ }
+ })
+ // A failed status read is unknown, not evidence that the game exited.
+ .catch(() => {})
+ ), [appId]);
+ useAutoRefetch(refreshNativeLaunchStatus, 1500, {
+ enabled: Boolean(launchProcess) && launchProcess === app?.nativeLaunch?.processName,
+ pollOnly: true,
+ });
const handleStop = async () => {
setActionLoading('stop');
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsx
index 39ca0d6358..aab5c6ce58 100644
--- a/client/src/components/cos/tabs/ConfigTab.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.jsx
@@ -17,6 +17,7 @@ import {
} from 'lucide-react';
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
+import { useAutoRefetch } from '../../../hooks/useAutoRefetch.js';
import PersistentMindProfileControls from '../PersistentMindProfileControls';
import { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';
import ConfigRow from './ConfigRow';
@@ -270,11 +271,7 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle })
), []);
useEffect(() => { void refreshBudgetUsage(); }, [refreshBudgetUsage]);
- useEffect(() => {
- void refreshMindStatus();
- const interval = setInterval(() => { void refreshMindStatus(); }, 15_000);
- return () => clearInterval(interval);
- }, [refreshMindStatus]);
+ useAutoRefetch(refreshMindStatus, 15_000, { pollOnly: true });
const handleCancel = () => {
setFormData(getDefaultFormData(config, avatarStyle));
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index 8f15cafd75..3066f99667 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
import { ArrowUp, Brain, Check, CirclePause, CirclePlay, Cpu, Database, Eraser, ImagePlus, MessageCircle, PhoneCall, PhoneOff, RefreshCw, Settings2, Square, StickyNote, Upload, Wrench, X } from 'lucide-react';
import { Link } from 'react-router';
+import { useAutoRefetch } from '../../../hooks/useAutoRefetch.js';
import useMounted from '../../../hooks/useMounted';
import { useSocket } from '../../../hooks/useSocket';
import { uuidv4 } from '../../../lib/uuid.js';
@@ -314,16 +315,8 @@ export default function MindTab() {
}, [runtimeMountedRef]);
useEffect(() => { void loadHistory({ reset: true }); }, [loadHistory]);
- useEffect(() => {
- void loadRuntime();
- const interval = setInterval(() => { void loadRuntime(); }, 10_000);
- return () => clearInterval(interval);
- }, [loadRuntime]);
- useEffect(() => {
- void loadVisibility();
- const interval = setInterval(() => { void loadVisibility(); }, 30_000);
- return () => clearInterval(interval);
- }, [loadVisibility]);
+ useAutoRefetch(loadRuntime, 10_000, { pollOnly: true });
+ useAutoRefetch(loadVisibility, 30_000, { pollOnly: true });
useEffect(() => {
const refresh = () => {
diff --git a/client/src/components/fableloom/LoomEditorialAutomation.jsx b/client/src/components/fableloom/LoomEditorialAutomation.jsx
index e9856db254..b2613d71bb 100644
--- a/client/src/components/fableloom/LoomEditorialAutomation.jsx
+++ b/client/src/components/fableloom/LoomEditorialAutomation.jsx
@@ -6,6 +6,7 @@ import {
import ProviderModelSelector from '../ProviderModelSelector';
import toast from '../ui/Toast';
import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';
import useFableLoomAiRun from '../../hooks/useFableLoomAiRun';
import useProviderModels from '../../hooks/useProviderModels';
import {
@@ -109,18 +110,14 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {
}, [loom.id]);
const autopilotActive = ACTIVE_STATUSES.has(autopilotRun?.status);
- useEffect(() => {
- if (!autopilotActive || !autopilotRun?.id) return undefined;
- let ignore = false;
- const refresh = () => getLoomEditorialAutopilotRun(loom.id, autopilotRun.id, { silent: true })
- .then((run) => { if (!ignore) setAutopilotRun(run); })
- .catch(() => {});
- const interval = setInterval(refresh, 2000);
- return () => {
- ignore = true;
- clearInterval(interval);
- };
- }, [autopilotActive, autopilotRun?.id, loom.id]);
+ const refreshAutopilotRun = () => getLoomEditorialAutopilotRun(loom.id, autopilotRun.id, { silent: true })
+ .then(setAutopilotRun)
+ .catch(() => {});
+ useAutoRefetch(refreshAutopilotRun, 2000, {
+ enabled: autopilotActive && Boolean(autopilotRun?.id),
+ immediate: false,
+ pollOnly: true,
+ });
useEffect(() => {
if (!TERMINAL_STATUSES.has(autopilotRun?.status)
diff --git a/client/src/components/fableloom/LoomProductionPanel.jsx b/client/src/components/fableloom/LoomProductionPanel.jsx
index 9b3420679f..717c4668a0 100644
--- a/client/src/components/fableloom/LoomProductionPanel.jsx
+++ b/client/src/components/fableloom/LoomProductionPanel.jsx
@@ -22,6 +22,7 @@ import {
StopCircle,
} from 'lucide-react';
import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';
import BackendChipStrip from '../media/BackendChipStrip';
import {
cancelLoomEpisodeProductionBatch,
@@ -178,30 +179,30 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode, onLoo
setActiveBatchRun(null);
}, [productionIdentity]);
- // Batch run polling
- useEffect(() => {
- if (!activeBatchRun || activeBatchRun.status !== 'in_progress') return undefined;
- const interval = setInterval(() => {
- getLoomEpisodeProductionBatch(
- activeBatchRun.loomId,
- activeBatchRun.episodeId,
- activeBatchRun.id,
- { silent: true },
- )
- .then((updated) => {
- if (!updated) return;
- if (`${updated.loomId}:${updated.episodeId}` !== productionIdentityRef.current) return;
- setActiveBatchRun(updated);
- if (updated.status === 'completed' || updated.status === 'canceled' || updated.status === 'failed') {
- fetchPlan(mode);
- }
- })
- .catch(() => {
- // Polling is best-effort; the next interval can reattach to the run.
- });
- }, 2000);
- return () => clearInterval(interval);
- }, [activeBatchRun, mode]);
+ // Batch run polling. Only reached while a run is in progress, so the
+ // non-null read of activeBatchRun below is guarded by `enabled`.
+ const refreshBatchRun = () => getLoomEpisodeProductionBatch(
+ activeBatchRun.loomId,
+ activeBatchRun.episodeId,
+ activeBatchRun.id,
+ { silent: true },
+ )
+ .then((updated) => {
+ if (!updated) return;
+ if (`${updated.loomId}:${updated.episodeId}` !== productionIdentityRef.current) return;
+ setActiveBatchRun(updated);
+ if (updated.status === 'completed' || updated.status === 'canceled' || updated.status === 'failed') {
+ fetchPlan(mode);
+ }
+ })
+ .catch(() => {
+ // Polling is best-effort; the next tick can reattach to the run.
+ });
+ useAutoRefetch(refreshBatchRun, 2000, {
+ enabled: activeBatchRun?.status === 'in_progress',
+ immediate: false,
+ pollOnly: true,
+ });
const [startBatch, startingBatch] = useAsyncAction(async () => {
const requestedIdentity = productionIdentity;
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 1ca954e78b..b44eec1055 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -368,11 +368,12 @@ function TrainingJobDetail({ runId, status }) {
useEffect(() => { load(); }, [load]);
// Poll only while the run is live — a terminal run's checkpoints are fixed.
- useEffect(() => {
- if (status !== 'running' && status !== 'queued') return undefined;
- const t = setInterval(load, 5000);
- return () => clearInterval(t);
- }, [status, load]);
+ // `immediate: false` because the effect above already owns the first load.
+ useAutoRefetch(load, 5000, {
+ enabled: status === 'running' || status === 'queued',
+ immediate: false,
+ pollOnly: true,
+ });
if (checkpoints === null) {
return <div className="mt-2 text-[11px] text-port-text-muted">Loading checkpoints…</div>;
diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsx
index cc6afbddbd..c293d1c16f 100644
--- a/client/src/components/media/MediaJobsQueue.test.jsx
+++ b/client/src/components/media/MediaJobsQueue.test.jsx
@@ -1,5 +1,5 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
+import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { retypeSettled } from '../../test/settledInput';
@@ -398,6 +398,39 @@ describe('MediaJobsQueue — training rows', () => {
});
});
+// #5697 — the checkpoint poll used to be a raw `useEffect` + `setInterval`, so
+// a live training run kept re-listing checkpoints every 5s from a background
+// tab. This is the gated (`enabled`) half of the migration; MemoryManagement
+// covers the unconditional half.
+describe('MediaJobsQueue — hidden-tab polling (#5697)', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('pauses the checkpoint poll while the tab is hidden and re-fires on return', async () => {
+ listMediaJobs.mockResolvedValue([trainingJob]);
+ listLoraTrainingCheckpoints.mockResolvedValue({ checkpoints: [] });
+
+ render(<MediaJobsQueue kind="training" />);
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(1);
+ const jobListCalls = listMediaJobs.mock.calls.length;
+
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(1);
+ // The queue's own job poll is paused by the same hook.
+ expect(listMediaJobs.mock.calls.length).toBe(jobListCalls);
+
+ visibility.mockReturnValue('visible');
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(listLoraTrainingCheckpoints).toHaveBeenCalledTimes(2);
+ visibility.mockRestore();
+ });
+});
+
// The conditioning promise (#4874) rides a video retry — and has to snap back
// when the user retargets the retry at a model that pins frame one, because the
// picker offers only Anchor there and the server rejects the mismatch.
diff --git a/client/src/components/settings/MemoryManagement.jsx b/client/src/components/settings/MemoryManagement.jsx
index 4f389ca735..411a60082b 100644
--- a/client/src/components/settings/MemoryManagement.jsx
+++ b/client/src/components/settings/MemoryManagement.jsx
@@ -21,11 +21,12 @@
// apiCore's default toast doesn't fire underneath; per the AGENTS.md
// "Silent vs. toasting API requests" rule, custom catch ⇒ silent: true.
-import { useState, useEffect, useCallback, useRef } from 'react';
+import { useState, useCallback, useRef } from 'react';
import { Cpu, Mic, Volume2, Trash2, Power, PowerOff, RefreshCw, AlertTriangle } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';
import useMounted from '../../hooks/useMounted.js';
import { formatBytes } from '../../utils/formatters';
import {
@@ -170,11 +171,7 @@ export default function MemoryManagement({ onLoadedModelsChange } = {}) {
return snapshot;
}, [mountedRef, onLoadedModelsChange]);
- useEffect(() => {
- refresh();
- const t = setInterval(refresh, POLL_MS);
- return () => clearInterval(t);
- }, [refresh]);
+ useAutoRefetch(refresh, POLL_MS, { pollOnly: true });
const [unloadModel, unloadingModel] = useAsyncAction(async (modelId) => {
await unloadOllamaModel(modelId, SILENT);
diff --git a/client/src/components/settings/MemoryManagement.test.jsx b/client/src/components/settings/MemoryManagement.test.jsx
index 98ef8ce6da..aa47d19734 100644
--- a/client/src/components/settings/MemoryManagement.test.jsx
+++ b/client/src/components/settings/MemoryManagement.test.jsx
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
vi.mock('../../services/apiLocalLlm.js', () => ({
@@ -110,6 +110,33 @@ describe('MemoryManagement', () => {
expect(screen.queryByText(/full unified memory is available/i)).not.toBeInTheDocument();
});
+ // #5697 — this poll used to be a raw `useEffect` + `setInterval`, so it kept
+ // probing the local LLM / TTS / voice status endpoints every 5s from a tab
+ // nobody was looking at. It is the unconditional (always-`enabled`) half of
+ // the migration; MediaJobsQueue covers the gated half.
+ describe('hidden-tab polling', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('pauses the residency poll while the tab is hidden and re-fires on return', async () => {
+ render(<MemoryManagement />);
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(1);
+
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(1);
+
+ visibility.mockReturnValue('visible');
+ await act(async () => {
+ document.dispatchEvent(new Event('visibilitychange'));
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(getLoadedLlmModels).toHaveBeenCalledTimes(2);
+ visibility.mockRestore();
+ });
+ });
+
it('keeps a backend disabled across a later failed poll', async () => {
// The banner-suppression scenario IS a transient outage, so a failed poll
// must not resurrect the warning for a backend a good poll already marked
diff --git a/client/src/components/sprites/TrackWorkflow.jsx b/client/src/components/sprites/TrackWorkflow.jsx
index 86fe021554..d90ccafa8b 100644
--- a/client/src/components/sprites/TrackWorkflow.jsx
+++ b/client/src/components/sprites/TrackWorkflow.jsx
@@ -1,8 +1,9 @@
-import { useEffect, useMemo } from 'react';
+import { useMemo } from 'react';
import { Check, Film, Radio, RefreshCw, Wind } from 'lucide-react';
import toast from '../ui/Toast';
import { approveSpriteTrack, reopenSpriteTrack } from '../../services/apiSprites.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';
import { SPRITE_DIRECTIONS } from '../../lib/spriteFacets.js';
import { CorrectionNoteToggle, trackCorrectionKey } from './CorrectionNote.jsx';
import { checkerboardStyle, spriteAssetUrl } from './spriteAssets.js';
@@ -48,11 +49,7 @@ export default function TrackWorkflow({
])), [runs, directions]);
const working = runs.some((run) => ['rendering', 'postprocessing'].includes(run.status));
- useEffect(() => {
- if (!working) return undefined;
- const timer = setInterval(onChanged, 4000);
- return () => clearInterval(timer);
- }, [working, onChanged]);
+ useAutoRefetch(onChanged, 4000, { enabled: working, immediate: false, pollOnly: true });
const [approve, approving] = useAsyncAction(async (direction, runId) => {
await approveSpriteTrack(record.id, definition.id, { direction, runId }, { silent: true });
diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsx
index a2717d7a59..4d6bfd8784 100644
--- a/client/src/pages/LocalLlmPlayground.jsx
+++ b/client/src/pages/LocalLlmPlayground.jsx
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useAutoRefetch } from '../hooks/useAutoRefetch.js';
import useMounted from '../hooks/useMounted';
import { Link, useSearchParams } from 'react-router';
import { ArrowLeft, ArrowRightLeft, Brain, Check, ChevronDown, Clock, Copy, Cpu, Gauge, MessageSquare, Play, RefreshCw, Send, TriangleAlert, X } from 'lucide-react';
@@ -307,11 +308,7 @@ export default function LocalLlmPlayground() {
// Poll which models are warm in memory. A faster cadence while a run is busy
// so the "serving" flag and freed-slot countdown stay live; relaxed when idle.
- useEffect(() => {
- refreshLoaded();
- const interval = setInterval(refreshLoaded, busy ? 2000 : 6000);
- return () => clearInterval(interval);
- }, [refreshLoaded, busy]);
+ useAutoRefetch(refreshLoaded, busy ? 2000 : 6000, { pollOnly: true });
const installedTargets = useMemo(() => {
const models = [];
diff --git a/client/src/pages/Loops.jsx b/client/src/pages/Loops.jsx
index 5723bf2dcc..04135c4608 100644
--- a/client/src/pages/Loops.jsx
+++ b/client/src/pages/Loops.jsx
@@ -42,7 +42,7 @@ function StatusBadge({ loop }) {
function CreateLoopForm({ providers, onCreated }) {
const [prompt, setPrompt] = useState('');
- const [interval, setInterval] = useState('10m');
+ const [interval, setIntervalPreset] = useState('10m');
const [customInterval, setCustomInterval] = useState('');
const [name, setName] = useState('');
const [providerId, setProviderId] = useState('');
@@ -100,7 +100,7 @@ function CreateLoopForm({ providers, onCreated }) {
<button
key={p.value}
type="button"
- onClick={() => { setInterval(p.value); setCustomInterval(''); }}
+ onClick={() => { setIntervalPreset(p.value); setCustomInterval(''); }}
className={`px-2 py-1 text-xs rounded border ${
interval === p.value && !customInterval
? 'border-port-accent bg-port-accent/20 text-port-accent'
diff --git a/client/src/pages/LoraDatasetDetail.jsx b/client/src/pages/LoraDatasetDetail.jsx
index 25a6bb717d..d245a5932b 100644
--- a/client/src/pages/LoraDatasetDetail.jsx
+++ b/client/src/pages/LoraDatasetDetail.jsx
@@ -20,6 +20,7 @@ import toast from '../components/ui/Toast';
import FilePickerButton from '../components/ui/FilePickerButton';
import { IMAGE_ACCEPT } from '../utils/fileUpload';
import Modal from '../components/ui/Modal';
+import { useAutoRefetch } from '../hooks/useAutoRefetch.js';
import { useSseProgress } from '../hooks/useSseProgress';
import DatasetImageGrid from '../components/loraTraining/DatasetImageGrid';
import GenerateBatchDialog from '../components/loraTraining/GenerateBatchDialog';
@@ -371,11 +372,7 @@ export default function LoraDatasetDetail({ recordId }) {
// Poll while any image renders — the server heals stuck images on read.
const renderingCount = readiness.rendering;
- useEffect(() => {
- if (!renderingCount) return undefined;
- const timer = setInterval(refresh, 5000);
- return () => clearInterval(timer);
- }, [renderingCount, refresh]);
+ useAutoRefetch(refresh, 5000, { enabled: renderingCount > 0, immediate: false, pollOnly: true });
// Caption-run SSE — refetch on terminal so captions land in the grid, and
// surface failures the run reported. The server emits per-image `error`
diff --git a/client/src/pollingConventions.test.js b/client/src/pollingConventions.test.js
new file mode 100644
index 0000000000..e85c5a5a29
--- /dev/null
+++ b/client/src/pollingConventions.test.js
@@ -0,0 +1,146 @@
+// @vitest-environment node
+
+/**
+ * Repo-wide guard: data-fetch polling in a view goes through `useAutoRefetch`.
+ *
+ * `hooks/useAutoRefetch.js` short-circuits its tick while
+ * `document.visibilityState === 'hidden'` and re-fires once on the way back to
+ * visible. A hand-rolled `useEffect` + `setInterval` does neither, so it keeps
+ * hitting the server from a tab nobody is looking at — and PortOS is routinely
+ * left open in a background tab on a second machine over the tailnet. Eleven
+ * such polls had accumulated (#5697), several of which fanned out to `pm2
+ * jlist` or Ollama on every tick.
+ *
+ * The rule is deliberately blunt: **no `setInterval` at all** under
+ * `src/components/` or `src/pages/`, except for an allowlisted file carrying a
+ * one-line reason. A rule that tried to tell "a poll that fetches" from "a
+ * timer that ticks a clock" by looking at the callback body would have to
+ * recognize every API-call spelling in the tree, and would miss the next one.
+ * Banning the primitive outright and making the exceptions explicit is both
+ * simpler and stricter: a genuine local timer costs one allowlist line, and
+ * writing that line is the moment someone asks whether the hook fits.
+ *
+ * `src/hooks/` and `src/lib/` are out of scope — that is where a shared timer
+ * primitive (`useTimeTick`, `useCooldownTick`, the metronome transports, and
+ * `useAutoRefetch` itself) is supposed to live.
+ *
+ * ## What this guard CANNOT see
+ *
+ * It is a source grep, not an AST pass:
+ * - A poll built on `setTimeout` that re-arms itself is invisible.
+ * - A poll moved into a helper module outside the two scanned directories is
+ * invisible (that is also the sanctioned escape hatch, so this is by design).
+ * - `setInterval` written only inside a comment or a string counts.
+ * - It cannot tell an allowlisted file's *sanctioned* interval from a second,
+ * unsanctioned one added to the same file later. Allowlist entries are
+ * therefore meant to stay rare and small.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { existsSync, readFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { trackedSourceFiles } from './test/trackedFiles.js';
+
+const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+// View code only. A shared hook or lib module is where a timer primitive belongs.
+const SCAN_DIRS = ['src/components/', 'src/pages/'];
+
+/**
+ * `\b` keeps `resetInterval(` / `setIntervalPreset(` out, and requiring the
+ * open paren keeps a bare mention of the identifier out. `window.setInterval(`
+ * is intentionally still a match — it is the same timer.
+ */
+const TIMER_CALL = /\bsetInterval\s*\(/;
+
+/**
+ * Files allowed to schedule an interval directly, each with the reason it is
+ * not a data-fetch poll. Adding a row is the point at which to ask whether
+ * `useAutoRefetch` fits instead — a poll that talks to the server does not
+ * belong here.
+ */
+const ALLOWED = {
+ 'src/components/BrailleSpinner.jsx': 'advances the spinner glyph; no I/O',
+ 'src/components/calendar/DayView.jsx': 'moves the "now" line down the day grid; no I/O',
+ 'src/components/cos/tabs/AgentCard.jsx': 'elapsed-time clock tick (the card polls stats via useAutoRefetch)',
+ 'src/components/meatspace/post/PostDrillRunner.jsx': 'drill countdown timer; no I/O',
+ 'src/components/meatspace/post/PostLlmDrillRunner.jsx': 'drill countdown timer; no I/O',
+ 'src/components/meatspace/post/WordplayDrillUI.jsx': 'elapsed-time clock tick; no I/O',
+ 'src/components/music/MusicGenPanel.jsx': 'elapsed-time clock for a running generation (the job itself polls via useAutoRefetch)',
+ 'src/components/sprites/LoopTrimmer.jsx': 'advances the sprite playback frame; no I/O',
+ 'src/components/sprites/WalkWorkflow.jsx': 'counts ticks to self-cancel a stale-queued attach after ~60s — useAutoRefetch does not model a bounded poll',
+ 'src/components/voice/VoiceWidget.jsx': 'samples the in-memory VAD RMS level every 100ms; no I/O',
+ 'src/components/writers-room/ExercisePanel.jsx': 'elapsed-time clock tick; no I/O',
+ 'src/components/writers-room/WorkEditor.jsx': 'elapsed-time clock for the analysis-run banner; no I/O',
+ 'src/pages/Ambient.jsx': 'wall clock; no I/O',
+ 'src/pages/ThreejsModelDetail.jsx': 'bounded in-flight poll pool with a per-tick AbortController — useAutoRefetch does not model either',
+};
+
+const scannedFiles = () => trackedSourceFiles(CLIENT_ROOT)
+ .filter((file) => SCAN_DIRS.some((dir) => file.startsWith(dir)));
+
+const schedulesInterval = (file) => TIMER_CALL.test(readFileSync(join(CLIENT_ROOT, file), 'utf8'));
+
+describe('view polling goes through useAutoRefetch', () => {
+ it('has no hand-rolled setInterval outside the allowlist', () => {
+ const files = scannedFiles();
+ // A broken `git ls-files` (wrong cwd, detached checkout) would otherwise
+ // make this guard pass by scanning nothing at all.
+ expect(files.length).toBeGreaterThan(100);
+
+ const violations = files.filter((file) => !(file in ALLOWED) && schedulesInterval(file));
+
+ expect(
+ violations,
+ 'These view files schedule a raw `setInterval`. If it fetches data, it keeps '
+ + 'hitting the server from a hidden background tab — the exact load #5697 removed.\n'
+ + 'Fix: `useAutoRefetch(fetchFn, intervalMs, { enabled, pollOnly: true })` from '
+ + '`client/src/hooks/useAutoRefetch.js` — it pauses while the tab is hidden and '
+ + 're-fires once on the way back. Keep the site\'s existing gate as `enabled` '
+ + 'rather than an early return, and pass `immediate: false` when another effect '
+ + 'already owns the first fetch.\n'
+ + 'If it is genuinely a local timer (a clock tick, an animation frame advance, a '
+ + 'bounded self-cancelling poll), add it to ALLOWED in this file with a one-line '
+ + 'reason.\n'
+ + `Offenders:\n ${violations.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ // Burn-down: an allowlist entry that no longer needs to be there must go, or
+ // the list quietly becomes a list of files nobody has looked at in a year.
+ it('has no stale allowlist entry', () => {
+ const missing = Object.keys(ALLOWED).filter((file) => !existsSync(join(CLIENT_ROOT, file)));
+ expect(missing, `Allowlisted files that no longer exist:\n ${missing.join('\n ')}`).toEqual([]);
+
+ const noLongerNeeded = Object.keys(ALLOWED).filter((file) => !schedulesInterval(file));
+ expect(
+ noLongerNeeded,
+ 'These files are allowlisted but no longer call `setInterval`. Delete their rows '
+ + `from ALLOWED.\n ${noLongerNeeded.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ it('allowlists only files inside the scanned directories', () => {
+ const outside = Object.keys(ALLOWED).filter((file) => !SCAN_DIRS.some((dir) => file.startsWith(dir)));
+ expect(
+ outside,
+ `These rows can never be reached — the scan only covers ${SCAN_DIRS.join(' and ')}.\n ${outside.join('\n ')}`,
+ ).toEqual([]);
+ });
+
+ // Guards the guard: a detector that stopped recognizing the banned call would
+ // make the scan above vacuously green and let the bug class walk back in.
+ it('recognizes a scheduled interval and nothing that merely looks like one', () => {
+ expect(TIMER_CALL.test('const t = setInterval(refresh, 5000);')).toBe(true);
+ expect(TIMER_CALL.test('const t = setInterval (refresh, 5000);')).toBe(true);
+ expect(TIMER_CALL.test('const t = window.setInterval(refresh, 5000);')).toBe(true);
+
+ expect(TIMER_CALL.test('clearInterval(timer);')).toBe(false);
+ expect(TIMER_CALL.test('resetInterval(timer);')).toBe(false);
+ // A useState setter named for the value it sets, not the timer API.
+ expect(TIMER_CALL.test('setIntervalPreset(p.value);')).toBe(false);
+ // The sanctioned replacement must not read as a violation.
+ expect(TIMER_CALL.test("useAutoRefetch(load, 5000, { pollOnly: true });")).toBe(false);
+ });
+});