Skip to content

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

refactor([client-use-previous-hook]): extract shared usePrevious hook and migrate two ad-hoc sites

[._.]/ Adam Eivy1781de1d0fcf
diff --git a/client/src/components/settings/LocalSetupPanel.jsx b/client/src/components/settings/LocalSetupPanel.jsx
index 0728574258..26f2bb5119 100644
--- a/client/src/components/settings/LocalSetupPanel.jsx
+++ b/client/src/components/settings/LocalSetupPanel.jsx
@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { CheckCircle2, XCircle, Wand2, RefreshCw, Terminal, AlertTriangle, Box, Cpu } from 'lucide-react';
import toast from '../ui/Toast';
import BrailleSpinner from '../BrailleSpinner';
+import { usePrevious } from '../../hooks/usePrevious.js';
export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPackagesChanged }) {
const [detecting, setDetecting] = useState(false);
@@ -69,12 +70,12 @@ export default function LocalSetupPanel({ pythonPath, onPythonPathChange, onPack
// packages" to "all installed" — covers manual refresh, terminal installs,
// and the SSE-complete path. Without this, parent state (e.g. VideoGen's
// status pill) stays stale until the user manually clicks its own refresh.
- const prevHadMissingRef = useRef(false);
+ const hadMissing = !!check && Array.isArray(check.missing) && check.missing.length > 0;
+ const allInstalled = !!check && Array.isArray(check.missing) && check.missing.length === 0;
+ const prevHadMissing = usePrevious(hadMissing, false);
useEffect(() => {
- const allInstalled = !!check && Array.isArray(check.missing) && check.missing.length === 0;
- if (allInstalled && prevHadMissingRef.current) onPackagesChanged?.();
- prevHadMissingRef.current = !!check && Array.isArray(check.missing) && check.missing.length > 0;
- }, [check, onPackagesChanged]);
+ if (allInstalled && prevHadMissing) onPackagesChanged?.();
+ }, [allInstalled, prevHadMissing, onPackagesChanged]);
const handleDetect = async () => {
setDetecting(true);
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 4a8d29f7ae..bdba1c6217 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -57,6 +57,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |
| `useUpdateChecker` | Detect stale client bundle; show reload toast. | Wire once at app root. |
| `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. |
+| `usePrevious` | Returns the value from the previous render (initial value on first render). | Compare-and-act on prop/state change without rolling another `useRef` + `useEffect` pair. |
| `useTimeTick` | Singleton-backed wall-clock tick (`Date.now()`); N subscribers at the same cadence share one `setInterval`. | A widget renders something derived from `Date.now()` (relative timestamps, threshold-based health labels, countdowns) and is also fed by a deduped `useAutoRefetch` — without this the label goes stale until the data changes. |
| `useVisibilityEvent` | Singleton-backed `document.visibilitychange` subscription (N subscribers share one listener). | Reacting to tab show/hide without spawning a per-component listener. `useAutoRefetch` already builds on this. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 7e5cf091d6..6cc25bcdd9 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -58,6 +58,7 @@ export * from './useOpenClawAttachments.js';
export * from './useCodeReviewDefaults.jsx';
// === Sockets & lifecycle ===
+export * from './usePrevious.js';
export * from './useSocket.js';
export * from './useTimeTick.js';
export * from './useUpdateChecker.jsx';
diff --git a/client/src/hooks/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.js
index 2bdff31de5..d63ff0cb50 100644
--- a/client/src/hooks/useMediaJobProgress.js
+++ b/client/src/hooks/useMediaJobProgress.js
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import socket from '../services/socket';
import { getMediaJob } from '../services/apiMediaJobs';
+import { usePrevious } from './usePrevious.js';
/**
* Subscribe to live progress for a single mediaJobQueue job (image-gen
@@ -33,19 +34,14 @@ const INITIAL_STATE = Object.freeze({
export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
const [state, setState] = useState(INITIAL_STATE);
// SYNCHRONOUS reset when `jobId` changes — React's "adjusting state on
- // prop change" pattern. Doing this in a `useEffect` (as we used to)
- // means the FIRST render after `jobId` flips still returns the previous
+ // prop change" pattern. The setState below runs DURING render (guarded by
+ // the prev !== current check), so React discards the in-progress render
+ // and re-runs with INITIAL_STATE before consumers ever observe the prior
// job's `status` / `filename`. Consumers that fire `onJobCompleted` on
- // status='completed' would mis-attribute the prior job's filename to the
- // NEW jobId and prematurely clear the rest of a queued batch. With this
- // pattern React discards the in-progress render and re-runs the
- // component immediately, so the new jobId is never observed against
- // stale state.
- const prevJobIdRef = useRef(jobId);
- if (prevJobIdRef.current !== jobId) {
- prevJobIdRef.current = jobId;
- setState(INITIAL_STATE);
- }
+ // status='completed' would otherwise mis-attribute the prior job's
+ // filename to the NEW jobId and prematurely clear a queued batch.
+ const prevJobId = usePrevious(jobId, jobId);
+ if (prevJobId !== jobId) setState(INITIAL_STATE);
// Track mount so the initial fetch's setState doesn't fire after unmount
// (the panel could be removed while the GET is in flight).
//
diff --git a/client/src/hooks/usePrevious.js b/client/src/hooks/usePrevious.js
new file mode 100644
index 0000000000..f94a4e2aee
--- /dev/null
+++ b/client/src/hooks/usePrevious.js
@@ -0,0 +1,16 @@
+import { useEffect, useRef } from 'react';
+
+/**
+ * Returns the value from the previous render. On the first render, returns
+ * `initialValue` (default `undefined`).
+ *
+ * Useful for "did this prop/state just change?" comparisons where the previous
+ * value is needed to decide whether to fire a side effect. The snapshot is
+ * updated in a `useEffect`, so within a render the returned value reflects the
+ * prior committed value — exactly the contract a compare-and-act block expects.
+ */
+export function usePrevious(value, initialValue) {
+ const ref = useRef(initialValue);
+ useEffect(() => { ref.current = value; }, [value]);
+ return ref.current;
+}
diff --git a/client/src/hooks/usePrevious.test.jsx b/client/src/hooks/usePrevious.test.jsx
new file mode 100644
index 0000000000..6d5a464691
--- /dev/null
+++ b/client/src/hooks/usePrevious.test.jsx
@@ -0,0 +1,42 @@
+import { describe, it, expect } from 'vitest';
+import { renderHook } from '@testing-library/react';
+import { usePrevious } from './usePrevious';
+
+describe('usePrevious', () => {
+ it('returns the initial value on the first render', () => {
+ const { result } = renderHook(() => usePrevious('a', 'initial'));
+ expect(result.current).toBe('initial');
+ });
+
+ it('returns undefined when no initial value is supplied', () => {
+ const { result } = renderHook(() => usePrevious('a'));
+ expect(result.current).toBeUndefined();
+ });
+
+ it('returns the previous render value on subsequent renders', () => {
+ const { result, rerender } = renderHook(({ v }) => usePrevious(v, 'initial'), {
+ initialProps: { v: 'a' },
+ });
+ expect(result.current).toBe('initial');
+
+ rerender({ v: 'b' });
+ expect(result.current).toBe('a');
+
+ rerender({ v: 'c' });
+ expect(result.current).toBe('b');
+ });
+
+ it('still returns the prior value across a re-render with the same value', () => {
+ const { result, rerender } = renderHook(({ v }) => usePrevious(v), {
+ initialProps: { v: 1 },
+ });
+
+ rerender({ v: 2 });
+ expect(result.current).toBe(1);
+
+ // Same value re-render: ref-update effect only fires when the dep changes,
+ // so the snapshot stays at the previously-rendered value.
+ rerender({ v: 2 });
+ expect(result.current).toBe(2);
+ });
+});