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
fix: stop a slow search or subject read from overwriting a newer one
Adam Eivy4ac6b270492f
diff --git a/client/src/components/messages/IMessageTab.jsx b/client/src/components/messages/IMessageTab.jsxindex 2f81c8fe81..2292d6fed5 100644--- a/client/src/components/messages/IMessageTab.jsx+++ b/client/src/components/messages/IMessageTab.jsx@@ -11,6 +11,7 @@ import * as api from '../../services/api';import { formatClockTime, formatCount, timeAgo, formatDateNumeric } from '../../utils/formatters';import useDrawerTab from '../../hooks/useDrawerTab';import { IMessageSettingsPanel } from './IMessageSettingsPanel';+import useLatestRequest from '../../hooks/useLatestRequest';// Comms → Messages → iMessage (#2413). Browse / manage PortOS-side activity// ingested from macOS chat.db. Deletes and blocklists never write Apple's Messages database.@@ -470,16 +471,19 @@ export default function IMessageTab() {return () => clearTimeout(t);}, [query]);+ const beginListRequest = useLatestRequest();const loadList = useCallback(async () => {+ const isCurrent = beginListRequest();setListLoading(true);const [statsRes, convRes] = await Promise.all([api.getImessageStats({ silent: true }).catch(() => null),api.getImessageConversations({ q: debouncedQ || undefined, silent: true }).catch(() => null),]);+ if (!isCurrent()) return;setStats(statsRes);setConversations(convRes?.conversations || []);setListLoading(false);- }, [debouncedQ]);+ }, [debouncedQ, beginListRequest]);useEffect(() => {loadList();diff --git a/client/src/components/messages/InboxTab.jsx b/client/src/components/messages/InboxTab.jsxindex ef4d92fb5d..9dffa419da 100644--- a/client/src/components/messages/InboxTab.jsx+++ b/client/src/components/messages/InboxTab.jsx@@ -11,6 +11,7 @@ import MessageDetail from './MessageDetail';import AddToThreadButton from '../threads/AddToThreadButton';import { messageReadState, partitionAccountsBySyncMode } from '../../lib/messageSyncModes';import LoadFailedState from '../ui/LoadFailedState';+import useLatestRequest from '../../hooks/useLatestRequest';const ACTION_CONFIG = {reply: { icon: Reply, color: 'text-port-accent', bg: 'bg-port-accent/10', hoverBg: 'hover:bg-port-accent/20', label: 'Reply' },@@ -229,16 +230,21 @@ export default function InboxTab({ accounts }) {return () => clearTimeout(debounceRef.current);}, [search]);+ // A fast typist fires overlapping searches; an older, slower response must not+ // replace the list for the query now in the box.+ const beginRequest = useLatestRequest();const fetchMessages = useCallback(async () => {+ const isCurrent = beginRequest();setLoading(true);const params = { summary: true };if (selectedAccount) params.accountId = selectedAccount;if (debouncedSearch) params.search = debouncedSearch;const result = await api.getMessageInbox(params, { silent: true }).catch(() => null);+ if (!isCurrent()) return;setLoadFailed(result === null);if (result) setMessages(result.messages || []);setLoading(false);- }, [selectedAccount, debouncedSearch]);+ }, [selectedAccount, debouncedSearch, beginRequest]);useEffect(() => {fetchMessages();diff --git a/client/src/components/privacy/PrivacyBrokersTab.jsx b/client/src/components/privacy/PrivacyBrokersTab.jsxindex 0fcf66d5a3..1ae2164f91 100644--- a/client/src/components/privacy/PrivacyBrokersTab.jsx+++ b/client/src/components/privacy/PrivacyBrokersTab.jsx@@ -21,6 +21,7 @@ import {import { isHttpUrl } from '../../utils/urlNormalize';import CronSchedulePicker from '../CronSchedulePicker';import Banner from '../ui/Banner';+import useLatestRequest from '../../hooks/useLatestRequest';// Digest action icon by descriptor `icon` token (positive resolution vs dismiss).const ACTION_ICONS = { check: CheckCircle2, x: XCircle };@@ -51,18 +52,21 @@ export default function PrivacyBrokersTab({ subjectId, consentScopes, onManageCo// Cases, exposure counts, and the digest are per-subject — `load` is also the// post-action refresh, so it runs after every scan/recheck/transition.+ const beginRequest = useLatestRequest();const load = useCallback(() => {+ const isCurrent = beginRequest();setLoading(true);Promise.allSettled([getPrivacyScanStatus({ subjectId }), getPrivacyBrokerCases(undefined, { subjectId }),getPrivacyOptOutDigest({ subjectId }),]).then(([s, c, d]) => {+ if (!isCurrent()) return;setScanStatus(s.status === 'fulfilled' ? s.value : { enabledBrokers: 0, caseCounts: {}, dueForRecheck: 0 });setCases(c.status === 'fulfilled' ? c.value : []);setDigest(d.status === 'fulfilled' ? d.value : { total: 0, humanTasks: 0, blocked: 0, items: [] });setLoading(false);});- }, [subjectId]);+ }, [subjectId, beginRequest]);useEffect(() => { load(); }, [load]);diff --git a/client/src/components/privacy/PrivacyChangesTab.jsx b/client/src/components/privacy/PrivacyChangesTab.jsxindex 721146b134..a1bff436c8 100644--- a/client/src/components/privacy/PrivacyChangesTab.jsx+++ b/client/src/components/privacy/PrivacyChangesTab.jsx@@ -11,6 +11,7 @@ import DeclareChangeDrawer from './DeclareChangeDrawer';import { VAULT_TYPES, CHANGE_KINDS, labelFor } from './constants';import { isHttpUrl } from '../../utils/urlNormalize';import { formatDateNumeric } from '../../utils/formatters';+import useLatestRequest from '../../hooks/useLatestRequest';// A slim progress bar over pending/updated/removed. Done = zero pending.function ProgressBar({ progress }) {@@ -114,18 +115,21 @@ export default function PrivacyChangesTab({ subjectId }) {const [detail, setDetail] = useState(null); // { event, oldRecord, replacementRecord, progress }const [detailLoading, setDetailLoading] = useState(false);+ const beginRequest = useLatestRequest();const load = useCallback(() => {+ const isCurrent = beginRequest();setLoading(true);// A change event inherits its subject from the vault record it replaces, so// scoping the record list is what keeps the Declare form on one person.Promise.allSettled([getPrivacyChanges({ subjectId }), getVaultRecords(undefined, { subjectId }),]).then(([e, v]) => {+ if (!isCurrent()) return;setEvents(e.status === 'fulfilled' ? e.value : []);setVaultRecords(v.status === 'fulfilled' ? v.value : []);setLoading(false);});- }, [subjectId]);+ }, [subjectId, beginRequest]);useEffect(() => { load(); }, [load]);diff --git a/client/src/components/privacy/PrivacyOrgsTab.jsx b/client/src/components/privacy/PrivacyOrgsTab.jsxindex fbbdc8ab9c..96d353567f 100644--- a/client/src/components/privacy/PrivacyOrgsTab.jsx+++ b/client/src/components/privacy/PrivacyOrgsTab.jsx@@ -11,6 +11,7 @@ import {TRUST_TONE, HOLDING_TONE, labelFor,} from './constants';import { isHttpUrl } from '../../utils/urlNormalize';+import useLatestRequest from '../../hooks/useLatestRequest';// Filter chip row — a single-select toggle group over a list of {id,label}.function ChipFilter({ label, options, value, onChange }) {@@ -46,28 +47,31 @@ export default function PrivacyOrgsTab({ subjectId }) {const [editing, setEditing] = useState(null);const [confirmDelete, setConfirmDelete] = useState(null);+ const beginRequest = useLatestRequest();const load = useCallback(() => {+ const isCurrent = beginRequest();setLoading(true);// Holdings depend only on the org list, so they chain off it directly — the// vault read runs alongside rather than gating the fan-out.const orgsThenHoldings = getPrivacyOrgs({}, { subjectId }).then(async (orgList) => {+ if (!isCurrent()) return;setOrgs(orgList);// One request per org (single-user scale — a handful of orgs).const entries = await Promise.all(orgList.map(async (org) => {const h = await getOrgHoldings(org.id, { silent: true }).catch(() => []);return [org.id, h || []];}));- setHoldingsByOrg(Object.fromEntries(entries));+ if (isCurrent()) setHoldingsByOrg(Object.fromEntries(entries));})- .catch(() => { setOrgs([]); setHoldingsByOrg({}); });+ .catch(() => { if (isCurrent()) { setOrgs([]); setHoldingsByOrg({}); } });const vault = getVaultRecords(undefined, { subjectId })- .then((v) => setVaultRecords(v || []))- .catch(() => setVaultRecords([]));+ .then((v) => { if (isCurrent()) setVaultRecords(v || []); })+ .catch(() => { if (isCurrent()) setVaultRecords([]); });- Promise.all([orgsThenHoldings, vault]).then(() => setLoading(false));- }, [subjectId]);+ Promise.all([orgsThenHoldings, vault]).then(() => { if (isCurrent()) setLoading(false); });+ }, [subjectId, beginRequest]);useEffect(() => { load(); }, [load]);diff --git a/client/src/components/privacy/PrivacyVaultTab.jsx b/client/src/components/privacy/PrivacyVaultTab.jsxindex b03cad7a3a..2741a34966 100644--- a/client/src/components/privacy/PrivacyVaultTab.jsx+++ b/client/src/components/privacy/PrivacyVaultTab.jsx@@ -7,6 +7,7 @@ import toast from '../ui/Toast';import InlineConfirmRow from '../ui/InlineConfirmRow';import VaultRecordDrawer from './VaultRecordDrawer';import { VAULT_TYPES, SENSITIVE_TYPES } from './constants';+import useLatestRequest from '../../hooks/useLatestRequest';// Toggle switch for share_with_twin / use_for_scans — optimistic PATCH, reverts// on failure. Disabled + off for the toggle when the type forbids it.@@ -28,16 +29,21 @@ export default function PrivacyVaultTab({ subjectId }) {const [confirmDelete, setConfirmDelete] = useState(null);const [keyConfigured, setKeyConfigured] = useState(true);+ // `?subject=` switches reuse this mounted tab: without the guard a slow read+ // for the previous subject lands last and shows their records under this one.+ const beginRequest = useLatestRequest();const load = useCallback(() => {+ const isCurrent = beginRequest();setLoading(true);Promise.allSettled([getVaultRecords(undefined, { subjectId }), getPrivacyStatus({ subjectId }),]).then(([recs, status]) => {+ if (!isCurrent()) return;setRecords(recs.status === 'fulfilled' ? recs.value : []);if (status.status === 'fulfilled') setKeyConfigured(status.value.keyConfigured !== false);setLoading(false);});- }, [subjectId]);+ }, [subjectId, beginRequest]);useEffect(() => { load(); }, [load]);diff --git a/client/src/components/privacy/PrivacyVaultTab.test.jsx b/client/src/components/privacy/PrivacyVaultTab.test.jsxnew file mode 100644index 0000000000..9bc44dbcb2--- /dev/null+++ b/client/src/components/privacy/PrivacyVaultTab.test.jsx@@ -0,0 +1,46 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';++const api = vi.hoisted(() => ({+ getVaultRecords: vi.fn(),+ getPrivacyStatus: vi.fn(),+ deleteVaultRecord: vi.fn(),+ revealVaultRecord: vi.fn(),+ updateVaultRecord: vi.fn(),+}));+vi.mock('../../services/api', () => api);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));+vi.mock('./VaultRecordDrawer', () => ({ default: () => null }));++import PrivacyVaultTab from './PrivacyVaultTab';++const record = (label) => ({ id: label, label, type: 'email', status: 'current', maskedValue: '••••' });+const deferred = () => {+ let resolve;+ const promise = new Promise((r) => { resolve = r; });+ return { promise, resolve };+};++describe('PrivacyVaultTab subject switching', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getPrivacyStatus.mockResolvedValue({ keyConfigured: true });+ });++ it('drops a slow read for the previous subject that lands after the new subject loaded', async () => {+ const slowA = deferred();+ api.getVaultRecords.mockImplementation((_type, { subjectId }) => (+ subjectId === 'subject-a' ? slowA.promise : Promise.resolve([record('Record for B')])+ ));++ const { rerender } = render(<PrivacyVaultTab subjectId="subject-a" />);+ rerender(<PrivacyVaultTab subjectId="subject-b" />);+ await waitFor(() => expect(screen.getByText('Record for B')).toBeTruthy());++ slowA.resolve([record('Record for A')]);+ await new Promise((r) => setTimeout(r, 0));++ expect(screen.queryByText('Record for A')).toBeNull();+ expect(screen.getByText('Record for B')).toBeTruthy();+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8c6b7733fe..f3639d1bdc 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -101,6 +101,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. || `useCharacterAugmentation` | The propose → tick → selectively-apply loop for cast-integrity character augmentation (#6417): owns `preview`/`accepted`/`proposing`/`applying` and enforces the rules both surfaces share — nothing accepted until ticked, "no improvement offered" is a success not an error, and a lock stops the flow at propose AND at apply. Caller supplies only the two request thunks and an `onApplied`. | A surface that augments character framework fields — Universe cast panel and the Writers Room Cast pane both use it; do not re-roll the state machine. || `useMaintenance` | Server-confirmed maintenance status and `refresh`. | Admission hold, blockers, and reconnect invalidation. |+| `useLatestRequest` | `begin()` → `isCurrent()`: a latest-request-wins guard. Each `begin()` supersedes earlier requests (and unmount supersedes all), so an older response resolving late can see `isCurrent() === false` and drop its setState. | A load keyed on changing input (a debounced search, a `?subject=` route param) where responses can arrive out of order and overwrite the view the user has already moved to. || `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. || `useMemoRecorder` | Owns one memo recorder through permission prompts, stop/cancel, and unmount; exposes `{ recording, starting, start, stop, cancel, stream }`. | Catalog voice memos and song takes. || `usePortosRestartWatch` | Watches PortOS restarting ITSELF and reloads the page once it answers again: arms on the update stream's restart step, on `portos:update:complete`, or on a socket disconnect confirmed unreachable, then polls `/api/system/health` for a version change, a down→up dip, or an uptime reset. `update.sh` pm2-deletes the server mid-run, so there is no completion event to await. | Only a surface that launches a PortOS self-update WITHOUT going through an app operation — today just the Update page. `useAppOperation` already wires it, so App Management surfaces read `restarting` from there instead. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 0e9fc5a35d..f27fcf0244 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -87,6 +87,7 @@ export { default as useBeeperRealtime } from './useBeeperRealtime.js';export { default as useMoltworldWs } from './useMoltworldWs.js';export { default as useCharacterAugmentation } from './useCharacterAugmentation.js';export { useMaintenance } from './useMaintenance.js';+export { default as useLatestRequest } from './useLatestRequest.js';export { default as useMounted } from './useMounted.js';export { default as useMemoRecorder } from './useMemoRecorder.js';export { default as usePendingListRows } from './usePendingListRows.js';diff --git a/client/src/hooks/useLatestRequest.js b/client/src/hooks/useLatestRequest.jsnew file mode 100644index 0000000000..1296fd865d--- /dev/null+++ b/client/src/hooks/useLatestRequest.js@@ -0,0 +1,19 @@+import { useCallback, useEffect, useRef } from 'react';++// Latest-request-wins guard for a load keyed on changing input (a search box, a+// route param like the active privacy subject). `begin()` supersedes every+// earlier request and returns an `isCurrent()` predicate; an older response+// that resolves after a newer request started (or after unmount) reads+// `isCurrent() === false` and must drop its setState, so it can't overwrite the+// view the user has already moved on to.+//+// Counter-based, so React StrictMode's mount→cleanup→remount cycle needs no+// re-arm: the remount's effect simply calls `begin()` again.+export default function useLatestRequest() {+ const generationRef = useRef(0);+ useEffect(() => () => { generationRef.current += 1; }, []);+ return useCallback(() => {+ const generation = ++generationRef.current;+ return () => generation === generationRef.current;+ }, []);+}diff --git a/client/src/hooks/useLatestRequest.test.jsx b/client/src/hooks/useLatestRequest.test.jsxnew file mode 100644index 0000000000..aa6f1ab551--- /dev/null+++ b/client/src/hooks/useLatestRequest.test.jsx@@ -0,0 +1,21 @@+import { describe, it, expect } from 'vitest';+import { renderHook } from '@testing-library/react';+import useLatestRequest from './useLatestRequest.js';++describe('useLatestRequest', () => {+ it('only the most recently begun request is current', () => {+ const { result } = renderHook(() => useLatestRequest());+ const first = result.current();+ expect(first()).toBe(true);+ const second = result.current();+ expect(first()).toBe(false);+ expect(second()).toBe(true);+ });++ it('invalidates an in-flight request on unmount', () => {+ const { result, unmount } = renderHook(() => useLatestRequest());+ const inFlight = result.current();+ unmount();+ expect(inFlight()).toBe(false);+ });+});