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: collapse deleted Brain records without reloading the list
[._.]/ Adam Eivyfa6f666626a3
diff --git a/client/src/AGENTS.md b/client/src/AGENTS.mdindex 4287231473..fda00c0555 100644--- a/client/src/AGENTS.md+++ b/client/src/AGENTS.md@@ -27,6 +27,7 @@ These apply to React/Vite client code. Universal constraints (functional program- **No local binding shadows a timer or `fetch`** - a `useState` pair, `useCallback`, or `const` named `setInterval` / `setTimeout` / `clearInterval` / `clearTimeout` / `requestAnimationFrame` / `cancelAnimationFrame` / `fetch` shadows that global for the whole component body, so a timer or fetch added to the same scope later silently calls the local instead — no throw, no lint error, just a state setter that stores a callback (#5728). Name the binding for what it holds (`intervalPreset`, `timeoutMinutes`, `loadRefs`). Enforced tree-wide by `client/src/globalShadowConventions.test.js`, which has no allowlist; idiomatic React state like `[open, setOpen]` / `[status, setStatus]` is deliberately out of scope because nothing here calls those globals bare.- **An async effect keyed to a switchable identity drops a superseded response** - an effect that fetches on a dependency and writes the answer into state needs a disposal guard: `let active = true;` at the top, every `set*` gated on it, `return () => { active = false; };`. Without it, switching the record faster than the request resolves renders the previous record's data under the current one — and it does not self-correct where the value is passed down as a controlled prop, so `WorkEditor` enriched one work's persisted storyboard images with another's characters and places (#7242, after #6996–#7000 were each fixed as a single site). **`useMounted()` does not cover this** — the component never unmounted, only its subject changed. Where the response must be matched against the newest request rather than merely dropped — notably when the effect writes a state value that is itself in its own dependency array, so a lifetime-scoped flag would be flipped by its own cleanup — bump and compare a generation ref instead (`IngredientPicker.jsx`). Enforced tree-wide by `client/src/asyncEffectDisposalConventions.test.js`, which allowlists the few deps that cannot select a different record (a drawer `open` flag, a once-only latch).- **User-facing counts and amounts go through `formatCount` / `formatUsd`** (`utils/formatters.js`) — thousands-grouped and en-US-pinned (`2,762`, `$4,610.09`). An unseparated `4610` is read at the wrong order of magnitude, and a bare `.toLocaleString()` follows the browser locale, which then disagrees with the `$` beside it. A **measured** zero already renders `0`; `formatCount` gives `—` only for a value that is missing or unparseable, so pass `{ fallback: '0' }` just where an ABSENT count should still read as zero. Enforced tree-wide by `client/src/numberFormattingConventions.test.js` — any new bare `.toLocaleString(` call under `client/src` fails CI. Other formatters (`formatBytes`, `timeAgo`, …) live beside them — see the helper catalog in the root `AGENTS.md`.+- **List deletion preserves place** — after the server confirms success, collapse the affected row and its spacing with `components/ui/CollapsibleListItem`, then remove it from local state. Keep the list/scroll container mounted, retain filters and pagination, and refresh counts separately. Never replace populated content with a loading placeholder for a deletion. Keep failures visible, guard duplicate requests, honor reduced motion, and move focus to a surviving row/container with `preventScroll`. Put spacing inside the collapsing wrapper rather than parent gaps.- **Reactive UI updates** - after mutations (delete, create, update), update local state directly instead of refetching the entire list from the server. Use `setState(prev => prev.filter(...))` or similar patterns for immediate feedback## API errors and save gatingdiff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsxindex 4a44749e7f..9ff42969af 100644--- a/client/src/components/brain/tabs/MemoryTab.jsx+++ b/client/src/components/brain/tabs/MemoryTab.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback, useMemo } from 'react';+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';import { useNavigate, useParams, useLocation } from 'react-router';import * as api from '../../../services/api';import {Plus,@@ -28,6 +28,7 @@ import { timeAgo, formatDateNumeric } from '../../../utils/formatters';import BrailleSpinner from '../../BrailleSpinner';import InlineConfirmRow from '../../ui/InlineConfirmRow';import CopyableId from '../../ui/CopyableId';+import CollapsibleListItem from '../../ui/CollapsibleListItem';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';// Progressive list: imported ChatGPT corpora routinely top 1k+ records with@@ -62,6 +63,11 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {const closeReader = () => navigate(basePath + location.search);const [activeType, setActiveType] = useState(fixedType || recordType || 'memories');const [records, setRecords] = useState([]);+ const [removingIds, setRemovingIds] = useState(new Set());+ const pendingDeletes = useRef(new Set());+ const currentType = useRef(activeType);+ currentType.current = activeType;+ const fetchGeneration = useRef(0);const [loading, setLoading] = useState(true);const [editingId, setEditingId] = useState(null);const [editForm, setEditForm] = useState({});@@ -75,13 +81,14 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {if (recordType && MEMORY_TABS.some(tab => tab.id === recordType)) setActiveType(recordType);}, [recordType]);const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE);- const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();+ const { isConfirming, requestDelete, cancelDelete } = useConfirmDelete();useEffect(() => {if (fixedType) setActiveType(fixedType);}, [fixedType]);const fetchRecords = useCallback(async () => {+ const generation = ++fetchGeneration.current;setLoading(true);let data = [];@@ -105,6 +112,7 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {break;}+ if (generation !== fetchGeneration.current) return;// Filter out archived recordsdata = data.filter(r => !r.archived);setRecords(data);@@ -113,6 +121,7 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {useEffect(() => {fetchRecords();+ return () => { fetchGeneration.current += 1; };}, [fetchRecords]);const fetchBackendStatus = useCallback(() => {@@ -134,13 +143,14 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {const q = searchQuery.toLowerCase();if (!q) return records;return records.filter((r) => {+ if (removingIds.has(`${activeType}:${r.id}`)) return true;const fields = [r.name, r.title, r.context, r.content, r.notes, r.oneLiner,r.nextAction, r.mood, ...(r.tags || []), ...(r.followUps || []),];return fields.some((f) => f?.toLowerCase().includes(q));});- }, [records, searchQuery]);+ }, [records, searchQuery, removingIds, activeType]);const handleSave = async () => {let result;@@ -237,6 +247,9 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {};const handleDelete = async (id) => {+ const key = `${activeType}:${id}`;+ if (pendingDeletes.current.has(key)) return;+ pendingDeletes.current.add(key);let failed = false;switch (activeType) {case 'people':@@ -271,10 +284,11 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {break;}- if (!failed) {+ pendingDeletes.current.delete(key);+ if (!failed && currentType.current === activeType) {toast.success('Deleted');if (recordId === id) closeReader();- fetchRecords();+ setRemovingIds(previous => new Set(previous).add(key));onRefresh?.();}};@@ -728,7 +742,7 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {question="Delete this entry? This cannot be undone."confirmTitle="Confirm delete"cancelTitle="Cancel delete"- onConfirm={() => confirmDelete(() => handleDelete(record.id))}+ onConfirm={() => handleDelete(record.id)}onCancel={cancelDelete}/>)}@@ -886,8 +900,21 @@ export default function MemoryTab({ onRefresh, fixedType = null }) {: `No ${DESTINATIONS[activeType]?.label?.toLowerCase() || 'records'} yet. Add one or capture thoughts in the Inbox.`}</p>) : (- <div className="space-y-2">- {filteredRecords.slice(0, visibleCount).map(record => renderRecord(record))}+ <div>+ {filteredRecords.filter((record, index) => index < visibleCount || removingIds.has(`${activeType}:${record.id}`)).map(record => (+ <CollapsibleListItem key={`${activeType}:${record.id}`}+ removing={removingIds.has(`${activeType}:${record.id}`)}+ onExited={() => {+ setRecords(previous => previous.filter(item => item.id !== record.id));+ setRemovingIds(previous => {+ const next = new Set(previous);+ next.delete(`${activeType}:${record.id}`);+ return next;+ });+ }}>+ {renderRecord(record)}+ </CollapsibleListItem>+ ))}{filteredRecords.length > visibleCount && (<buttontype="button"diff --git a/client/src/components/brain/tabs/MemoryTab.reader.test.jsx b/client/src/components/brain/tabs/MemoryTab.reader.test.jsxindex 9a43638c48..811c955ec7 100644--- a/client/src/components/brain/tabs/MemoryTab.reader.test.jsx+++ b/client/src/components/brain/tabs/MemoryTab.reader.test.jsx@@ -5,7 +5,7 @@ import MemoryTab from './MemoryTab';const api = vi.hoisted(() => ({getBrainMemories: vi.fn(), getMemoryBackendStatus: vi.fn().mockResolvedValue({ backend: 'postgres' }),- getChatgptArchive: vi.fn()+ getChatgptArchive: vi.fn(), deleteBrainMemory: vi.fn()}));vi.mock('../../../services/api', () => api);vi.mock('../../../services/apiBrain', () => api);@@ -103,3 +103,51 @@ describe('Brain memory reader', () => {expect(screen.queryByRole('dialog')).toBeNull();});});+++describe('Brain deletion preserves the list', () => {+ it('waits for success, collapses only the deleted row and keeps search and siblings mounted', async () => {+ let resolveDelete;+ api.deleteBrainMemory.mockImplementation(() => new Promise(resolve => { resolveDelete = resolve; }));+ api.getBrainMemories.mockResolvedValue([+ { id: 'example-a', title: 'Example first' }, { id: 'example-b', title: 'Example second' }+ ]);+ mount();+ const first = await screen.findByRole('button', { name: 'Read Example first' });+ const second = screen.getByRole('button', { name: 'Read Example second' });+ const region = screen.getByRole('region', { name: 'Memory entries' });+ const search = screen.getByRole('textbox', { name: /Search/ });+ fireEvent.change(search, { target: { value: 'Example' } });+ fireEvent.click(screen.getAllByRole('button', { name: 'Delete', exact: true })[0]);+ const confirm = screen.getByTitle('Confirm delete');+ confirm.focus();+ fireEvent.click(confirm);+ fireEvent.click(confirm);+ expect(api.deleteBrainMemory).toHaveBeenCalledTimes(1);+ expect(first.isConnected).toBe(true);+ resolveDelete({});+ await waitFor(() => expect(first.closest('[inert]')).toBeTruthy());+ expect(second.isConnected).toBe(true);+ await waitFor(() => expect(first.isConnected).toBe(false));+ expect(document.activeElement.contains(second)).toBe(true);+ expect(screen.getByRole('region', { name: 'Memory entries' })).toBe(region);+ expect(screen.getByRole('button', { name: 'Read Example second' })).toBe(second);+ expect(search.value).toBe('Example');+ expect(api.getBrainMemories).toHaveBeenCalledTimes(1);+ });++ it('keeps a failed deletion visible and allows retry with reduced motion', async () => {+ vi.stubGlobal('matchMedia', () => ({ matches: true, addEventListener() {}, removeEventListener() {} }));+ api.getBrainMemories.mockResolvedValue([{ id: 'example-a', title: 'Example first' }]);+ api.deleteBrainMemory.mockRejectedValueOnce(new Error('Example failure')).mockResolvedValueOnce({});+ mount();+ await screen.findByRole('button', { name: 'Read Example first' });+ fireEvent.click(screen.getByRole('button', { name: 'Delete', exact: true }));+ fireEvent.click(screen.getByTitle('Confirm delete'));+ await waitFor(() => expect(api.deleteBrainMemory).toHaveBeenCalledTimes(1));+ expect(screen.getByRole('button', { name: 'Read Example first' }).closest('[inert]')).toBeNull();+ fireEvent.click(screen.getByTitle('Confirm delete'));+ await waitFor(() => expect(screen.getByText(/No memories yet/)).toBeTruthy());+ expect(api.getBrainMemories).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/components/ui/CollapsibleListItem.jsx b/client/src/components/ui/CollapsibleListItem.jsxnew file mode 100644index 0000000000..43fd57edba--- /dev/null+++ b/client/src/components/ui/CollapsibleListItem.jsx@@ -0,0 +1,37 @@+import { useEffect, useRef } from 'react';+import usePrefersReducedMotion from '../../hooks/usePrefersReducedMotion';++/** Keep the row mounted until its successful deletion has collapsed its space.+ * Put row spacing INSIDE this wrapper (paddingBottom), never on the parent gap.+ */+export default function CollapsibleListItem({ removing, onExited, children, spacing = '0.5rem' }) {+ const elementRef = useRef(null);+ const exitRef = useRef(onExited);+ exitRef.current = onExited;+ const reducedMotion = usePrefersReducedMotion();++ useEffect(() => {+ if (!removing) return undefined;+ const element = elementRef.current;+ if (element.contains(document.activeElement)) {+ const siblings = [...element.parentElement.children];+ const destination = siblings.slice(siblings.indexOf(element) + 1).find(sibling => !sibling.inert)+ || siblings.reverse().find(sibling => sibling !== element && !sibling.inert)+ || element.parentElement.closest('[tabindex]');+ destination?.focus({ preventScroll: true });+ }+ // A timer is also the fallback when transitions don't fire (hidden tabs).+ const timer = setTimeout(() => exitRef.current(), reducedMotion ? 0 : 200);+ return () => clearTimeout(timer);+ }, [removing, reducedMotion]);++ return (+ <div ref={elementRef} tabIndex={-1} inert={removing || undefined}+ className="grid transition-[grid-template-rows,opacity] duration-200 ease-out motion-reduce:transition-none"+ style={{ gridTemplateRows: removing ? '0fr' : '1fr', opacity: removing ? 0 : 1 }}>+ <div className="min-h-0 overflow-hidden">+ <div style={{ paddingBottom: spacing }}>{children}</div>+ </div>+ </div>+ );+}diff --git a/client/src/components/ui/README.md b/client/src/components/ui/README.mdindex 3682d50317..28f5343aa9 100644--- a/client/src/components/ui/README.md+++ b/client/src/components/ui/README.md@@ -11,6 +11,7 @@ accessibility). Feature-specific components live under their own feature directo| `AutoSizeTextarea` | Controlled `<textarea>` that grows to fit its content — no internal scroll, no hand-resize. || `Banner` | Toned alert block (icon + content + actions) for warnings, errors, and info callouts. || `BeatPulse` | Metronome dot row — one dot per beat of the bar, the current one lit. |+| `CollapsibleListItem` | Successful-delete row collapse with reduced-motion support and focus transfer; set `removing`, then filter local state in `onExited`. Owns row spacing. || `CollapsibleSection` | Disclosure section header — chevron, leading icon, collapsed summary, `aria-expanded`/`aria-controls`; `keepMounted` hides the body instead of unmounting it. || `CollapsibleText` | Collapsed content preview with a show-more/less toggle — line-clamped `text`, or `children` capped by `maxHeight` when `line-clamp` can't (rendered markdown). || `ConfirmButtonPair` | Compact inline confirm/cancel pair for a destructive action in a dense control row. |diff --git a/docs/UX_DESIGN_GUIDE.md b/docs/UX_DESIGN_GUIDE.mdindex f30d6b2034..28658971a7 100644--- a/docs/UX_DESIGN_GUIDE.md+++ b/docs/UX_DESIGN_GUIDE.md@@ -248,3 +248,7 @@ The page families, spacing, navigation grouping, and pilot choices are PortOS de- [NN/g: Progressive disclosure](https://www.nngroup.com/articles/progressive-disclosure/) supports moving secondary detail behind explicit requests while keeping primary work clear. Disclosure does not justify hiding sibling destinations.- [W3C: Reflow](https://www.w3.org/WAI/WCAG22/Understanding/reflow.html) explains narrow-width/zoom reflow and the exception for two-dimensional tables within their own scroll region.- [WCAG 2.2](https://www.w3.org/TR/WCAG22/) supplies the accessibility baseline, including contrast, focus, keyboard access, labels, and target-size requirements. The 44px touch target above is a PortOS design default, not a claim that every WCAG AA target must be 44px.++## List deletion and reading position++Deleting an item keeps the populated list and its scroll container mounted. After server success, use `CollapsibleListItem` to fade and collapse the row, including its spacing, so following content slides up; remove the record locally on exit. Preserve search, filters, pagination and unrelated selection. Refresh summary counts separately. Keep failed deletions visible and actionable, prevent duplicate pending requests, honor reduced motion, and transfer keyboard focus without scrolling. Never show a whole-list loading placeholder as deletion feedback. Brain MemoryTab is the reference implementation across Memories, People, Projects, Ideas and Admin.