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: add a shared client sleep helper and delegate useLocalStorageBool to safeStorage (#2846)
[._.]/ Adam Eivya46aad19d55e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fea506d20f..82d073f5a7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -65,3 +65,4 @@- **[issue-2845] Standardize the `loraTraining` sample 404 error envelope** — new `sendErrorResponse`/`buildErrorEnvelope` helpers in `server/lib/errorHandler.js` build the shared `{ error, code, timestamp }` body in one place; `asyncHandler`, `errorMiddleware`, the `res.sendFile` 404 callback in `server/routes/loraTraining.js`, and the `authGate` 401/403 short-circuits now all route through it, so responses raised outside a handler's catch no longer omit `code`/`timestamp`. Mid-response failures (SSE/streaming routes) now delegate to Express's finalhandler so the socket is destroyed instead of the request hanging.- **[issue-2837] Break the agent-lifecycle circular-dependency cluster** — `finalizeAgent`/`releaseAgentLane` (plus the success-criteria + output-hook helpers) move to `server/services/agentFinalization.js`, the summary extractors to `agentSummaryExtraction.js`, runner recovery to `agentRunnerSync.js`, and the runner output batchers to `agentRunnerOutputBatchers.js`. With those leaves in place the two static cycles (`agentLifecycle` ↔ `agentCliSpawning`, `agentLifecycle` ↔ `agentTuiSpawning`) are gone, and three `await import()` cycle-dodges — `handleOrphanedTask`, the spawner's init-time lifecycle/management lookups, and `flushRunnerOutputBatcher` — become plain static imports. `agentLifecycle.js` still re-exports every moved symbol, so no import path changes for callers. New `agentImportCycles.test.js` re-derives the static import graph and fails if a cycle is reintroduced.- **[issue-2844] Drop the `@dnd-kit/utilities` dependency** — the package was pulled in only for `CSS.Transform.toString()` at three drag-and-drop sites (influence chips, CoS sortable tasks, video timeline blocks). A ~10-line owned helper, `dndTransformToCss` in `client/src/lib/dndTransform.js`, replaces it with byte-identical output (rounded `translate3d` + verbatim `scaleX`/`scaleY`, `undefined` for a null transform), and the direct dependency is removed from `client/package.json` and its lockfile. It remains in the tree only as a transitive peer of `@dnd-kit/core`/`sortable`, which stay.+- **[issue-2846] Add a client `sleep(ms)` helper and rebuild `useLocalStorageBool` on `safeStorage`** — `client/src/utils/sleep.js` mirrors the server helper and replaces the three duplicated inline delays (`lazyWithReload`'s retry backoff, `staleChunkReload`'s purge race timeout, `voiceClient`'s decoder-tick wait). `useLocalStorageBool`/`useLocalStoragePersisted` now delegate their four hand-rolled `try/catch` storage helpers to `client/src/lib/safeStorage.js`, which gains a `safeWriteJsonStorage` that guards `JSON.stringify` alongside `setItem`. The JSON read keeps a private sentinel so a stored `null` still runs the caller's `parse` migration instead of collapsing into "missing".diff --git a/client/src/hooks/useLocalStorageBool.js b/client/src/hooks/useLocalStorageBool.jsindex 10c5560286..69e0c16d61 100644--- a/client/src/hooks/useLocalStorageBool.js+++ b/client/src/hooks/useLocalStorageBool.js@@ -1,4 +1,10 @@import { useCallback, useState } from 'react';+import {+ safeReadJsonStorage,+ safeReadStorage,+ safeWriteJsonStorage,+ safeWriteStorage,+} from '../lib/safeStorage.js';// Boolean-valued `useState` mirror that round-trips through `localStorage`.//@@ -53,41 +59,29 @@ export function useLocalStoragePersisted(key, defaultValue, { parse } = {}) {}function readBool(key, defaultValue) {- if (typeof window === 'undefined') return defaultValue;- try {- const raw = window.localStorage.getItem(key);- if (raw === null) return defaultValue;- return raw === '1' || raw === 'true';- } catch {- return defaultValue;- }+ const raw = safeReadStorage(key);+ if (raw === null) return defaultValue;+ return raw === '1' || raw === 'true';}function writeBool(key, bool, format) {- if (typeof window === 'undefined') return;- try {- const v = format === 'true' ? String(bool) : (bool ? '1' : '0');- window.localStorage.setItem(key, v);- } catch { /* sandboxed storage */ }+ safeWriteStorage(key, format === 'true' ? String(bool) : (bool ? '1' : '0'));}+// `safeReadJsonStorage` collapses "missing" and "corrupt" into its fallback, so+// pass a private sentinel rather than `undefined` — `undefined` would hit the+// helper's own `fallback = null` default and be indistinguishable from a stored+// `null`, which we must return verbatim.+const MISSING = Symbol('missing');+// Returns `undefined` to distinguish "key missing / parse failed" (caller// applies the default) from a stored `null`. useLocalStoragePersisted uses// this so it can run an optional `parse` migration only on real stored data.function readJsonRaw(key) {- if (typeof window === 'undefined') return undefined;- try {- const raw = window.localStorage.getItem(key);- if (raw === null) return undefined;- return JSON.parse(raw);- } catch {- return undefined;- }+ const value = safeReadJsonStorage(key, MISSING);+ return value === MISSING ? undefined : value;}function writeJson(key, value) {- if (typeof window === 'undefined') return;- try {- window.localStorage.setItem(key, JSON.stringify(value));- } catch { /* sandboxed storage */ }+ safeWriteJsonStorage(key, value);}diff --git a/client/src/hooks/useLocalStorageBool.test.jsx b/client/src/hooks/useLocalStorageBool.test.jsxnew file mode 100644index 0000000000..65f72de6d9--- /dev/null+++ b/client/src/hooks/useLocalStorageBool.test.jsx@@ -0,0 +1,79 @@+import { describe, it, expect, afterEach, vi } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import { useLocalStorageBool, useLocalStoragePersisted } from './useLocalStorageBool.js';++afterEach(() => {+ vi.restoreAllMocks();+ window.localStorage.clear();+});++describe('useLocalStorageBool', () => {+ it('falls back to the default when the key is missing', () => {+ const { result } = renderHook(() => useLocalStorageBool('missing', true));+ expect(result.current[0]).toBe(true);+ });++ it('accepts both legacy encodings on read', () => {+ window.localStorage.setItem('a', '1');+ window.localStorage.setItem('b', 'true');+ window.localStorage.setItem('c', '0');+ expect(renderHook(() => useLocalStorageBool('a')).result.current[0]).toBe(true);+ expect(renderHook(() => useLocalStorageBool('b')).result.current[0]).toBe(true);+ expect(renderHook(() => useLocalStorageBool('c', true)).result.current[0]).toBe(false);+ });++ it('writes in the configured format and supports updater functions', () => {+ const { result } = renderHook(() => useLocalStorageBool('flag', false, { format: 'true' }));+ act(() => result.current[1]((prev) => !prev));+ expect(result.current[0]).toBe(true);+ expect(window.localStorage.getItem('flag')).toBe('true');++ const numeric = renderHook(() => useLocalStorageBool('n', false));+ act(() => numeric.result.current[1](true));+ expect(window.localStorage.getItem('n')).toBe('1');+ });++ it('keeps the default when storage reads throw', () => {+ vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {+ throw new DOMException('The operation is insecure.', 'SecurityError');+ });+ const { result } = renderHook(() => useLocalStorageBool('flag', true));+ expect(result.current[0]).toBe(true);+ });++ it('does not throw when storage writes throw', () => {+ vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {+ throw new DOMException('QuotaExceededError', 'QuotaExceededError');+ });+ const { result } = renderHook(() => useLocalStorageBool('flag', false));+ act(() => result.current[1](true));+ expect(result.current[0]).toBe(true);+ });+});++describe('useLocalStoragePersisted', () => {+ it('hydrates stored JSON and persists updates', () => {+ window.localStorage.setItem('cfg', JSON.stringify({ a: 1 }));+ const { result } = renderHook(() => useLocalStoragePersisted('cfg', { a: 0 }));+ expect(result.current[0]).toEqual({ a: 1 });++ act(() => result.current[1]({ a: 2 }));+ expect(JSON.parse(window.localStorage.getItem('cfg'))).toEqual({ a: 2 });+ });++ it('applies the default for missing and corrupt entries without running parse', () => {+ window.localStorage.setItem('corrupt', '{not-json');+ const parse = vi.fn();+ expect(renderHook(() => useLocalStoragePersisted('missing', 'd', { parse })).result.current[0]).toBe('d');+ expect(renderHook(() => useLocalStoragePersisted('corrupt', 'd', { parse })).result.current[0]).toBe('d');+ expect(parse).not.toHaveBeenCalled();+ });++ it('runs parse on a stored null rather than treating it as missing', () => {+ window.localStorage.setItem('nullish', 'null');+ const parse = vi.fn(() => 'migrated');+ const { result } = renderHook(() => useLocalStoragePersisted('nullish', 'default', { parse }));+ expect(parse).toHaveBeenCalledWith(null);+ expect(result.current[0]).toBe('migrated');+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex e2c16418b7..5e57dcffb5 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -100,7 +100,7 @@ grep -i "what you want to do" client/src/lib/README.md| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. || `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image src (`imageUrl` → served `image:<file>` bytes → null). Shared by MoodBoardDetail + MoodBoardReferenceStrip. || `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |-| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useCitySettings`, `useNavWorkingSet`, and the command palette. |+| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useCitySettings`, `useNavWorkingSet`, and the command palette. || `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. || `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). || `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |diff --git a/client/src/lib/safeStorage.js b/client/src/lib/safeStorage.jsindex 24036a673a..f68f77e442 100644--- a/client/src/lib/safeStorage.js+++ b/client/src/lib/safeStorage.js@@ -37,6 +37,17 @@ export const safeWriteStorage = (key, value) => {}};+// Best-effort JSON write. Serialization happens inside the guard because+// JSON.stringify itself throws on circular/BigInt values — a caller that only+// wrapped setItem would still crash on those.+export const safeWriteJsonStorage = (key, value) => {+ try {+ globalThis.localStorage?.setItem(key, JSON.stringify(value));+ } catch {+ // Ignore — the value stays in memory when persistence is unavailable.+ }+};+// Best-effort remove; silently no-ops when storage is unavailable.export const safeRemoveStorage = (key) => {try {diff --git a/client/src/lib/safeStorage.test.js b/client/src/lib/safeStorage.test.jsindex 8356e5c24e..e579eda7d3 100644--- a/client/src/lib/safeStorage.test.js+++ b/client/src/lib/safeStorage.test.js@@ -1,5 +1,5 @@import { describe, it, expect, afterEach, vi } from 'vitest';-import { safeReadStorage, safeReadJsonStorage, safeWriteStorage, safeRemoveStorage } from './safeStorage.js';+import { safeReadStorage, safeReadJsonStorage, safeWriteStorage, safeWriteJsonStorage, safeRemoveStorage } from './safeStorage.js';afterEach(() => {vi.restoreAllMocks();@@ -36,6 +36,16 @@ describe('safeStorage', () => {expect(safeReadJsonStorage('corrupt', [])).toEqual([]);});+ it('writes JSON and swallows a circular-value serialization throw', () => {+ safeWriteJsonStorage('obj', { a: 1 });+ expect(safeReadJsonStorage('obj', null)).toEqual({ a: 1 });++ const circular = {};+ circular.self = circular;+ expect(() => safeWriteJsonStorage('circular', circular)).not.toThrow();+ expect(safeReadStorage('circular')).toBeNull();+ });+it('swallows setItem / removeItem throws', () => {vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {throw new DOMException('QuotaExceededError', 'QuotaExceededError');diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex 2c1435ca73..839aa22d80 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -7,6 +7,7 @@import socket from './socket';import { subscribeVisibility } from '../hooks/useVisibilityEvent.js';+import { sleep } from '../utils/sleep.js';let stream = null;let recorder = null;@@ -641,7 +642,7 @@ export const captureScreenForVision = async () => {const playing = await video.play().then(() => true).catch(() => false);if (!playing) return null;// One frame is enough; give the decoder a tick to paint dimensions.- await new Promise((resolve) => setTimeout(resolve, 120));+ await sleep(120);const w = video.videoWidth || 1280;const h = video.videoHeight || 720;const canvas = document.createElement('canvas');diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 3212a41864..b7d997f236 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -35,6 +35,7 @@ grep -i "what you want to do" client/src/utils/README.md| `coalesce` | Trailing-edge coalescer: wraps a function so rapid calls collapse into one deferred invocation. || `easing` | `smoothstep` interpolation easing curve. || `hashString` | Deterministic string → 32-bit hash (stable colors, keys, seeds). |+| `sleep` | `sleep(ms)` — promise-returning `setTimeout` for retry backoffs and race timeouts. Use instead of re-declaring a local `delay`. || `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), and `isHttpUrl` (explicit http(s) only — safe-href check). || `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. || `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. |diff --git a/client/src/utils/index.js b/client/src/utils/index.jsindex ae3c2ccf2d..ddc2b1bc68 100644--- a/client/src/utils/index.js+++ b/client/src/utils/index.js@@ -20,6 +20,7 @@ export * from './animationClips.js';export * from './coalesce.js';export * from './easing.js';export * from './hashString.js';+export * from './sleep.js';export * from './urlNormalize.js';export * from './platform.js';export * from './navWorkingSet.js';diff --git a/client/src/utils/lazyWithReload.js b/client/src/utils/lazyWithReload.jsindex a6776544f0..74e7f70a3b 100644--- a/client/src/utils/lazyWithReload.js+++ b/client/src/utils/lazyWithReload.js@@ -1,13 +1,12 @@import { lazy } from 'react';import { isStaleChunkError, reloadOnceForStaleChunk } from './staleChunkReload';+import { sleep } from './sleep.js';// How many times to re-attempt a failed dynamic import before giving up, and// the base backoff between attempts (multiplied by the attempt number).const MAX_RETRIES = 2;const RETRY_BASE_DELAY_MS = 350;-const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));-// Retry a dynamic import a few times before treating the failure as terminal.// On flaky mobile/cellular links a chunk fetch can fail on a transient blip// ("Importing a module script failed" on Safari, "Failed to fetch dynamically@@ -18,7 +17,7 @@ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));export const importWithRetry = (importFn, retriesLeft = MAX_RETRIES) =>importFn().catch(async (err) => {if (retriesLeft > 0) {- await delay(RETRY_BASE_DELAY_MS * (MAX_RETRIES - retriesLeft + 1));+ await sleep(RETRY_BASE_DELAY_MS * (MAX_RETRIES - retriesLeft + 1));return importWithRetry(importFn, retriesLeft - 1);}throw err;diff --git a/client/src/utils/sleep.js b/client/src/utils/sleep.jsnew file mode 100644index 0000000000..018e0dd176--- /dev/null+++ b/client/src/utils/sleep.js@@ -0,0 +1,4 @@+// Promise-returning `setTimeout`. Every "wait a beat" in the client used to+// hand-roll its own `delay`/inline `new Promise(...)`; point at this instead so+// retry backoffs, race timeouts, and decoder-tick waits all read the same.+export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));diff --git a/client/src/utils/sleep.test.js b/client/src/utils/sleep.test.jsnew file mode 100644index 0000000000..1e013ea74c--- /dev/null+++ b/client/src/utils/sleep.test.js@@ -0,0 +1,25 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { sleep } from './sleep.js';++afterEach(() => {+ vi.useRealTimers();+});++describe('sleep', () => {+ it('resolves after the requested delay', async () => {+ vi.useFakeTimers();+ let settled = false;+ const pending = sleep(500).then(() => { settled = true; });++ await vi.advanceTimersByTimeAsync(499);+ expect(settled).toBe(false);++ await vi.advanceTimersByTimeAsync(1);+ await pending;+ expect(settled).toBe(true);+ });++ it('resolves with undefined', async () => {+ await expect(sleep(0)).resolves.toBeUndefined();+ });+});diff --git a/client/src/utils/staleChunkReload.js b/client/src/utils/staleChunkReload.jsindex fe6ef186ad..61747f3adf 100644--- a/client/src/utils/staleChunkReload.js+++ b/client/src/utils/staleChunkReload.js@@ -1,3 +1,5 @@+import { sleep } from './sleep.js';+// Cross-browser detection for stale dynamic-import chunk errors that happen// after a rebuild changes Vite chunk hashes while a tab is still open.//@@ -65,7 +67,7 @@ export const purgeOfflineCaches = async () => {const withTimeout = (promise, ms) =>Promise.race([Promise.resolve(promise).catch(() => {}),- new Promise((resolve) => setTimeout(resolve, ms)),+ sleep(ms),]);// A flaky or dead network produces the same import-error messages as a