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([issue-1086]): extract sidebar data-fetch hooks from Layout.jsx
Adam Eivy96c1c4f69d0a
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex e316bbce5e..d6aaf78ccb 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -95,6 +95,9 @@ import { useSharingNotifications } from '../hooks/useSharingNotifications';import { useUpdateChecker } from '../hooks/useUpdateChecker';import { useAIStatusNotifications } from '../hooks/useAIStatusNotifications';import { useNavWorkingSet } from '../hooks/useNavWorkingSet.js';+import { useSidebarApps } from '../hooks/useSidebarApps.js';+import { useSidebarSeries } from '../hooks/useSidebarSeries.js';+import { useSidebarUniverses } from '../hooks/useSidebarUniverses.js';import { useThemeContext } from './ThemeContext';import NotificationDropdown from './NotificationDropdown';import VoiceToggleButton from './voice/VoiceToggleButton';@@ -120,7 +123,6 @@ function ThemeModeToggle({ className = '' }) {);}import * as api from '../services/api';-import socket from '../services/socket';const navItems = [{ to: '/', label: 'Dashboard', icon: Home, single: true },@@ -484,80 +486,12 @@ export default function Layout() {clearAll} = useNotifications();- // Fetch apps for sidebar navigation- const [sidebarApps, setSidebarApps] = useState([]);- useEffect(() => {- const fetchApps = () => {- api.getApps({ silent: true }).then(apps => {- setSidebarApps((apps || []).filter(a => !a.archived).sort((a, b) => a.name.localeCompare(b.name)));- }).catch((err) => {- console.warn(`⚠️ Layout: getApps refresh failed: ${err?.message || err}`);- });- };- fetchApps();- socket.on('apps:changed', fetchApps);- return () => socket.off('apps:changed', fetchApps);- }, []);-- // Fetch all pipeline series for the Create > Pipeline grandchildren.- // Refresh on focus (debounced 30s) so freshly-created or renamed series- // surface without a reload. Signature guard avoids re-rendering the whole- // sidebar tree when nothing changed.- const [pipelineSeries, setPipelineSeries] = useState([]);- useEffect(() => {- let lastSuccessAt = 0;- const sigOf = (items) => items.map((s) => `${s.id}|${s.name}`).join('||');- const loadSeries = () => {- api.listPipelineSeries({ silent: true })- .then((items) => {- lastSuccessAt = Date.now();- const next = (Array.isArray(items) ? items : []).slice().sort((a, b) =>- (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }),- );- setPipelineSeries((prev) => sigOf(prev) === sigOf(next) ? prev : next);- })- .catch((err) => {- console.warn(`⚠️ Sidebar pipeline-series fetch failed: ${err?.message || err}`);- });- };- loadSeries();- const onFocus = () => {- if (Date.now() - lastSuccessAt < 30_000) return;- loadSeries();- };- window.addEventListener('focus', onFocus);- return () => window.removeEventListener('focus', onFocus);- }, []);-- // Fetch all universes for the Create > Universes grandchildren.- // Refresh on focus (debounced 30s) so freshly-created or renamed universes- // surface without a reload. Signature guard avoids re-rendering the whole- // sidebar tree when nothing changed.- const [universes, setUniverses] = useState([]);- useEffect(() => {- let lastSuccessAt = 0;- const sigOf = (items) => items.map((u) => `${u.id}|${u.name}`).join('||');- const loadUniverses = () => {- api.listUniverses({ silent: true })- .then((items) => {- lastSuccessAt = Date.now();- const next = (Array.isArray(items) ? items : []).slice().sort((a, b) =>- (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }),- );- setUniverses((prev) => sigOf(prev) === sigOf(next) ? prev : next);- })- .catch((err) => {- console.warn(`⚠️ Sidebar universes fetch failed: ${err?.message || err}`);- });- };- loadUniverses();- const onFocus = () => {- if (Date.now() - lastSuccessAt < 30_000) return;- loadUniverses();- };- window.addEventListener('focus', onFocus);- return () => window.removeEventListener('focus', onFocus);- }, []);+ // Sidebar data-fetch loops (apps / pipeline series / universes) live in+ // dedicated hooks so the shared focus-debounce + signature-guard pattern is+ // testable in isolation. See client/src/hooks/useSidebar*.js.+ const sidebarApps = useSidebarApps();+ const pipelineSeries = useSidebarSeries();+ const universes = useSidebarUniverses();// Fetch the palette nav manifest once on mount so manifest-only paths// (e.g. /wiki/log, /goals/tree) can be resolved in the Pinned/Recent sectionsdiff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 2a102a3dda..6fcf4ffd72 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -102,6 +102,15 @@ grep -i "what you want to do" client/src/hooks/README.md| `useLocalStorageBool` | Boolean `useState` mirrored to `localStorage`. | Per-user UI preference toggle. || `useNavWorkingSet` | Sidebar Pinned + Recent working set (localStorage MRU + pins); resolves stored paths to `{ path, label, icon }` rows via a `resolveNavEntry` arg. | Rendering the sidebar's Pinned/Recent sections. |+## Sidebar navigation data++| Hook | Purpose | Use when |+|---|---|---|+| `useFocusRefreshedList` | Load-once-then-refresh-on-focus list fetcher: debounces focus refreshes to 30s, sorts by name, and skips re-render when an `id\|name` signature is unchanged. Owns its own warn-on-error. | Any sidebar/nav list that should refresh when the user returns to the tab without hammering the API. Pass a stable `api.*` fetch fn. |+| `useSidebarApps` | Apps list for sidebar nav: socket-driven (`apps:changed`), archived filtered out, name-sorted. | The sidebar apps section. |+| `useSidebarSeries` | Pipeline series for the Create > Pipeline grandchildren (built on `useFocusRefreshedList`). | The sidebar pipeline-series section. |+| `useSidebarUniverses` | Universes for the Create > Universes grandchildren (built on `useFocusRefreshedList`). | The sidebar universes section. |+## Apps / Sessions / Domain| Hook | Purpose | Use when |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 9c950ddcc7..6a7edf1f69 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -96,6 +96,12 @@ export * from './useSwipeNav.js';export * from './useLocalStorageBool.js';export * from './useNavWorkingSet.js';+// === Sidebar navigation data ===+export * from './useFocusRefreshedList.js';+export * from './useSidebarApps.js';+export * from './useSidebarSeries.js';+export * from './useSidebarUniverses.js';+// === Domain: City / Voice / Mortality / Universe / Apps / Sessions ===export * from './useAppDeploy.js';export * from './useAppOperation.js';diff --git a/client/src/hooks/useFocusRefreshedList.js b/client/src/hooks/useFocusRefreshedList.jsnew file mode 100644index 0000000000..6f02ae07b3--- /dev/null+++ b/client/src/hooks/useFocusRefreshedList.js@@ -0,0 +1,52 @@+import { useState, useEffect, useRef } from 'react';++// Shared sidebar-list fetch pattern: load once on mount, refresh on window+// focus (debounced 30s so tab-switching doesn't hammer the API), and guard+// against re-rendering the consumer when the list is unchanged via an+// id|name signature compare. Sorts by name (case-insensitive) so the caller+// always receives a stable, display-ready array.+//+// `fetchFn` must accept `{ silent: true }` (it owns its own error handling via+// the warn below, so the API helper should not also toast) and resolve to an+// array. Pass a stable function reference (a module-level `api.*` export is+// stable). The `signature`/`label` options are read through refs so an inline+// arrow doesn't re-arm the effect (and double-fetch) on every render.+const defaultSignature = (item) => `${item.id}|${item.name}`;+const byName = (a, b) =>+ (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' });++export function useFocusRefreshedList(fetchFn, { signature = defaultSignature, label = 'list' } = {}) {+ const [items, setItems] = useState([]);+ const signatureRef = useRef(signature);+ signatureRef.current = signature;+ const labelRef = useRef(label);+ labelRef.current = label;+ useEffect(() => {+ let lastSuccessAt = 0;+ let cancelled = false;+ const sigOf = (list) => list.map((item) => signatureRef.current(item)).join('||');+ const load = () => {+ fetchFn({ silent: true })+ .then((result) => {+ if (cancelled) return;+ lastSuccessAt = Date.now();+ const next = (Array.isArray(result) ? result : []).slice().sort(byName);+ setItems((prev) => (sigOf(prev) === sigOf(next) ? prev : next));+ })+ .catch((err) => {+ console.warn(`⚠️ Sidebar ${labelRef.current} fetch failed: ${err?.message || err}`);+ });+ };+ load();+ const onFocus = () => {+ if (Date.now() - lastSuccessAt < 30_000) return;+ load();+ };+ window.addEventListener('focus', onFocus);+ return () => {+ cancelled = true;+ window.removeEventListener('focus', onFocus);+ };+ }, [fetchFn]);+ return items;+}diff --git a/client/src/hooks/useFocusRefreshedList.test.jsx b/client/src/hooks/useFocusRefreshedList.test.jsxnew file mode 100644index 0000000000..741ba4938b--- /dev/null+++ b/client/src/hooks/useFocusRefreshedList.test.jsx@@ -0,0 +1,110 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act, waitFor } from '@testing-library/react';+import { useFocusRefreshedList } from './useFocusRefreshedList.js';++const fireFocus = () => act(() => { window.dispatchEvent(new Event('focus')); });++describe('useFocusRefreshedList', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('fetches once on mount and returns a name-sorted array', async () => {+ const fetchFn = vi.fn().mockResolvedValue([+ { id: '2', name: 'Zebra' },+ { id: '1', name: 'apple' },+ ]);+ const { result } = renderHook(() => useFocusRefreshedList(fetchFn));++ await waitFor(() => expect(result.current.length).toBe(2));+ expect(fetchFn).toHaveBeenCalledTimes(1);+ expect(fetchFn).toHaveBeenCalledWith({ silent: true });+ // Case-insensitive sort: 'apple' before 'Zebra'.+ expect(result.current.map((i) => i.id)).toEqual(['1', '2']);+ });++ it('preserves the previous array reference when the signature is unchanged', async () => {+ const fetchFn = vi.fn()+ .mockResolvedValueOnce([{ id: '1', name: 'A' }])+ .mockResolvedValue([{ id: '1', name: 'A' }]);+ const { result } = renderHook(() => useFocusRefreshedList(fetchFn));++ await waitFor(() => expect(result.current.length).toBe(1));+ const first = result.current;++ // Advance past the 30s debounce so the focus handler actually refetches.+ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 31_000);+ fireFocus();+ await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(2));+ expect(result.current).toBe(first); // same id|name signature → no new array+ });++ it('replaces the array when the signature changes', async () => {+ const fetchFn = vi.fn()+ .mockResolvedValueOnce([{ id: '1', name: 'A' }])+ .mockResolvedValue([{ id: '1', name: 'A renamed' }]);+ const { result } = renderHook(() => useFocusRefreshedList(fetchFn));++ await waitFor(() => expect(result.current[0].name).toBe('A'));++ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 31_000);+ fireFocus();+ await waitFor(() => expect(result.current[0].name).toBe('A renamed'));+ });++ it('debounces focus refreshes within 30s of the last success', async () => {+ const fetchFn = vi.fn().mockResolvedValue([{ id: '1', name: 'A' }]);+ renderHook(() => useFocusRefreshedList(fetchFn));+ await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));++ // Focus immediately — still inside the 30s window, so no refetch.+ fireFocus();+ await new Promise((r) => setTimeout(r, 20));+ expect(fetchFn).toHaveBeenCalledTimes(1);+ });++ it('coerces a non-array result to an empty array and warns on rejection', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const fetchFn = vi.fn().mockResolvedValue(null);+ const { result } = renderHook(() => useFocusRefreshedList(fetchFn, { label: 'widgets' }));+ await waitFor(() => expect(fetchFn).toHaveBeenCalled());+ expect(result.current).toEqual([]);++ const rejectFn = vi.fn().mockRejectedValue(new Error('boom'));+ renderHook(() => useFocusRefreshedList(rejectFn, { label: 'widgets' }));+ await waitFor(() => expect(warn).toHaveBeenCalled());+ expect(warn.mock.calls.some((c) => String(c[0]).includes('widgets'))).toBe(true);+ warn.mockRestore();+ });++ it('honors a custom signature function', async () => {+ const fetchFn = vi.fn()+ .mockResolvedValueOnce([{ id: '1', name: 'A', rev: 1 }])+ .mockResolvedValue([{ id: '1', name: 'A', rev: 2 }]);+ const { result } = renderHook(() =>+ useFocusRefreshedList(fetchFn, { signature: (i) => `${i.id}|${i.rev}` }),+ );+ await waitFor(() => expect(result.current[0].rev).toBe(1));++ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + 31_000);+ fireFocus();+ // rev changed → signature differs → array replaced even though name is equal.+ await waitFor(() => expect(result.current[0].rev).toBe(2));+ });++ it('removes the focus listener on unmount', async () => {+ const fetchFn = vi.fn().mockResolvedValue([{ id: '1', name: 'A' }]);+ const removeSpy = vi.spyOn(window, 'removeEventListener');+ const { unmount } = renderHook(() => useFocusRefreshedList(fetchFn));+ await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));+ unmount();+ expect(removeSpy).toHaveBeenCalledWith('focus', expect.any(Function));+ removeSpy.mockRestore();+ });+});diff --git a/client/src/hooks/useSidebarApps.js b/client/src/hooks/useSidebarApps.jsnew file mode 100644index 0000000000..4013a94311--- /dev/null+++ b/client/src/hooks/useSidebarApps.js@@ -0,0 +1,28 @@+import { useState, useEffect } from 'react';+import * as api from '../services/api';+import socket from '../services/socket';++// Sidebar apps list: load on mount and refresh whenever the server emits+// `apps:changed`. Archived apps are filtered out and the rest sorted by name.+// Unlike the series/universes lists this is socket-driven (not focus-debounced)+// because app create/rename/archive events are pushed live.+export function useSidebarApps() {+ const [apps, setApps] = useState([]);+ useEffect(() => {+ const fetchApps = () => {+ api.getApps({ silent: true })+ .then((result) => {+ setApps((result || [])+ .filter((a) => !a.archived)+ .sort((a, b) => a.name.localeCompare(b.name)));+ })+ .catch((err) => {+ console.warn(`⚠️ Layout: getApps refresh failed: ${err?.message || err}`);+ });+ };+ fetchApps();+ socket.on('apps:changed', fetchApps);+ return () => socket.off('apps:changed', fetchApps);+ }, []);+ return apps;+}diff --git a/client/src/hooks/useSidebarSeries.js b/client/src/hooks/useSidebarSeries.jsnew file mode 100644index 0000000000..99d385668b--- /dev/null+++ b/client/src/hooks/useSidebarSeries.js@@ -0,0 +1,9 @@+import * as api from '../services/api';+import { useFocusRefreshedList } from './useFocusRefreshedList.js';++// All pipeline series for the Create > Pipeline grandchildren. Loads on mount+// and refreshes on window focus (debounced 30s) so freshly-created or renamed+// series surface without a reload.+export function useSidebarSeries() {+ return useFocusRefreshedList(api.listPipelineSeries, { label: 'pipeline-series' });+}diff --git a/client/src/hooks/useSidebarUniverses.js b/client/src/hooks/useSidebarUniverses.jsnew file mode 100644index 0000000000..2bb0dab3e8--- /dev/null+++ b/client/src/hooks/useSidebarUniverses.js@@ -0,0 +1,9 @@+import * as api from '../services/api';+import { useFocusRefreshedList } from './useFocusRefreshedList.js';++// All universes for the Create > Universes grandchildren. Loads on mount and+// refreshes on window focus (debounced 30s) so freshly-created or renamed+// universes surface without a reload.+export function useSidebarUniverses() {+ return useFocusRefreshedList(api.listUniverses, { label: 'universes' });+}