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

feat([extract-compare-helpers-once-eight-callers]): extract equalByKeys / equalListByKeys for useAutoRefetch compare

Adam Eivydf1113cd0373
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsx
index b39d237824..e6313767ff 100644
--- a/client/src/components/BackupWidget.jsx
+++ b/client/src/components/BackupWidget.jsx
@@ -15,6 +15,7 @@ import toast from './ui/Toast';
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { useTimeTick } from '../hooks/useTimeTick';
+import { equalByKeys, equalListByKeys } from '../lib/compareHelpers';
// ---------------------------------------------------------------------------
// Pure helpers
@@ -212,14 +213,7 @@ function SnapshotList() {
// the oldest — walk every rendered tuple (id + fileCount) so a stale
// server-side fileCount recount or a middle-row mutation can't hide
// behind the head/tail id check.
- compare: (prev, next) => {
- if (prev.length !== next.length) return false;
- for (let i = 0; i < prev.length; i++) {
- if (prev[i]?.id !== next[i]?.id) return false;
- if (prev[i]?.fileCount !== next[i]?.fileCount) return false;
- }
- return true;
- },
+ compare: (prev, next) => equalListByKeys(prev, next, ['id', 'fileCount']),
},
);
const [selectedId, setSelectedId] = useState(null);
@@ -282,14 +276,9 @@ const BackupWidget = memo(function BackupWidget() {
// monotonic timestamps + status + error + destPath captures every
// visible change at the widget's resolution. Avoids per-poll re-renders
// that would re-compute relative-time labels for no visual benefit.
- compare: (prev, next) => (
- prev.status === next.status
- && prev.lastRun === next.lastRun
- && prev.nextRun === next.nextRun
- && prev.error === next.error
- && prev.filesChanged === next.filesChanged
- && prev.destPath === next.destPath
- ),
+ compare: (prev, next) => equalByKeys(prev, next, [
+ 'status', 'lastRun', 'nextRun', 'error', 'filesChanged', 'destPath',
+ ]),
},
);
const [triggering, setTriggering] = useState(false);
diff --git a/client/src/components/DecisionLogWidget.jsx b/client/src/components/DecisionLogWidget.jsx
index bd481db14d..9b4db119db 100644
--- a/client/src/components/DecisionLogWidget.jsx
+++ b/client/src/components/DecisionLogWidget.jsx
@@ -18,6 +18,7 @@ import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { useTimeTick } from '../hooks/useTimeTick';
import { timeAgo } from '../utils/formatters';
+import { equalByKeys, equalListByKeys } from '../lib/compareHelpers';
/**
* DecisionLogWidget - Shows transparency into CoS decision-making
@@ -44,48 +45,19 @@ const DecisionLogWidget = memo(function DecisionLogWidget() {
// below — including the timestamp fields in this comparator would
// pointlessly break dedup on every backend mtime nudge. Keep this tuple
// in sync with the JSX above.
- compare: (prev, next) => {
- if (prev.last24Hours?.total !== next.last24Hours?.total
- || prev.last24Hours?.skipped !== next.last24Hours?.skipped
- || prev.last24Hours?.switched !== next.last24Hours?.switched
- || prev.last24Hours?.capacityFull !== next.last24Hours?.capacityFull
- || prev.last24Hours?.cooldownActive !== next.last24Hours?.cooldownActive
- || prev.last24Hours?.selected !== next.last24Hours?.selected
- || prev.last24Hours?.adjusted !== next.last24Hours?.adjusted
- || prev.transparencyScore !== next.transparencyScore) return false;
- const a = Array.isArray(prev.impactfulDecisions) ? prev.impactfulDecisions : null;
- const b = Array.isArray(next.impactfulDecisions) ? next.impactfulDecisions : null;
- if (a === null || b === null) return a === b;
- if (a.length !== b.length) return false;
- for (let i = 0; i < a.length; i++) {
- const da = a[i];
- const db = b[i];
- if (
- da.id !== db?.id
- || da.type !== db?.type
- || da.reason !== db?.reason
- || (da.count ?? 1) !== (db?.count ?? 1)
- ) return false;
- const ca = da.context;
- const cb = db?.context;
- if (
- ca?.running !== cb?.running
- || ca?.max !== cb?.max
- || ca?.project !== cb?.project
- || ca?.limit !== cb?.limit
- || ca?.appId !== cb?.appId
- || ca?.cooldownMs !== cb?.cooldownMs
- || ca?.fromTask !== cb?.fromTask
- || ca?.toTask !== cb?.toTask
- || ca?.attempts !== cb?.attempts
- || ca?.runningAgents !== cb?.runningAgents
- || ca?.awaitingApproval !== cb?.awaitingApproval
- || ca?.taskType !== cb?.taskType
- || ca?.successRate !== cb?.successRate
- ) return false;
- }
- return true;
- },
+ compare: (prev, next) =>
+ equalByKeys(prev.last24Hours, next.last24Hours, [
+ 'total', 'skipped', 'switched', 'capacityFull',
+ 'cooldownActive', 'selected', 'adjusted',
+ ])
+ && prev.transparencyScore === next.transparencyScore
+ && equalListByKeys(prev.impactfulDecisions, next.impactfulDecisions, [
+ 'id', 'type', 'reason', (d) => d?.count ?? 1,
+ 'context.running', 'context.max', 'context.project', 'context.limit',
+ 'context.appId', 'context.cooldownMs', 'context.fromTask', 'context.toTask',
+ 'context.attempts', 'context.runningAgents', 'context.awaitingApproval',
+ 'context.taskType', 'context.successRate',
+ ]),
},
);
const [expanded, setExpanded] = useState(false);
diff --git a/client/src/components/GoalProgressWidget.jsx b/client/src/components/GoalProgressWidget.jsx
index 55576dd000..2106df8b3f 100644
--- a/client/src/components/GoalProgressWidget.jsx
+++ b/client/src/components/GoalProgressWidget.jsx
@@ -4,6 +4,7 @@ import { ChevronRight, AlertTriangle, Target } from 'lucide-react';
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { useTimeTick } from '../hooks/useTimeTick';
+import { equalListByKeys } from '../lib/compareHelpers';
import { CATEGORY_CONFIG, GOAL_TYPE_CONFIG } from './goals/GoalDetailPanel';
const HORIZON_LABELS = {
@@ -40,24 +41,10 @@ const GoalProgressWidget = memo(function GoalProgressWidget() {
// drive `daysSinceUpdate` / `isStalled` (a backfilled or corrected
// progressHistory entry mutates the latest timestamp without changing
// array length).
- compare: (prev, next) => {
- const a = Array.isArray(prev.goals) ? prev.goals : null;
- const b = Array.isArray(next.goals) ? next.goals : null;
- if (a === null || b === null) return a === b;
- return a.length === b.length && a.every((g, i) => (
- g.id === b[i]?.id
- && g.title === b[i]?.title
- && g.category === b[i]?.category
- && g.horizon === b[i]?.horizon
- && g.goalType === b[i]?.goalType
- && g.progress === b[i]?.progress
- && g.status === b[i]?.status
- && g.parentId === b[i]?.parentId
- && g.urgency === b[i]?.urgency
- && g.createdAt === b[i]?.createdAt
- && getLastProgressDate(g) === getLastProgressDate(b[i])
- ));
- },
+ compare: (prev, next) => equalListByKeys(prev.goals, next.goals, [
+ 'id', 'title', 'category', 'horizon', 'goalType', 'progress',
+ 'status', 'parentId', 'urgency', 'createdAt', getLastProgressDate,
+ ]),
},
);
diff --git a/client/src/components/ProactiveAlertsWidget.jsx b/client/src/components/ProactiveAlertsWidget.jsx
index a29a2a6389..c60f9f57bb 100644
--- a/client/src/components/ProactiveAlertsWidget.jsx
+++ b/client/src/components/ProactiveAlertsWidget.jsx
@@ -14,6 +14,7 @@ import {
} from 'lucide-react';
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { equalByKeys, equalListByKeys } from '../lib/compareHelpers';
const SEVERITY_STYLES = {
critical: { bg: 'bg-port-error/10', text: 'text-port-error', border: 'border-port-error/30' },
@@ -41,22 +42,11 @@ const ProactiveAlertsWidget = memo(function ProactiveAlertsWidget() {
// field are unchanged. Each alert row renders title, detail, severity
// (style class), type (icon), and link (href), so all five participate
// in the comparison — keep this list in sync with the JSX below.
- compare: (prev, next) => {
- if (prev.counts?.total !== next.counts?.total
- || prev.counts?.critical !== next.counts?.critical
- || prev.counts?.high !== next.counts?.high
- || prev.counts?.medium !== next.counts?.medium) return false;
- const a = Array.isArray(prev.alerts) ? prev.alerts : null;
- const b = Array.isArray(next.alerts) ? next.alerts : null;
- if (a === null || b === null) return a === b;
- return a.length === b.length && a.every((al, i) => (
- al.title === b[i]?.title
- && al.severity === b[i]?.severity
- && al.detail === b[i]?.detail
- && al.type === b[i]?.type
- && al.link === b[i]?.link
- ));
- },
+ compare: (prev, next) =>
+ equalByKeys(prev.counts, next.counts, ['total', 'critical', 'high', 'medium'])
+ && equalListByKeys(prev.alerts, next.alerts, [
+ 'title', 'severity', 'detail', 'type', 'link',
+ ]),
},
);
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index d491251e91..a489f56d6f 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -59,6 +59,7 @@ grep -i "what you want to do" client/src/lib/README.md
|---|---|
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup. Wired from `main.jsx`; never call directly from React components. |
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
+| `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |
| `genUtils.js` | Shared bits between Image Gen and Video Gen pages. |
| `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. |
| `loopbackHost.js` | `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or `getUserMedia`-gated surface; matches the full `127.0.0.0/8` range, IPv6 `::1`, and the browser-bracketed `[::1]` form. |
diff --git a/client/src/lib/compareHelpers.js b/client/src/lib/compareHelpers.js
new file mode 100644
index 0000000000..232995212d
--- /dev/null
+++ b/client/src/lib/compareHelpers.js
@@ -0,0 +1,34 @@
+// Key-based equality helpers for `useAutoRefetch`'s `compare` option — the
+// "skip the re-render when nothing the widget renders changed" pattern. These
+// are the typed alternative to `sameJsonShape` (JSON.stringify equality):
+// reach for these when only a known subset of fields drives the render, so a
+// monotonic mtime/timestamp nudge or an unrendered field can't break dedup.
+//
+// A "key" is either:
+// - a string property name (`'status'`),
+// - a dotted path (`'context.running'`) — each segment is read with
+// optional chaining, so a missing intermediate object reads as undefined, or
+// - a function `(item) => value` for derived comparisons (e.g. a normalized
+// `(d) => d?.count ?? 1`, or a helper like `getLastProgressDate`).
+
+const valueAt = (obj, key) => {
+ if (typeof key === 'function') return key(obj);
+ if (key.includes('.')) return key.split('.').reduce((acc, part) => acc?.[part], obj);
+ return obj?.[key];
+};
+
+// True when `a` and `b` are equal (`===`) on every key. Null/undefined-safe:
+// a missing object reads each key as undefined, mirroring `a?.key`.
+export const equalByKeys = (a, b, keys) =>
+ keys.every((key) => valueAt(a, key) === valueAt(b, key));
+
+// True when `a` and `b` are arrays of equal length whose items are pairwise
+// equal on every key. Non-arrays fall back to identity (`a === b`), matching
+// the `Array.isArray(x) ? x : null` guard the inline callers used.
+export const equalListByKeys = (a, b, keys) => {
+ const aArr = Array.isArray(a) ? a : null;
+ const bArr = Array.isArray(b) ? b : null;
+ if (aArr === null || bArr === null) return aArr === bArr;
+ if (aArr.length !== bArr.length) return false;
+ return aArr.every((item, i) => equalByKeys(item, bArr[i], keys));
+};
diff --git a/client/src/lib/compareHelpers.test.js b/client/src/lib/compareHelpers.test.js
new file mode 100644
index 0000000000..40f68203c7
--- /dev/null
+++ b/client/src/lib/compareHelpers.test.js
@@ -0,0 +1,103 @@
+import { describe, it, expect } from 'vitest';
+import { equalByKeys, equalListByKeys } from './compareHelpers.js';
+
+describe('equalByKeys', () => {
+ it('returns true when every listed key matches', () => {
+ expect(equalByKeys(
+ { status: 'ok', lastRun: '2026-05-24', extra: 1 },
+ { status: 'ok', lastRun: '2026-05-24', extra: 999 },
+ ['status', 'lastRun'],
+ )).toBe(true);
+ });
+
+ it('returns false when a listed key differs', () => {
+ expect(equalByKeys({ status: 'ok' }, { status: 'error' }, ['status'])).toBe(false);
+ });
+
+ it('ignores unlisted keys', () => {
+ expect(equalByKeys({ a: 1, b: 2 }, { a: 1, b: 3 }, ['a'])).toBe(true);
+ });
+
+ it('reads dotted paths with optional chaining', () => {
+ expect(equalByKeys(
+ { counts: { total: 3 } },
+ { counts: { total: 3 } },
+ ['counts.total'],
+ )).toBe(true);
+ expect(equalByKeys(
+ { counts: { total: 3 } },
+ { counts: { total: 4 } },
+ ['counts.total'],
+ )).toBe(false);
+ });
+
+ it('treats a missing intermediate object as undefined (both missing = equal)', () => {
+ expect(equalByKeys({}, {}, ['counts.total'])).toBe(true);
+ expect(equalByKeys({ counts: { total: 1 } }, {}, ['counts.total'])).toBe(false);
+ });
+
+ it('is null/undefined-safe on the top-level objects', () => {
+ expect(equalByKeys(undefined, undefined, ['total'])).toBe(true);
+ expect(equalByKeys(undefined, { total: 1 }, ['total'])).toBe(false);
+ });
+
+ it('supports function keys for derived comparisons', () => {
+ const normCount = (d) => d?.count ?? 1;
+ expect(equalByKeys({ count: undefined }, { count: 1 }, [normCount])).toBe(true);
+ expect(equalByKeys({ count: 2 }, { count: 1 }, [normCount])).toBe(false);
+ });
+});
+
+describe('equalListByKeys', () => {
+ it('returns true for arrays of equal length with matching items', () => {
+ expect(equalListByKeys(
+ [{ id: 'a', n: 1 }, { id: 'b', n: 2 }],
+ [{ id: 'a', n: 1 }, { id: 'b', n: 2 }],
+ ['id', 'n'],
+ )).toBe(true);
+ });
+
+ it('returns false on length mismatch', () => {
+ expect(equalListByKeys([{ id: 'a' }], [{ id: 'a' }, { id: 'b' }], ['id'])).toBe(false);
+ });
+
+ it('returns false when any item differs on a key', () => {
+ expect(equalListByKeys(
+ [{ id: 'a' }, { id: 'b' }],
+ [{ id: 'a' }, { id: 'c' }],
+ ['id'],
+ )).toBe(false);
+ });
+
+ it('ignores unlisted item fields', () => {
+ expect(equalListByKeys(
+ [{ id: 'a', mtime: 1 }],
+ [{ id: 'a', mtime: 99 }],
+ ['id'],
+ )).toBe(true);
+ });
+
+ it('compares nested item fields via dotted paths', () => {
+ expect(equalListByKeys(
+ [{ id: 'a', context: { running: 2 } }],
+ [{ id: 'a', context: { running: 2 } }],
+ ['id', 'context.running'],
+ )).toBe(true);
+ expect(equalListByKeys(
+ [{ id: 'a', context: { running: 2 } }],
+ [{ id: 'a', context: { running: 3 } }],
+ ['id', 'context.running'],
+ )).toBe(false);
+ });
+
+ it('falls back to identity for non-arrays', () => {
+ expect(equalListByKeys(null, null, ['id'])).toBe(true);
+ expect(equalListByKeys(undefined, undefined, ['id'])).toBe(true);
+ expect(equalListByKeys(null, [{ id: 'a' }], ['id'])).toBe(false);
+ expect(equalListByKeys([{ id: 'a' }], null, ['id'])).toBe(false);
+ });
+
+ it('treats two empty arrays as equal', () => {
+ expect(equalListByKeys([], [], ['id'])).toBe(true);
+ });
+});
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 613c65a7fe..31cf84df48 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -30,6 +30,7 @@ export * from './graphSimulation.js';
// === Generic UI / collection utilities ===
export * from './clientErrorReporter.js';
export * from './clipboard.js';
+export * from './compareHelpers.js';
export * from './genUtils.js';
export * from './joinInfluenceList.js';
export * from './loopbackHost.js';