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
address review (claude): stop the filter row from hiding a just-created collection
[._.]/ Adam Eivycda143930b2c
diff --git a/client/src/pages/MediaCollections.jsx b/client/src/pages/MediaCollections.jsxindex 1b84a99638..3b7fcc4d2e 100644--- a/client/src/pages/MediaCollections.jsx+++ b/client/src/pages/MediaCollections.jsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link, useNavigate, useSearchParams } from 'react-router-dom';import { Plus, FolderOpen, Inbox, Trash2, Image as ImageIcon, Film, Search } from 'lucide-react';import toast from '../components/ui/Toast';@@ -102,6 +102,12 @@ export default function MediaCollections() {setCollections((prev) => [...prev, created]);setName('');toast.success(`Created "${created.name}"`);+ // A new collection is always empty, so with "Hide empty" on (the default)+ // it would be filtered straight back out and the create would read as+ // broken. Reveal the empties so the thing the user just made is visible.+ // (Referenced before its `const` in source order, but only ever called+ // from an event handler — well after the component body has run.)+ if (hideEmpty) updateParams({ empty: '1' });}};@@ -150,15 +156,20 @@ export default function MediaCollections() {const sort = normalizeCollectionSort(searchParams.get('sort'));const hideEmpty = searchParams.get('empty') !== '1';+ // react-router's functional `setSearchParams` updater is NOT latest-state: it+ // hands back the params captured in the closure at render time. A debounced+ // write armed before a sort/toggle change would therefore navigate with the+ // pre-change snapshot and silently drop the param the user just set. Read the+ // live params off a ref instead.+ const paramsRef = useRef(searchParams);+ paramsRef.current = searchParams;const updateParams = useCallback((patch, { replace = false } = {}) => {- setSearchParams((prev) => {- const next = new URLSearchParams(prev);- for (const [k, v] of Object.entries(patch)) {- if (v == null || v === '') next.delete(k);- else next.set(k, v);- }- return next;- }, { replace });+ const next = new URLSearchParams(paramsRef.current);+ for (const [k, v] of Object.entries(patch)) {+ if (v == null || v === '') next.delete(k);+ else next.set(k, v);+ }+ setSearchParams(next, { replace });}, [setSearchParams]);// Two-stage search (same shape as Catalog): `query` is what the user is@@ -280,7 +291,13 @@ export default function MediaCollections() {)}{visible.length === 0 ? (<div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center">- {query ? 'No collections match that search.' : 'No collections with items yet.'}+ {/* "No match" is only true when the search itself came up empty.+ When it matched rows that "Hide empty" then removed, saying+ that would contradict the "N empty hidden — Show" line above+ and send the user hunting for a collection that does exist. */}+ {matching.length === 0+ ? 'No collections match that search.'+ : 'Every collection here is empty — use Show above to see them.'}</div>) : (<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">diff --git a/client/src/pages/MediaCollections.test.jsx b/client/src/pages/MediaCollections.test.jsxindex f792f47007..a84cc27972 100644--- a/client/src/pages/MediaCollections.test.jsx+++ b/client/src/pages/MediaCollections.test.jsx@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { MemoryRouter } from 'react-router-dom';+import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom';// ── Mock API calls ───────────────────────────────────────────────────────────vi.mock('../services/api', () => ({@@ -53,10 +53,25 @@ vi.mock('../lib/unsorted', () => ({import MediaCollections from './MediaCollections';+// Surfaces the live URL search string and lets a test drive an EXTERNAL+// navigation (Back/Forward, a ⌘K deep-link) while the page stays mounted — the+// only way to exercise the adopt-the-URL effect.+function RouteProbe() {+ const location = useLocation();+ const navigate = useNavigate();+ return (+ <>+ <div data-testid="search-string">{location.search}</div>+ <button type="button" onClick={() => navigate('/media/collections?q=alpha')}>external nav</button>+ </>+ );+}+function renderPage(entry = '/media/collections') {return render(<MemoryRouter initialEntries={[entry]}><MediaCollections />+ <RouteProbe /></MemoryRouter>,);}@@ -135,6 +150,68 @@ describe('MediaCollections', () => {expect(screen.getByTitle('Creative Director: Nightly Surreal Landscapes — 2026-08-01')).toBeInTheDocument();});+ it('hydrates the search box, sort, and empty toggle from the URL', async () => {+ renderPage('/media/collections?q=a&sort=name&empty=1');+ await waitFor(() => screen.getByText('Alpha'));+ expect(screen.getByLabelText('Search collections')).toHaveValue('a');+ expect(screen.getByLabelText('Sort collections')).toHaveValue('name');+ expect(screen.getByLabelText('Hide empty')).not.toBeChecked();+ // `q=a` matches Alpha and Beta but not Unsorted, and empty=1 keeps Beta.+ expect(screen.getByText('Beta')).toBeInTheDocument();+ expect(screen.queryByText('Unsorted')).not.toBeInTheDocument();+ });++ it('mirrors the typed query into the URL after the debounce', async () => {+ const user = userEvent.setup();+ renderPage();+ await waitFor(() => screen.getByText('Alpha'));+ await user.type(screen.getByLabelText('Search collections'), 'beta');+ await waitFor(+ () => expect(screen.getByTestId('search-string')).toHaveTextContent('q=beta'),+ { timeout: 3000 },+ );+ });++ it('writes the sort to the URL and drops the param at the default', async () => {+ const user = userEvent.setup();+ renderPage();+ await waitFor(() => screen.getByText('Alpha'));+ await user.selectOptions(screen.getByLabelText('Sort collections'), 'name');+ await waitFor(() => expect(screen.getByTestId('search-string')).toHaveTextContent('sort=name'));+ await user.selectOptions(screen.getByLabelText('Sort collections'), 'updated');+ await waitFor(() => expect(screen.getByTestId('search-string')).not.toHaveTextContent('sort='));+ });++ it('adopts an externally-changed ?q= while the page stays mounted', async () => {+ const user = userEvent.setup();+ renderPage();+ await waitFor(() => screen.getByText('Alpha'));+ await user.click(screen.getByRole('button', { name: 'external nav' }));+ await waitFor(() => expect(screen.getByLabelText('Search collections')).toHaveValue('alpha'));+ });++ it('says every match is empty rather than claiming there was no match', async () => {+ // `beta` matches exactly one collection, which "Hide empty" then removes —+ // reporting "no match" here would send the user hunting for a real record.+ renderPage('/media/collections?q=beta');+ await waitFor(() => screen.getByText(/1 empty collection hidden/));+ expect(screen.getByText(/Every collection here is empty/)).toBeInTheDocument();+ expect(screen.queryByText(/No collections match that search/)).not.toBeInTheDocument();+ });++ it('reveals the empties after creating a collection so the new one is visible', async () => {+ const { createMediaCollection } = await import('../services/api');+ createMediaCollection.mockResolvedValue({ id: 'col-4', name: 'Fresh Bucket', items: [] });+ const user = userEvent.setup();+ renderPage();+ await waitFor(() => screen.getByText('Alpha'));+ await user.type(screen.getByLabelText('New collection name'), 'Fresh Bucket');+ await user.click(screen.getByRole('button', { name: /create/i }));+ // A brand-new collection is always empty; without the reveal it would be+ // filtered straight back out and the create would look like it failed.+ expect(await screen.findByText('Fresh Bucket')).toBeInTheDocument();+ });+it('offers the three sort options', async () => {renderPage();await waitFor(() => screen.getByText('Alpha'));diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex f4eb15fa87..b52288969a 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -398,18 +398,28 @@ export function nameFromImageFilename(filename, fallback = 'Untitled 3D model')* prefix (auto-generated names, dated run labels, deep paths), where clipping* the end collapses every row to the same visible text.* @param {string} value - Source string (non-strings coerce; nullish → '')- * @param {number} [max=48] - Maximum length of the RESULT, ellipsis included+ * @param {number} [max=48] - Maximum length of the RESULT in CODE POINTS, ellipsis included.+ * A non-finite cap returns the string whole rather than discarding it.* @returns {string} `value` when it already fits, else `head…tail`*/export function middleTruncate(value, max = 48) {const str = value == null ? '' : String(value);- // A max that can't fit the ellipsis plus one char on each side has no+ // A cap that isn't a real number can't middle-truncate anything — return the+ // string untouched. (`Math.max(0, NaN)` is NaN, so a naive slice would+ // silently return '' and swallow the value.)+ if (!Number.isFinite(max)) return str;+ const cap = Math.floor(max);+ // Slice on CODE POINTS, not UTF-16 code units: cutting through a surrogate+ // pair (any emoji / astral character) emits a lone surrogate that renders as+ // the replacement glyph.+ const chars = Array.from(str);+ // A cap that can't fit the ellipsis plus one char on each side has no// meaningful middle-truncation; fall back to a plain head slice.- if (!Number.isFinite(max) || max < 3) return str.slice(0, Math.max(0, max));- if (str.length <= max) return str;- const head = Math.ceil((max - 1) / 2);- const tail = max - 1 - head;- return `${str.slice(0, head)}…${str.slice(str.length - tail)}`;+ if (cap < 3) return chars.slice(0, Math.max(0, cap)).join('');+ if (chars.length <= cap) return str;+ const head = Math.ceil((cap - 1) / 2);+ const tail = cap - 1 - head;+ return `${chars.slice(0, head).join('')}…${chars.slice(chars.length - tail).join('')}`;}/**diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.jsindex a3e8c8a5c8..9d0828e6b9 100644--- a/client/src/utils/formatters.test.js+++ b/client/src/utils/formatters.test.js@@ -276,4 +276,29 @@ describe('middleTruncate', () => {expect(middleTruncate('abcdef', 2)).toBe('ab');expect(middleTruncate('abcdef', 0)).toBe('');});++ it('never splits a surrogate pair', () => {+ // Both cut points land inside an astral character; slicing by UTF-16 code+ // unit would emit a lone surrogate that renders as the replacement glyph.+ const out = middleTruncate('AAAAAAAAAAAAAAAA🎬BBBBBBBBBBBB🎬CCCC', 20);+ // Array.from groups a valid pair into one char above 0xFFFF; a LONE+ // surrogate survives as a single char inside the surrogate range.+ const lone = Array.from(out).filter((ch) => {+ const cp = ch.codePointAt(0);+ return cp >= 0xD800 && cp <= 0xDFFF;+ });+ expect(lone).toEqual([]);+ expect(Array.from(out)).toHaveLength(20);+ });++ it('counts the cap in code points, not UTF-16 units', () => {+ // 10 emoji = 20 code units but only 10 code points, so a cap of 10 fits.+ expect(middleTruncate('🎬'.repeat(10), 10)).toBe('🎬'.repeat(10));+ });++ it('returns the string whole for a non-finite cap instead of discarding it', () => {+ expect(middleTruncate('keep me', NaN)).toBe('keep me');+ expect(middleTruncate('keep me', Infinity)).toBe('keep me');+ expect(middleTruncate('keep me', undefined)).toBe('keep me');+ });});