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
refactor: extract the triplicated URL search-param patch helper into useUrlParams (#3313)
[._.]/ Adam Eivy1226e7cc1708
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6ac9123762..a5202572f8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -133,3 +133,7 @@## UI Consistency- **[issue-3293] Sprite approve/lock confirmations, the near-black canvases, and the final music-video player now follow the shared conventions.** The shared `ConfirmButtonPair` had no positive tone, so the "Approve this walk" and "Freeze this reference version" confirmations in the sprite workflows hand-rolled their own confirm/cancel markup and each drifted on busy text, spinner, and touch-target height; a `success` tone closes that gap and five hand-rolled pairs now share one implementation, with a 36px minimum height on every pair in the app. The four piano-roll/ambient surfaces that hardcoded a near-black hex now say why they don't follow the theme — the rolls read their background from the same `ROLL_BG` constant their canvas paints with, so the CSS fallback can never drift from the painted pixels, and Ambient mode is explicitly `bg-black` because its white-on-black layers would be unreadable under a day theme. The rendered music video also reserves its 16:9 box like the scene thumbnails already do, so the Download row above it stops jumping when the video's dimensions resolve.++## Internal++- **[issue-3313] The URL search-param patch helper is now one hook instead of three copies.** `updateParams(patch, { replace })` — merge a patch into the query string, dropping keys set to empty so a cleared filter leaves the URL clean — had been re-typed into Catalog, Media Collections, and (in a narrower single-key form) the 3D page. It now lives in `useUrlParams`, which reads the live params off a ref because react-router's functional updater hands the callback the params captured at the render that memoized it — a debounced `?q=` write armed before a sort change would otherwise navigate with the pre-change snapshot and silently drop the sort the user just picked. The hook is also referentially stable, so the debounce effects on those pages stop re-arming every time an unrelated param changes.diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex b16f2b61fb..a19aa05be6 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -111,6 +111,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `usePopoverPosition` | Viewport-clamped `{ left, top, width }` for a fixed-position portal popover anchored to a trigger; re-measures on open and rAF-coalesced on capture-phase scroll/resize. Returns `{ triggerRef, popoverRef, style, reposition }`; pass `anchorRef` to follow a parent-owned trigger. | Any portal-into-`<body>` menu/popover placed relative to a button (ThemeSwitcher, CollectionPickerShell) — use this instead of re-rolling the measure/flip/clamp/reflow plumbing. || `useScrollLock` | Body-scroll lock with ref-count. | Modals, drawers, lightboxes. || `useSwipeNav` | Horizontal swipe prev/next. | Mobile swipe between siblings. |+| `useUrlParams` | `[searchParams, updateParams]` — `updateParams(patch, { replace })` merges a patch into the query string and deletes keys set to `null`/`undefined`/`''` so a cleared filter leaves the URL clean. Reads the live params off a ref (react-router's functional updater is closure-stale) and is referentially stable. | Any page whose filter/sort/selection state lives in the URL (Catalog, MediaCollections, Media3D) — don't re-roll the merge-and-prune loop. || `useValidTab` | Resolve the active tab from the `:tab` URL param against a TABS list, falling back to a default on invalid/missing. | Any tabbed page whose tab lives in the URL — don't re-roll the `new Set(TABS.map(...))` guard. || `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. || `useAutoscroll` | rAF autoscroll for a scrollable container: advances `scrollTop` by `pxPerSec`, auto-stops at the bottom, pauses on user wheel/touchmove, live speed changes via ref. Returns `{ playing, toggle, stop, pxPerSec, setPxPerSec }`. | SongBook play view; any teleprompter-style surface. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 7ad7c5c34d..54106a7571 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -132,6 +132,7 @@ export * from './useKeyboardHelp.js';export * from './useLockToggle.js';export * from './useScrollLock.js';export * from './useSwipeNav.js';+export { default as useUrlParams } from './useUrlParams.js';export * from './useValidTab.js';// === Storage & persistence ===diff --git a/client/src/hooks/useUrlParams.js b/client/src/hooks/useUrlParams.jsnew file mode 100644index 0000000000..4d348ee01e--- /dev/null+++ b/client/src/hooks/useUrlParams.js@@ -0,0 +1,44 @@+import { useCallback, useRef } from 'react';+import { useSearchParams } from 'react-router-dom';++// URL-synced filter/selection state: `[searchParams, updateParams]`, where+// `updateParams(patch, { replace })` merges a patch into the current query+// string and DELETES any key whose value is `null` / `undefined` / `''`, so a+// cleared filter leaves the URL clean instead of trailing `?type=&tag=`.+// `replace` avoids history spam while typing (debounced mirrors); discrete+// clicks push so Back returns to the prior filter.+//+// Only those three values clear a key — `false` and `0` are written through as+// `"false"` / `"0"`, because a falsy-but-meaningful value is a legitimate+// filter state and must not vanish from a shared link.+//+// The sibling of `useDrawerTab` (single named param, tab-shaped) for the+// multi-param case: this is the plumbing behind "the URL is the source of truth+// for what's filtered/selected".+export default function useUrlParams() {+ const [searchParams, setSearchParams] = useSearchParams();++ // react-router's functional `setSearchParams` updater is NOT latest-state: it+ // hands the callback `new URLSearchParams(searchParams)` captured in the+ // closure of the render that memoized the setter. A debounced write armed+ // before a sort/toggle change would therefore navigate with the pre-change+ // snapshot and silently drop the param the user just set. Read the live+ // params — and the live setter — off refs instead. That also keeps+ // `updateParams` referentially stable, so effects that list it as a+ // dependency don't re-arm every time any unrelated query param changes.+ const paramsRef = useRef(searchParams);+ paramsRef.current = searchParams;+ const setParamsRef = useRef(setSearchParams);+ setParamsRef.current = setSearchParams;++ const updateParams = useCallback((patch, { replace = false } = {}) => {+ const next = new URLSearchParams(paramsRef.current);+ for (const [k, v] of Object.entries(patch)) {+ if (v == null || v === '') next.delete(k);+ else next.set(k, v);+ }+ setParamsRef.current(next, { replace });+ }, []);++ return [searchParams, updateParams];+}diff --git a/client/src/hooks/useUrlParams.test.jsx b/client/src/hooks/useUrlParams.test.jsxnew file mode 100644index 0000000000..250d4bd1ee--- /dev/null+++ b/client/src/hooks/useUrlParams.test.jsx@@ -0,0 +1,119 @@+import { describe, it, expect } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom';+import useUrlParams from './useUrlParams';++// MemoryRouter so `useSearchParams` resolves; `useLocation` lets the assertions+// read back the resulting URL — the deep-link contract this hook defines —+// and `useNavigate` lets the push-vs-replace test walk the history stack.+const renderWithRouter = (initial = '/x') => {+ const wrapper = ({ children }) => (+ <MemoryRouter initialEntries={[initial]}>{children}</MemoryRouter>+ );+ return renderHook(() => ({+ pair: useUrlParams(),+ location: useLocation(),+ navigate: useNavigate(),+ }), { wrapper });+};++const params = (result) => new URLSearchParams(result.current.location.search);++describe('useUrlParams', () => {+ it('exposes the current search params', () => {+ const { result } = renderWithRouter('/x?type=character&q=hi');+ expect(result.current.pair[0].get('type')).toBe('character');+ expect(result.current.pair[0].get('q')).toBe('hi');+ });++ it('writes a patched key into the URL', () => {+ const { result } = renderWithRouter();+ act(() => result.current.pair[1]({ type: 'place' }));+ expect(params(result).get('type')).toBe('place');+ });++ it('merges the patch, preserving unrelated params', () => {+ const { result } = renderWithRouter('/x?universe=u1&view=albums');+ act(() => result.current.pair[1]({ type: 'place' }));+ const p = params(result);+ expect(p.get('universe')).toBe('u1');+ expect(p.get('view')).toBe('albums');+ expect(p.get('type')).toBe('place');+ });++ it("deletes keys patched to '' so a cleared filter leaves the URL clean", () => {+ const { result } = renderWithRouter('/x?type=place&tag=t1');+ act(() => result.current.pair[1]({ type: '' }));+ const p = params(result);+ expect(p.has('type')).toBe(false);+ expect(p.get('tag')).toBe('t1');+ });++ it('deletes keys patched to null or undefined', () => {+ const { result } = renderWithRouter('/x?a=1&b=2&c=3');+ act(() => result.current.pair[1]({ a: null, b: undefined }));+ const p = params(result);+ expect(p.has('a')).toBe(false);+ expect(p.has('b')).toBe(false);+ expect(p.get('c')).toBe('3');+ });++ it('clears every key of a multi-key reset patch at once', () => {+ const { result } = renderWithRouter('/x?type=a&universe=b&series=c&tag=d&q=e&view=albums');+ act(() => result.current.pair[1]({ type: '', universe: '', series: '', tag: '', q: '' }));+ const p = params(result);+ expect([...p.keys()]).toEqual(['view']);+ });++ it('writes falsy-but-meaningful values instead of clearing them', () => {+ // Only null/undefined/'' clear — `false` and `0` are legitimate filter+ // states and must survive into a shared link.+ const { result } = renderWithRouter();+ act(() => result.current.pair[1]({ flag: false, page: 0 }));+ const p = params(result);+ expect(p.get('flag')).toBe('false');+ expect(p.get('page')).toBe('0');+ });++ it('pushes by default so Back returns to the prior filter', () => {+ const { result } = renderWithRouter();+ act(() => result.current.pair[1]({ a: '1' }));+ act(() => result.current.pair[1]({ b: '2' }));+ act(() => result.current.navigate(-1));+ expect(result.current.location.search).toBe('?a=1');+ });++ it('replaces when asked so debounced mirrors do not spam history', () => {+ const { result } = renderWithRouter();+ act(() => result.current.pair[1]({ a: '1' }));+ act(() => result.current.pair[1]({ b: '2' }, { replace: true }));+ expect(params(result).get('b')).toBe('2');+ // The replace landed on top of the push, so one Back step reaches the+ // pristine URL rather than `?a=1&b=2`'s predecessor.+ act(() => result.current.navigate(-1));+ expect(result.current.location.search).toBe('');+ });++ it('keeps updateParams referentially stable across param changes', () => {+ // Effects that list `updateParams` as a dependency (the debounced `?q=`+ // mirrors in Catalog/MediaCollections) must not re-arm every time an+ // unrelated param changes.+ const { result } = renderWithRouter();+ const first = result.current.pair[1];+ act(() => first({ type: 'place' }));+ expect(result.current.pair[1]).toBe(first);+ });++ it('reads the live params, not the render-time snapshot, from a stale callback', () => {+ // react-router's functional `setSearchParams` updater closes over the+ // params of the render that memoized it. A debounced write armed before an+ // unrelated change would drop that change; this hook must not.+ const { result } = renderWithRouter();+ const stale = result.current.pair[1]; // captured before any navigation+ act(() => result.current.pair[1]({ sort: 'newest' }));+ act(() => stale({ q: 'hello' }));+ const p = params(result);+ expect(p.get('sort')).toBe('newest');+ expect(p.get('q')).toBe('hello');+ });+});diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsxindex 0c296c074e..5676064de2 100644--- a/client/src/pages/Catalog.jsx+++ b/client/src/pages/Catalog.jsx@@ -15,7 +15,7 @@*/import { useState, useEffect, useCallback, useMemo, useRef } from 'react';-import { Link, useNavigate, useSearchParams } from 'react-router-dom';+import { Link, useNavigate } from 'react-router-dom';import { Sparkles, Plus, Search, FileInput, Loader2, RefreshCw, Wand2, X, LayoutGrid, Library, FolderPlus } from 'lucide-react';import toast from '../components/ui/Toast';import {@@ -33,6 +33,7 @@ import CatalogCard from '../components/catalog/CatalogCard';import CatalogAlbum from '../components/catalog/CatalogAlbum';import { catalogRefRoleForType } from '../lib/catalogTypes';import { useCatalogTypes } from '../hooks/useCatalogTypes.jsx';+import useUrlParams from '../hooks/useUrlParams';// All type-derived UI (chips, badge color, inline-form primary content// key/label, snippet fallback) flows from the merged registry (system +@@ -61,27 +62,15 @@ export default function Catalog() {const { types: TYPES, getType } = useCatalogTypes();// ── URL-synced filter state (linkable routes per CLAUDE.md) ────────────────- const [searchParams, setSearchParams] = useSearchParams();+ // `updateParams` merges a patch and drops keys set to '' so a cleared filter+ // leaves the URL clean; `replace` avoids history spam while typing.+ const [searchParams, updateParams] = useUrlParams();const selectedType = searchParams.get('type') || '';const selectedUniverse = searchParams.get('universe') || '';const selectedSeries = searchParams.get('series') || '';const selectedTag = searchParams.get('tag') || '';const view = searchParams.get('view') === 'albums' ? 'albums' : 'grid';- // Merge a patch into the URL search params, dropping keys set to '' so a- // cleared filter leaves the URL clean. `replace` avoids history spam while- // typing; discrete clicks push so Back returns to the prior filter.- const updateParams = useCallback((patch, { replace = false } = {}) => {- setSearchParams((prev) => {- const next = new URLSearchParams(prev);- for (const [k, v] of Object.entries(patch)) {- if (v == null || v === '') next.delete(k);- else next.set(k, v);- }- return next;- }, { replace });- }, [setSearchParams]);-// Two-stage search: `searchInput` is what the user is typing; `q` is the// debounced value that drives the list fetch (and is mirrored to the URL).// Seeded from the URL once so a shared/reloaded `?q=` link restores the box.diff --git a/client/src/pages/Media3D.jsx b/client/src/pages/Media3D.jsxindex ff4f01f6e2..1367005c63 100644--- a/client/src/pages/Media3D.jsx+++ b/client/src/pages/Media3D.jsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useState } from 'react';-import { Link, useSearchParams } from 'react-router-dom';+import { Link } from 'react-router-dom';import { Boxes, CheckCircle2, Download, AlertTriangle, Loader2, ExternalLink, ImagePlus, Sparkles, KeyRound } from 'lucide-react';import { getImageTo3dTargets, createImageTo3dModel, getImageTo3dModel, listImageTo3dModels } from '../services/api';import { useAutoRefetch } from '../hooks/useAutoRefetch';@@ -10,6 +10,7 @@ import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';import GlbViewer from '../components/media/GlbViewer';import HfTokenBanner, { GatedModelList, HF_SOURCE_LABEL } from '../components/imageGen/HfTokenBanner';import { useHfTokenStatus } from '../hooks/useHfTokenStatus';+import useUrlParams from '../hooks/useUrlParams';import MediaImage from '../components/MediaImage';import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';@@ -179,7 +180,7 @@ function TargetCard({ target, onInstall }) {}export default function Media3D() {- const [searchParams, setSearchParams] = useSearchParams();+ const [searchParams, updateParams] = useUrlParams();// URL is the source of truth for what's open: the source image, the chosen// target, and (once the runner lands #2952) the generated mesh to preview.const imageFromRoute = searchParams.get('image') || '';@@ -250,27 +251,16 @@ export default function Media3D() {}, [targets, targetFromRoute]);// Keep the URL honest: if a bare `/3d` resolved a default target, reflect- // it so the selection is shareable/reload-safe (URL as source of truth). The- // functional updater reads the freshest params, so this effect depends only on- // the resolved target — not on every unrelated `?image=`/`?glb=` change.+ // it so the selection is shareable/reload-safe (URL as source of truth).+ // `updateParams` reads the freshest params off a ref and is referentially+ // stable, so this effect depends only on the resolved target — not on every+ // unrelated `?image=`/`?glb=` change.useEffect(() => {if (!selectedTarget || targetFromRoute === selectedTarget.id) return;- setSearchParams((prev) => {- const next = new URLSearchParams(prev);- next.set('target', selectedTarget.id);- return next;- }, { replace: true });- }, [selectedTarget, targetFromRoute, setSearchParams]);-- const setParam = useCallback((key, value) => {- setSearchParams((prev) => {- const next = new URLSearchParams(prev);- if (value) next.set(key, value); else next.delete(key);- return next;- });- }, [setSearchParams]);+ updateParams({ target: selectedTarget.id }, { replace: true });+ }, [selectedTarget, targetFromRoute, updateParams]);- const handlePick = (item) => { setParam('image', item.filename); setPickerOpen(false); };+ const handlePick = (item) => { updateParams({ image: item.filename }); setPickerOpen(false); };// One poll tick against the in-flight record. Let a transient GET *throw* so// useAutoRefetch logs and retries next tick — a multi-minute render must not be@@ -287,20 +277,20 @@ export default function Media3D() {// the fresh row, so re-fetching the whole list would be wasted I/O (the// repo's reactive-update convention).if (model.status === 'ready' && model.assetPath) {- setGenPercent(100); setParam('glb', model.assetPath); setGenerating(false); patchRecord(model);+ setGenPercent(100); updateParams({ glb: model.assetPath }); setGenerating(false); patchRecord(model);} else if (model.status === 'failed' || model.status === 'canceled') {// model.error carries the runner's actionable message (e.g. the HF-auth guidance).setGenError(model.error || 'The render did not finish.'); setGenerating(false); patchRecord(model);}// else still draft/generating → the hook re-polls after POLL_INTERVAL_MS.- }, [modelId, setParam, mountedRef, patchRecord]);+ }, [modelId, updateParams, mountedRef, patchRecord]);useAutoRefetch(pollTick, POLL_INTERVAL_MS, { pollOnly: true, enabled: generating && !!modelId });const handleGenerate = useCallback(async () => {if (!selectedImage || !selectedTarget) return;setGenError(null); setGenPercent(0); setModelId(null);- setParam('glb', ''); // clear any previously-previewed mesh+ updateParams({ glb: '' }); // clear any previously-previewed meshconst created = await createImageTo3dModel({ name: nameFromImageFilename(selectedImage.filename), filename: selectedImage.filename, target: selectedTarget.id },{ silent: true },@@ -309,7 +299,7 @@ export default function Media3D() {return null;});if (created && mountedRef.current) { setModelId(created.id); setGenerating(true); patchRecord(created); }- }, [selectedImage, selectedTarget, setParam, mountedRef, patchRecord]);+ }, [selectedImage, selectedTarget, updateParams, mountedRef, patchRecord]);// Why the Generate action is blocked, or null when it's ready to run. The runner// (POST create → on-device render → landed .glb) is wired, so the terminal state@@ -378,7 +368,7 @@ export default function Media3D() {<buttonkey={t.id}type="button"- onClick={() => setParam('target', t.id)}+ onClick={() => updateParams({ target: t.id })}className={`rounded-lg border px-3 py-1.5 text-xs ${active? 'border-port-accent bg-port-accent/10 text-white': 'border-port-border bg-port-bg text-gray-300 hover:border-port-accent'}`}diff --git a/client/src/pages/MediaCollections.jsx b/client/src/pages/MediaCollections.jsxindex 896c83eff7..a5f4f16731 100644--- a/client/src/pages/MediaCollections.jsx+++ b/client/src/pages/MediaCollections.jsx@@ -1,5 +1,5 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Link, useNavigate, useSearchParams } from 'react-router-dom';+import { useEffect, useMemo, useState } from 'react';+import { Link, useNavigate } from 'react-router-dom';import { Plus, FolderOpen, Inbox, Trash2, Image as ImageIcon, Film, Search } from 'lucide-react';import toast from '../components/ui/Toast';import {@@ -15,6 +15,7 @@ import { middleTruncate } from '../utils/formatters';import MediaImage from '../components/MediaImage';import SyncBadge from '../components/sync/SyncBadge';import { useSyncIntegrity, syncBadgeStatus } from '../hooks/useSyncIntegrity';+import useUrlParams from '../hooks/useUrlParams';// Cap for the card title AFTER the auto-creator prefix moves to its badge.// Middle-truncating at this length keeps the trailing date/qualifier — the only@@ -62,7 +63,7 @@ const resolveCover = (collection, imagesByName, videosById) => {export default function MediaCollections() {const navigate = useNavigate();- const [searchParams, setSearchParams] = useSearchParams();+ const [searchParams, updateParams] = useUrlParams();const [collections, setCollections] = useState([]);const [loading, setLoading] = useState(true);const [creating, setCreating] = useState(false);@@ -157,22 +158,6 @@ export default function MediaCollections() {const sort = normalizeCollectionSort(searchParams.get('sort'));const hideEmpty = searchParams.get('empty') !== '1';- // react-router's functional `setSearchParams` updater is NOT latest-state: it- // hands back the params captured in the closure at render time. A debounced- // write armed before a sort/toggle change would therefore navigate with the- // pre-change snapshot and silently drop the param the user just set. Read the- // live params off a ref instead.- const paramsRef = useRef(searchParams);- paramsRef.current = searchParams;- const updateParams = useCallback((patch, { replace = false } = {}) => {- const next = new URLSearchParams(paramsRef.current);- for (const [k, v] of Object.entries(patch)) {- if (v == null || v === '') next.delete(k);- else next.set(k, v);- }- setSearchParams(next, { replace });- }, [setSearchParams]);-// Two-stage search (same shape as Catalog): `query` is what the user is// typing and drives the client-side filter instantly; `mirroredQuery` is the// debounced copy written to the URL, so a shareable `?q=` doesn't cost a