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

fix([client-use-previous-hook]): add usePreviousSync for in-render snapshot, use it in useMediaJobProgress

[._.]/ Adam Eivy196243a4c31c
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index bdba1c6217..b46746f5e3 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -57,7 +57,8 @@ 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. |
+| `usePrevious` | Returns the value from the previous render — snapshot updated in a `useEffect`. | Compare-and-act on prop/state change from inside a `useEffect`. |
+| `usePreviousSync` | Same shape, but snapshot updated *during* render. | The prior value gates an in-render `setState` (React's "adjusting state on prop change" pattern); the during-render update avoids an extra discard/rerun cycle. |
| `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/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.js
index d63ff0cb50..28275beee1 100644
--- a/client/src/hooks/useMediaJobProgress.js
+++ b/client/src/hooks/useMediaJobProgress.js
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import socket from '../services/socket';
import { getMediaJob } from '../services/apiMediaJobs';
-import { usePrevious } from './usePrevious.js';
+import { usePreviousSync } from './usePrevious.js';
/**
* Subscribe to live progress for a single mediaJobQueue job (image-gen
@@ -34,13 +34,13 @@ 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. 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 otherwise mis-attribute the prior job's
- // filename to the NEW jobId and prematurely clear a queued batch.
- const prevJobId = usePrevious(jobId, jobId);
+ // prop change" pattern. `usePreviousSync` advances its snapshot during
+ // render (not in an effect), so React's re-run after the setState
+ // already sees `prevJobId === jobId` and doesn't fire a second setState.
+ // Without this synchronous semantics, the first observable render would
+ // still carry the prior job's `status` / `filename` and `onJobCompleted`
+ // consumers would mis-attribute it to the new jobId.
+ const prevJobId = usePreviousSync(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
index f94a4e2aee..3b0f5392dd 100644
--- a/client/src/hooks/usePrevious.js
+++ b/client/src/hooks/usePrevious.js
@@ -4,13 +4,40 @@ 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.
+ * The snapshot is updated in a `useEffect`, so the returned value reflects
+ * the *committed* prior value. Use this when the prior value is read from a
+ * `useEffect` (post-commit) — e.g. fire a callback when a derived boolean
+ * transitions from false to true.
+ *
+ * If you need the prior value to drive a synchronous `setState` during render
+ * (React's "adjusting state on prop change" pattern), use `usePreviousSync`
+ * — `usePrevious`'s effect-based snapshot would force one extra
+ * discard-and-rerun cycle before the ref updates.
*/
export function usePrevious(value, initialValue) {
const ref = useRef(initialValue);
useEffect(() => { ref.current = value; }, [value]);
return ref.current;
}
+
+/**
+ * Returns the value from the previous render and updates the snapshot
+ * *during* render (not in an effect). On the first render, returns
+ * `initialValue` (default `undefined`).
+ *
+ * Use this for React's "adjusting state on prop change" pattern, where the
+ * prior value gates an in-render `setState` and you want React to discard
+ * the in-progress render and re-run once with the new state — the
+ * during-render ref update means the re-run sees the snapshot already
+ * advanced, so the condition is false and the setState is skipped.
+ *
+ * Mutating a ref during render is supported by React (refs are escape
+ * hatches and not tracked for re-renders); it is the idiomatic way to
+ * snapshot the prior render's value synchronously.
+ */
+export function usePreviousSync(value, initialValue) {
+ const ref = useRef(initialValue);
+ const prev = ref.current;
+ ref.current = value;
+ return prev;
+}
diff --git a/client/src/hooks/usePrevious.test.jsx b/client/src/hooks/usePrevious.test.jsx
index 6d5a464691..b3beaacab0 100644
--- a/client/src/hooks/usePrevious.test.jsx
+++ b/client/src/hooks/usePrevious.test.jsx
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { renderHook } from '@testing-library/react';
-import { usePrevious } from './usePrevious';
+import { usePrevious, usePreviousSync } from './usePrevious';
describe('usePrevious', () => {
it('returns the initial value on the first render', () => {
@@ -40,3 +40,39 @@ describe('usePrevious', () => {
expect(result.current).toBe(2);
});
});
+
+describe('usePreviousSync', () => {
+ it('returns the initial value on the first render', () => {
+ const { result } = renderHook(() => usePreviousSync('a', 'initial'));
+ expect(result.current).toBe('initial');
+ });
+
+ it('returns the previous render value on subsequent renders', () => {
+ const { result, rerender } = renderHook(({ v }) => usePreviousSync(v, v), {
+ initialProps: { v: 'a' },
+ });
+ // Initial=value pattern (matches the useMediaJobProgress call shape):
+ // first render returns the seed equal to current → no compare-and-act fires.
+ expect(result.current).toBe('a');
+
+ rerender({ v: 'b' });
+ expect(result.current).toBe('a');
+
+ rerender({ v: 'c' });
+ expect(result.current).toBe('b');
+ });
+
+ it('snapshots synchronously — same-value re-render returns the new value immediately', () => {
+ const { result, rerender } = renderHook(({ v }) => usePreviousSync(v), {
+ initialProps: { v: 1 },
+ });
+
+ rerender({ v: 2 });
+ expect(result.current).toBe(1);
+
+ // Unlike the effect-based variant, the snapshot advances during render —
+ // the next render with the same value returns the value it just saw.
+ rerender({ v: 2 });
+ expect(result.current).toBe(2);
+ });
+});