Unified prefs writing

This commit is contained in:
patben8 committed 2026-10-03 10:31:32 +02:00
1 parent 957525393b
commit 4e9472c14a
8 files changed
+249 -44

No files matched your search

+17 -2
View File
@@ -533,7 +533,13 @@ Two independent apps that talk over HTTP:
"Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss. "Map by hand…" link to `PathMappingDialog`; no backdrop-click dismiss.
- `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data
dir). Last-opened collection (global AND per-platform), library column dir). Last-opened collection (global AND per-platform), library column
layout, prep-deck zoom, import destination. Best-effort. layout, prep-deck zoom, import destination. Best-effort, but **every
read-modify-write holds `_LOCK` and every write is atomic**
(`paths.write_json`): the UI sends several PATCHes at once on launch, and
unlocked, with a truncating write, a reader caught the file empty and wrote
back only its own key — wiping every pref, the column layout included. A
file that will not parse is moved to `userprefs.json.corrupt`, never
silently overwritten. New helpers that read then write must take the lock.
- `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`. - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`.
- `main.py` — thin FastAPI routes (all under `/api`), talking only to the - `main.py` — thin FastAPI routes (all under `/api`), talking only to the
adapter. Starts **unloaded**; the library is chosen at runtime via adapter. Starts **unloaded**; the library is chosen at runtime via
@@ -842,7 +848,11 @@ Two independent apps that talk over HTTP:
via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against via `GET`/`PATCH /api/prefs` (debounced; hydrated on launch, merged against
defaults so newly-added columns still appear). The prep deck's main-waveform defaults so newly-added columns still appear). The prep deck's main-waveform
zoom persists the same way (`mainZoomSec`, hydrated in `PrepStrip` from the zoom persists the same way (`mainZoomSec`, hydrated in `PrepStrip` from the
shared `['prefs']` query). shared `['prefs']` query). Continuously-changing prefs (columns, zoom,
`beatSize`) are written through ONE debounced writer, `lib/prefs.ts`
(`usePrefsWriter` / `queuePrefs`): changes merge into one PATCH, sent in
order, and the queue outlives unmounts; `QuitGuard` calls `flushPrefs()`
before quitting. Do not give a new pref its own timer.
## Commands ## Commands
@@ -1071,6 +1081,11 @@ serialization path.** It enforces:
as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the as a drive, and that the adapter and the browser share ONE mount scanner. Needs nothing installed: every assertion is about the SHAPE of the
answer, and prefs are redirected to a temp file so a test can never rewrite answer, and prefs are redirected to a temp file so a test can never rewrite
the user's last-opened library. the user's last-opened library.
- `test_prefs.py` — `userprefs.json` under concurrent writes: 200 bursts of
simultaneous patches (plus a reader) keep every key and every patch; the
last-collection and path-mapping helpers lose nothing either; an unreadable
file is moved aside, not overwritten. Against the old unlocked code it fails
on the first trial.
- `test_exports.py` — export sets against a temp copy of the real collection. - `test_exports.py` — export sets against a temp copy of the real collection.
Pins the things that would fail SILENTLY: a live reference picks up a playlist Pins the things that would fail SILENTLY: a live reference picks up a playlist
edited AFTER curation; contents dedupe across playlists and loose tracks; a edited AFTER curation; contents dedupe across playlists and loose tracks; a
+45 -8
View File
@@ -3,10 +3,19 @@
A self-contained JSON file in the app's per-OS user-writable data dir (see A self-contained JSON file in the app's per-OS user-writable data dir (see
``paths.app_data_dir``) so it survives a frozen/packaged build and works the same ``paths.app_data_dir``) so it survives a frozen/packaged build and works the same
on every platform. Best-effort: any I/O error degrades to "no prefs". on every platform. Best-effort: any I/O error degrades to "no prefs".
**Every read-modify-write holds ``_LOCK`` and every write is atomic.** FastAPI
runs ``PATCH /api/prefs`` on a thread pool, and the UI sends several at once on
launch. Unlocked, with ``write_text`` truncating before it wrote, a reader could
catch the file empty, take it for "no prefs" and write back only its own key —
wiping everything else (measured: 249 of 300 trials of three concurrent patches).
A file that exists but will not parse is moved aside before it is replaced, so
it is never silently overwritten.
""" """
from __future__ import annotations from __future__ import annotations
import json import json
import threading
from pathlib import Path from pathlib import Path
from . import paths from . import paths
@@ -16,6 +25,9 @@ from . import paths
_PREFS_PATH = paths.app_data_dir() / "userprefs.json" _PREFS_PATH = paths.app_data_dir() / "userprefs.json"
_LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json" _LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json"
# Reentrant: the helpers below read and write inside one critical section.
_LOCK = threading.RLock()
def _migrate_legacy() -> None: def _migrate_legacy() -> None:
"""One-time: if the new file is absent but a legacy package-relative one """One-time: if the new file is absent but a legacy package-relative one
@@ -27,18 +39,40 @@ def _migrate_legacy() -> None:
pass pass
def load_prefs() -> dict: def _read(*, for_write: bool) -> dict:
"""The stored prefs, or {} if there are none or they cannot be read.
With ``for_write``, a file that exists but is not a JSON object is renamed
to ``userprefs.json.corrupt`` first, since the caller is about to replace it.
"""
try: try:
_migrate_legacy() _migrate_legacy()
data = json.loads(_PREFS_PATH.read_text()) text = _PREFS_PATH.read_text()
return data if isinstance(data, dict) else {} except OSError:
except (OSError, ValueError): return {}
try:
data = json.loads(text)
if isinstance(data, dict):
return data
except ValueError:
pass
if for_write:
try:
_PREFS_PATH.replace(_PREFS_PATH.with_name(_PREFS_PATH.name + ".corrupt"))
except OSError:
pass
return {} return {}
def load_prefs() -> dict:
with _LOCK:
return _read(for_write=False)
def save_prefs(prefs: dict) -> None: def save_prefs(prefs: dict) -> None:
with _LOCK:
try: try:
_PREFS_PATH.write_text(json.dumps(prefs, indent=2)) paths.write_json(_PREFS_PATH, prefs)
except OSError: except OSError:
pass # non-fatal — prefs are a convenience, not a requirement pass # non-fatal — prefs are a convenience, not a requirement
@@ -46,7 +80,8 @@ def save_prefs(prefs: dict) -> None:
def update_prefs(patch: dict) -> dict: def update_prefs(patch: dict) -> dict:
"""Shallow-merge `patch` into the stored prefs and persist. Returns the """Shallow-merge `patch` into the stored prefs and persist. Returns the
full updated prefs dict.""" full updated prefs dict."""
prefs = load_prefs() with _LOCK:
prefs = _read(for_write=True)
prefs.update(patch) prefs.update(patch)
save_prefs(prefs) save_prefs(prefs)
return prefs return prefs
@@ -69,7 +104,8 @@ def set_path_mapping(
collection_path: str, from_prefix: str | None, to_prefix: str | None collection_path: str, from_prefix: str | None, to_prefix: str | None
) -> None: ) -> None:
"""Persist (or, when either prefix is blank, clear) a collection's mapping.""" """Persist (or, when either prefix is blank, clear) a collection's mapping."""
prefs = load_prefs() with _LOCK:
prefs = _read(for_write=True)
mappings = prefs.get("path_mappings") mappings = prefs.get("path_mappings")
if not isinstance(mappings, dict): if not isinstance(mappings, dict):
mappings = {} mappings = {}
@@ -105,7 +141,8 @@ def get_last_collection(platform: str | None = None) -> str | None:
def set_last_collection(path: str, platform: str | None = None) -> None: def set_last_collection(path: str, platform: str | None = None) -> None:
"""Record a library as the last opened, globally and for its platform.""" """Record a library as the last opened, globally and for its platform."""
prefs = load_prefs() with _LOCK:
prefs = _read(for_write=True)
prefs["last_collection"] = path prefs["last_collection"] = path
if platform: if platform:
by_platform = prefs.get("last_collection_by_platform") by_platform = prefs.get("last_collection_by_platform")
+1 -1
View File
@@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")"
source .venv/bin/activate source .venv/bin/activate
fail=0 fail=0
for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_engine_manager.py test_stems_batch.py test_stem_playback.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_onelibrary_fidelity.py test_onelibrary_anlz.py test_onelibrary_pdb.py test_onelibrary_tracks.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_prefs.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
echo "▶ $t" echo "▶ $t"
echo "──────────────────────────────────────────" echo "──────────────────────────────────────────"
+104
View File
@@ -0,0 +1,104 @@
"""userprefs.json under concurrent writes.
The UI sends several `PATCH /api/prefs` at once on launch (column layout, deck
zoom, loop size), and FastAPI runs them on a thread pool. Before the lock and
the atomic write, a reader could catch the file truncated mid-write, take it for
"no prefs" and write back only its own key — the column layout, and with it
every other pref, vanished between sessions (249 of 300 trials of the burst
below lost the other keys). Nothing failed; the app just forgot.
Prefs are redirected to a temp file — a test must never rewrite the user's own.
"""
import tempfile
import threading
from pathlib import Path
from konduktor import prefs
_TMP = tempfile.TemporaryDirectory()
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
failed = False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
if not cond:
failed = True
BASE = {"columns": {"order": ["a", "b"]}, "autoCueTemplate": [1, 2, 3], "beatSize": 4}
PATCHES = [
{"columns": {"order": ["b", "a"]}},
{"mainZoomSec": 16},
{"beatSize": 8},
{"stemDevice": "cpu"},
]
# The launch burst, many times over: every patch lands and nothing else is lost.
TRIALS = 200
bad = []
for i in range(TRIALS):
prefs.save_prefs(BASE)
go = threading.Barrier(len(PATCHES) + 1)
def write(p):
go.wait()
prefs.update_prefs(p)
def read():
go.wait()
for _ in range(20):
if "autoCueTemplate" not in prefs.load_prefs():
bad.append(f"trial {i}: a reader saw no prefs")
return
threads = [threading.Thread(target=write, args=(p,)) for p in PATCHES]
threads.append(threading.Thread(target=read))
for t in threads:
t.start()
for t in threads:
t.join()
got = prefs.load_prefs()
want = {**BASE, **{k: v for p in PATCHES for k, v in p.items()}}
if got != want:
bad.append(f"trial {i}: {got}")
check(f"{TRIALS} concurrent bursts keep every key and every patch", not bad,
bad[0] if bad else "")
# The path-specific helpers share the lock: a burst of them loses nothing either.
prefs.save_prefs({"autoCueTemplate": [1]})
threads = [threading.Thread(target=prefs.set_last_collection, args=(f"/lib/{p}", p))
for p in ("traktor", "rekordbox", "onelibrary")]
threads += [threading.Thread(target=prefs.set_path_mapping, args=(f"/c{n}", "X:", "/Volumes/X"))
for n in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
got = prefs.load_prefs()
check("concurrent last-collection writes keep every platform",
set(got.get("last_collection_by_platform", {})) == {"traktor", "rekordbox", "onelibrary"},
str(got))
check("concurrent path mappings keep every collection",
set(got.get("path_mappings", {})) == {"/c0", "/c1", "/c2"}, str(got))
check("and the unrelated key survives", got.get("autoCueTemplate") == [1])
# A file that will not parse is moved aside, never silently overwritten.
prefs._PREFS_PATH.write_text('{"columns": {"order": ["a"')
check("an unreadable file reads as no prefs", prefs.load_prefs() == {})
check("reading leaves it in place", prefs._PREFS_PATH.read_text().startswith('{"columns"'))
prefs.update_prefs({"beatSize": 2})
corrupt = prefs._PREFS_PATH.with_name("userprefs.json.corrupt")
check("writing over it keeps the old bytes beside it",
corrupt.exists() and corrupt.read_text() == '{"columns": {"order": ["a"')
check("and the new file holds the patch", prefs.load_prefs() == {"beatSize": 2})
check("no temp file is left behind",
not [p for p in Path(_TMP.name).iterdir() if ".tmp" in p.name])
print("\n" + ("❌ FAILED" if failed else "✅ PASSED"))
_TMP.cleanup()
raise SystemExit(1 if failed else 0)
+6 -13
View File
@@ -31,6 +31,7 @@ import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog'
import { ConvertStemsDialog } from './components/ConvertStemsDialog' import { ConvertStemsDialog } from './components/ConvertStemsDialog'
import { StemReportDialog } from './components/StemReportDialog' import { StemReportDialog } from './components/StemReportDialog'
import { Icon } from './lib/icons' import { Icon } from './lib/icons'
import { usePrefsWriter } from './lib/prefs'
function applyFilters(tracks: Track[], f: Filters): Track[] { function applyFilters(tracks: Track[], f: Filters): Track[] {
const q = f.search.trim().toLowerCase() const q = f.search.trim().toLowerCase()
@@ -117,7 +118,7 @@ export default function App() {
const [columnSizing, setColumnSizing] = useState<ColumnSizingState>({}) const [columnSizing, setColumnSizing] = useState<ColumnSizingState>({})
const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const hydratedRef = useRef(false) const hydratedRef = useRef(false)
const saveTimer = useRef<number | null>(null) const writePrefs = usePrefsWriter()
const resetColumns = useCallback(() => { const resetColumns = useCallback(() => {
setColumnVisibility(DEFAULT_COLUMN_VISIBILITY) setColumnVisibility(DEFAULT_COLUMN_VISIBILITY)
@@ -148,22 +149,14 @@ export default function App() {
} }
}, [prefsQuery.data]) }, [prefsQuery.data])
// Persist layout changes (debounced), but not before hydration so we never // Persist layout changes (debounced, via the shared prefs writer), but not
// clobber saved prefs with the initial defaults. // before hydration so we never clobber saved prefs with the initial defaults.
useEffect(() => { useEffect(() => {
if (!hydratedRef.current) return if (!hydratedRef.current) return
if (saveTimer.current) window.clearTimeout(saveTimer.current) writePrefs({
saveTimer.current = window.setTimeout(() => {
api
.patchPrefs({
columns: { visibility: columnVisibility, order: columnOrder, sizing: columnSizing }, columns: { visibility: columnVisibility, order: columnOrder, sizing: columnSizing },
}) })
.catch(() => {}) }, [columnVisibility, columnOrder, columnSizing, writePrefs])
}, 500)
return () => {
if (saveTimer.current) window.clearTimeout(saveTimer.current)
}
}, [columnVisibility, columnOrder, columnSizing])
const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection }) const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection })
const loaded = collection.data?.loaded ?? false const loaded = collection.data?.loaded ?? false
+8 -20
View File
@@ -33,6 +33,7 @@ import { HotcueBar } from './HotcueBar'
import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls' import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls'
import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform' import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform'
import { OverviewWaveform } from './OverviewWaveform' import { OverviewWaveform } from './OverviewWaveform'
import { usePrefsWriter } from '../lib/prefs'
/** Keys that mute stems 1-4 (Shift = solo), by `KeyboardEvent.code`. */ /** Keys that mute stems 1-4 (Shift = solo), by `KeyboardEvent.code`. */
const STEM_KEYS = ['KeyQ', 'KeyW', 'KeyE', 'KeyR'] const STEM_KEYS = ['KeyQ', 'KeyW', 'KeyE', 'KeyR']
@@ -165,11 +166,11 @@ export function PrepStrip({
// Main-waveform zoom persists to userprefs.json so it survives track switches // Main-waveform zoom persists to userprefs.json so it survives track switches
// (MainWaveform unmounts during each load) and app restarts. Hydrate once from // (MainWaveform unmounts during each load) and app restarts. Hydrate once from
// the shared ['prefs'] query, then persist changes debounced (mirrors the // the shared ['prefs'] query, then persist changes through the shared,
// column-layout prefs flow in App). // debounced prefs writer (as App's column layout does).
const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const prefsQuery = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const zoomHydratedRef = useRef(false) const zoomHydratedRef = useRef(false)
const zoomSaveTimer = useRef<number | null>(null) const writePrefs = usePrefsWriter()
useEffect(() => { useEffect(() => {
if (zoomHydratedRef.current || !prefsQuery.data) return if (zoomHydratedRef.current || !prefsQuery.data) return
zoomHydratedRef.current = true zoomHydratedRef.current = true
@@ -180,20 +181,13 @@ export function PrepStrip({
}, [prefsQuery.data]) }, [prefsQuery.data])
useEffect(() => { useEffect(() => {
if (!zoomHydratedRef.current) return // don't clobber saved prefs pre-hydration if (!zoomHydratedRef.current) return // don't clobber saved prefs pre-hydration
if (zoomSaveTimer.current) window.clearTimeout(zoomSaveTimer.current) writePrefs({ mainZoomSec: secPerView })
zoomSaveTimer.current = window.setTimeout(() => { }, [secPerView, writePrefs])
api.patchPrefs({ mainZoomSec: secPerView }).catch(() => {})
}, 500)
return () => {
if (zoomSaveTimer.current) window.clearTimeout(zoomSaveTimer.current)
}
}, [secPerView])
// The loop/jump size persists the same way (survives track switches + // The loop/jump size persists the same way (survives track switches +
// restarts). `beatJumpBeats` is its name from when only beat jump had a size; // restarts). `beatJumpBeats` is its name from when only beat jump had a size;
// it is read once so an upgrade keeps the user's choice. // it is read once so an upgrade keeps the user's choice.
const sizeHydratedRef = useRef(false) const sizeHydratedRef = useRef(false)
const sizeSaveTimer = useRef<number | null>(null)
useEffect(() => { useEffect(() => {
if (sizeHydratedRef.current || !prefsQuery.data) return if (sizeHydratedRef.current || !prefsQuery.data) return
sizeHydratedRef.current = true sizeHydratedRef.current = true
@@ -203,14 +197,8 @@ export function PrepStrip({
}, [prefsQuery.data]) }, [prefsQuery.data])
useEffect(() => { useEffect(() => {
if (!sizeHydratedRef.current) return // don't clobber saved prefs pre-hydration if (!sizeHydratedRef.current) return // don't clobber saved prefs pre-hydration
if (sizeSaveTimer.current) window.clearTimeout(sizeSaveTimer.current) writePrefs({ beatSize })
sizeSaveTimer.current = window.setTimeout(() => { }, [beatSize, writePrefs])
api.patchPrefs({ beatSize }).catch(() => {})
}, 500)
return () => {
if (sizeSaveTimer.current) window.clearTimeout(sizeSaveTimer.current)
}
}, [beatSize])
const getCtx = (): AudioContext => { const getCtx = (): AudioContext => {
if (!audioCtxRef.current) { if (!audioCtxRef.current) {
+3
View File
@@ -2,6 +2,7 @@ import { createPortal } from 'react-dom'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { api } from '../api' import { api } from '../api'
import { flushPrefs } from '../lib/prefs'
/** /**
* Ask before quitting with unsaved changes: Save · Discard · Cancel. * Ask before quitting with unsaved changes: Save · Discard · Cancel.
@@ -46,6 +47,7 @@ export function QuitGuard() {
.then((s) => s.dirty) .then((s) => s.dirty)
.catch(() => false) // no library loaded: nothing to lose .catch(() => false) // no library loaded: nothing to lose
if (!unsaved) { if (!unsaved) {
await flushPrefs(1000)
await invoke('quit_now') await invoke('quit_now')
return return
} }
@@ -73,6 +75,7 @@ export function QuitGuard() {
}, [dirty]) }, [dirty])
const quit = async () => { const quit = async () => {
await flushPrefs(1000) // a layout change made just before quitting still lands
const { invoke } = await import('@tauri-apps/api/core') const { invoke } = await import('@tauri-apps/api/core')
await invoke('quit_now') await invoke('quit_now')
} }
+65
View File
@@ -0,0 +1,65 @@
import { useCallback } from 'react'
import { useQueryClient, type QueryClient } from '@tanstack/react-query'
import { api } from '../api'
/**
* The one debounced writer for prefs that change continuously (column layout,
* deck zoom, loop size).
*
* Each of those used to own a 500 ms timer. All of them hydrate from the same
* ['prefs'] fetch on launch, so their timers fired together and sent several
* PATCHes at once, which is the burst that once wiped userprefs.json (the
* backend now serialises them too). Here every change is merged into one
* pending patch, sent as ONE request after a quiet 500 ms, and requests go out
* strictly in order, so an older response can never overwrite a newer cache.
*
* The queue is module-level, so a component unmounting does not cancel its
* pending write; `flushPrefs()` sends it at once (QuitGuard calls it before
* quitting).
*
* One-off writes from a dialog may still call `api.patchPrefs` directly.
*/
const DEBOUNCE_MS = 500
let pending: Record<string, unknown> = {}
let timer: number | null = null
let client: QueryClient | null = null
let chain: Promise<void> = Promise.resolve()
export function queuePrefs(qc: QueryClient, patch: Record<string, unknown>): void {
client = qc
Object.assign(pending, patch)
if (timer !== null) window.clearTimeout(timer)
timer = window.setTimeout(() => void flushPrefs(), DEBOUNCE_MS)
}
/**
* Send anything queued now. Resolves once every write so far has landed, or
* after `timeoutMs` if given — quitting must not wait on a hung backend.
*/
export function flushPrefs(timeoutMs?: number): Promise<void> {
if (timer !== null) {
window.clearTimeout(timer)
timer = null
}
if (Object.keys(pending).length) {
const patch = pending
pending = {}
chain = chain.then(() =>
api
.patchPrefs(patch)
.then((p) => {
client?.setQueryData(['prefs'], p)
})
.catch(() => {}),
)
}
if (timeoutMs === undefined) return chain
return Promise.race([chain, new Promise<void>((r) => window.setTimeout(r, timeoutMs))])
}
/** `queuePrefs` bound to this tree's QueryClient. */
export function usePrefsWriter(): (patch: Record<string, unknown>) => void {
const qc = useQueryClient()
return useCallback((patch) => queuePrefs(qc, patch), [qc])
}