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
docs: declare API polling an anti-pattern in favor of socket-driven reactive updates
[._.]/ Adam Eivy49b3cef0f19b
diff --git a/AGENTS.md b/AGENTS.mdindex d5a64a9180..de239b29ca 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -193,6 +193,7 @@ This complements the Security Model (the deployed product) — this section gove- **Selection lives in the URL, never in local state** — any view that opens/selects a specific record encodes it as a route param, so it's shareable, bookmarkable, and reachable from ⌘K and voice. Full contract in `client/src/AGENTS.md`.- **Client UI conventions** (`client/src/AGENTS.md`) — no `alert`/`confirm`, `htmlFor`/`id` label pairing, mobile responsive, above the fold, no hardcoded localhost, alphabetical nav, user-facing number formatting, reactive local-state updates after mutations, silent-vs-toasting API errors, save gating for "Run Now" actions, and the shared tabbed `Drawer` convention.- **Server conventions** (`server/AGENTS.md`) — schema parity when adding fields, serializing async PATCH races on shared records, batching high-frequency state writes, peer fan-out in record-creating tests, backup exclude anchoring, and stage-prompt template migrations.+- **Push, don't poll** — API polling for refreshing content/data is an anti-pattern. The server emits a Socket.IO event when data changes and the UI reacts immediately (own mutations apply the response to local state at once); never re-fetch on a timer or hang waiting for one. A missing event gets added on the server, not papered over with a client poll. Contract and the narrow exceptions: [Realtime updates, not polling](docs/UX_DESIGN_GUIDE.md#realtime-updates-not-polling).- **Socket-driven UI** — read [.claude/skills/portos-socket-ui/SKILL.md](.claude/skills/portos-socket-ui/SKILL.md) before wiring or debugging a socket-driven view.- **Single-line logging** — emoji prefixes and string interpolation; never log full JSON blobs or arrays.```jsdiff --git a/client/src/AGENTS.md b/client/src/AGENTS.mdindex 17d529f12d..7d0bd0df34 100644--- a/client/src/AGENTS.md+++ b/client/src/AGENTS.md@@ -24,7 +24,8 @@ These apply to React/Vite client code. Universal constraints (functional program- **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.- **A control that appears in response to a key-submit is never `autoFocus`ed** - the Enter that submitted is still down when the new control mounts and takes focus, so the browser activates it off that same keystroke (its keypress/keyup, or the first auto-repeat) and the thing it was meant to reveal is gone in the tick it appeared. This is not a flicker nit: a Morse copy round showed a right/wrong verdict per question that no user ever saw, so a two-character drill stayed a coin flip. Keep the submitting element focused (`readOnly`, not `disabled` — disabled drops focus) and filter `e.repeat` in its handler, or put Enter-to-advance in a window handler gated on `shouldIgnoreGlobalKey` (which drops auto-repeat for you) and leave the button unfocused. `MorseTrainer.jsx` takes the first shape, `PostDrillRunner.jsx` the second; a verdict gated behind a network round-trip is latent only, because Enter is long released by then.- **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).+- **API polling is an anti-pattern — push, don't poll.** Fetch once, then update from Socket.IO events (`useSocketSubscription`, the media-job hooks) and apply your own mutation's response to local state immediately; never re-fetch on a timer or spin waiting for one. A change with no event gets a server emit (declared in `server/lib/socketEventContracts.js`), not a client poll. Contract and the narrow exceptions (hardware telemetry, external systems with no callback, PortOS self-restart): [Realtime updates, not polling](../../docs/UX_DESIGN_GUIDE.md#realtime-updates-not-polling).+- **A sanctioned poll 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).- **No local binding shadows a timer or `fetch`** - a `useState` pair, `useCallback`, or `const` named `setInterval` / `setTimeout` / `clearInterval` / `clearTimeout` / `requestAnimationFrame` / `cancelAnimationFrame` / `fetch` shadows that global for the whole component body, so a timer or fetch added to the same scope later silently calls the local instead — no throw, no lint error, just a state setter that stores a callback (#5728). Name the binding for what it holds (`intervalPreset`, `timeoutMinutes`, `loadRefs`). Enforced tree-wide by `client/src/globalShadowConventions.test.js`, which has no allowlist; idiomatic React state like `[open, setOpen]` / `[status, setStatus]` is deliberately out of scope because nothing here calls those globals bare.- **An async effect keyed to a switchable identity drops a superseded response** - an effect that fetches on a dependency and writes the answer into state needs a disposal guard: `let active = true;` at the top, every `set*` gated on it, `return () => { active = false; };`. Without it, switching the record faster than the request resolves renders the previous record's data under the current one — and it does not self-correct where the value is passed down as a controlled prop, so `WorkEditor` enriched one work's persisted storyboard images with another's characters and places (#7242, after #6996–#7000 were each fixed as a single site). **`useMounted()` does not cover this** — the component never unmounted, only its subject changed. Where the response must be matched against the newest request rather than merely dropped — notably when the effect writes a state value that is itself in its own dependency array, so a lifetime-scoped flag would be flipped by its own cleanup — bump and compare a generation ref instead (`IngredientPicker.jsx`). Enforced tree-wide by `client/src/asyncEffectDisposalConventions.test.js`, which allowlists the few deps that cannot select a different record (a drawer `open` flag, a once-only latch).- **User-facing counts and amounts go through `formatCount` / `formatUsd`** (`utils/formatters.js`) — thousands-grouped and en-US-pinned (`2,762`, `$4,610.09`). An unseparated `4610` is read at the wrong order of magnitude, and a bare `.toLocaleString()` follows the browser locale, which then disagrees with the `$` beside it. A **measured** zero already renders `0`; `formatCount` gives `—` only for a value that is missing or unparseable, so pass `{ fallback: '0' }` just where an ABSENT count should still read as zero. Enforced tree-wide by `client/src/numberFormattingConventions.test.js` — any new bare `.toLocaleString(` call under `client/src` fails CI. Other formatters (`formatBytes`, `timeAgo`, …) live beside them — see the helper catalog in the root `AGENTS.md`.diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex eaa1c1c112..60f05ccd3d 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -109,7 +109,7 @@ grep -i "what you want to do" client/src/hooks/README.md|---|---|---|| `useAnchorReveal` | `useAnchorReveal(getTarget, key, { reveal? })` — scroll a freshly-opened element into view + flash a tint over it; re-fires when `key` changes; no-op when `key` is falsy or `getTarget()` is null. | Reveal an editorial finding's anchored manuscript text on open / prev-next step (#1601). || `useArmedAction` | Two-click-arm `[armed, fire]` confirmation. | Destructive button needing a confirm tap. (Project memory: user finds this less discoverable — prefer inline confirm rows for new UI.) |-| `useAutoRefetch` | Poll-based refetch on an interval, single-flight per instance (ticks during a pending fetch are dropped; mid-flight `refetch()` calls share one trailing fetch). `{ pollOnly: true }` skips internal data/loading state for side-effect-only callers (returns `{ refetch }` only). | Data needs periodic refresh (no socket / SSE available). |+| `useAutoRefetch` | Poll-based refetch on an interval, single-flight per instance (ticks during a pending fetch are dropped; mid-flight `refetch()` calls share one trailing fetch). `{ pollOnly: true }` skips internal data/loading state for side-effect-only callers (returns `{ refetch }` only). | Only a sanctioned poll — a source that cannot push (hardware telemetry, an external system with no callback). Polling is an anti-pattern: prefer a socket event, adding the server emit if it is missing. || `useSystemActivity` | One shared bounded system-activity snapshot. Socket invalidation coalesces to a single read; reconnect and reshow reconcile missed frames. A failed read stays unknown, never idle. | Update banner and the live-activity widget. GPU samples stay on a visible-only poll — they have no event. || `useAutoSizeTextarea` | `[ref, resize]` — grows a `<textarea>` to fit its content (no scroll / hand-resize); recomputes before paint on value change. | A textarea that should auto-fit content. Prefer the `AutoSizeTextarea` UI component, which wraps this. || `useChartColors` | Resolves the `--port-*` theme tokens (accent/success/warning/error, `chart-1..4`, grid, axis, tooltip surfaces) to concrete `rgb()` strings via `getComputedStyle`, re-resolving on theme switch. | A recharts card needs theme-following colors — SVG `fill`/`stroke` props can't read CSS vars, so pass these resolved strings instead of hardcoded hex. |diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.jsindex ec1ae3e230..d156554bd7 100644--- a/client/src/hooks/useAutoRefetch.js+++ b/client/src/hooks/useAutoRefetch.js@@ -6,6 +6,12 @@ import { useVisibilityEvent } from './useVisibilityEvent.js';* once when it becomes visible again. Replaces the per-component* useEffect + setInterval pattern for data-fetch polling.*+ * Polling is an anti-pattern in PortOS: data should arrive via Socket.IO+ * events and own mutations should update local state from their response.+ * Reach for this hook only for a source that cannot push (hardware telemetry,+ * an external system with no callback) — see "Realtime updates, not polling"+ * in docs/UX_DESIGN_GUIDE.md.+ ** The hook catches whatever `fetchFn` throws, warns, and keeps the prior* `data` untouched — so data-path callers (those reading the returned `data`)* should NOT swallow errors with `.catch(() => null)`. Returning `null` herediff --git a/client/src/pollingConventions.test.js b/client/src/pollingConventions.test.jsindex 61a7303d85..a3b8a6f4ca 100644--- a/client/src/pollingConventions.test.js+++ b/client/src/pollingConventions.test.js@@ -56,9 +56,10 @@ 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.+ * not a data-fetch poll. Adding a row is the point at which to ask whether a+ * socket event fits instead — a poll that talks to the server does not belong+ * here, and polling is an anti-pattern even through `useAutoRefetch` (see+ * "Realtime updates, not polling" in docs/UX_DESIGN_GUIDE.md).*/const ALLOWED = {'src/components/BrailleSpinner.jsx': 'advances the spinner glyph; no I/O',diff --git a/docs/UX_DESIGN_GUIDE.md b/docs/UX_DESIGN_GUIDE.mdindex d8a38e68bc..8bd6992402 100644--- a/docs/UX_DESIGN_GUIDE.md+++ b/docs/UX_DESIGN_GUIDE.md@@ -254,6 +254,19 @@ The page families, spacing, navigation grouping, and pilot choices are PortOS deDeleting an item keeps the populated list and its scroll container mounted. After server success, use `CollapsibleListItem` to fade and collapse the row, including its spacing, so following content slides up; remove the record locally on exit. Preserve search, filters, pagination and unrelated selection. Refresh summary counts separately. Keep failed deletions visible and actionable, prevent duplicate pending requests, honor reduced motion, and transfer keyboard focus without scrolling. Never show a whole-list loading placeholder as deletion feedback. Brain MemoryTab is the reference implementation across Memories, People, Projects, Ideas and Admin.+## Realtime updates, not polling++API polling is an anti-pattern in PortOS. Data on screen stays current because the server **pushes** changes over Socket.IO (or a job's SSE stream) and the UI **reacts immediately** — not because a timer re-fetches it every N seconds. Polling wastes server work (several PortOS polls fan out to `pm2 jlist`, Ollama, git, or peer HTTP hops on every tick), keeps background tabs on other tailnet machines busy, and still shows stale state for up to one interval.++- **Own mutations update the UI from the response.** After a create/update/delete succeeds, apply the returned record (or the known change) to local state at once. Never follow a mutation with "wait for the next poll", a fixed `setTimeout` refetch, or a spinner that clears only when a timer notices the change.+- **Everyone else's changes arrive as events.** Background jobs, agents, schedulers, peers, and other tabs emit a Socket.IO event when they change a record (`<domain>:changed`, `<record>:upserted`, `<job>:progress` / `:completed`). Subscribe through `useSocketSubscription` / `useSocket` or the media-job hooks, then patch the affected record or re-read just that resource.+- **Missing event? Add it on the server.** If the change has no event today, emit one from the service that performs it and declare its payload in `server/lib/socketEventContracts.js`. A client-side poll is not an acceptable substitute for a missing emit.+- **Recover, don't poll, for gaps.** Reconcile with one fetch on socket reconnect and when the tab becomes visible again; that covers events missed while disconnected without a recurring timer.+- **Long-running work streams progress.** Renders, imports, installs, and agent runs report progress and completion over their socket/SSE channel (`useMediaJobProgress`, `useSseProgress`, `usePipelineProgress`). Do not poll a job-status endpoint until it reports `completed`.+- **Sanctioned exceptions** are sources that genuinely cannot push: sampled hardware telemetry for a visible inspector (GPU utilization), an external system that offers no callback, and PortOS restarting itself (the socket is down, so `usePortosRestartWatch` probes health). These use `useAutoRefetch` (visibility-gated, single-flight), run only while their consumer is open, and carry a one-line justification at the call site. `client/src/pollingConventions.test.js` bans raw `setInterval` in views; routing a new data poll through `useAutoRefetch` does not by itself make it acceptable.++Existing polls are being migrated to socket events incrementally, tracked by [#8531](https://github.com/atomantic/PortOS/issues/8531), [#8532](https://github.com/atomantic/PortOS/issues/8532), [#8533](https://github.com/atomantic/PortOS/issues/8533), [#8534](https://github.com/atomantic/PortOS/issues/8534), [#8530](https://github.com/atomantic/PortOS/issues/8530), [#8535](https://github.com/atomantic/PortOS/issues/8535), [#8536](https://github.com/atomantic/PortOS/issues/8536), [#8517](https://github.com/atomantic/PortOS/issues/8517). Don't copy an existing poll as precedent for new code.+## Large collections and incremental loadingA growing collection must remain usable with hundreds, thousands, or more records. This applies to Brain inbox and memory, CoS tasks/agents, media and image history, and any new collection surface.